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
PixarAnimationStudios/USD
faed18ce62c8736b02413635b584a2f637156bad
pxr/usdImaging/usdviewq/selectionDataModel.py
python
SelectionDataModel.clearComputedProps
(self)
Clear the computed property selection.
Clear the computed property selection.
[ "Clear", "the", "computed", "property", "selection", "." ]
def clearComputedProps(self): """Clear the computed property selection.""" self._computedPropSelection.clear() self._computedPropSelectionChanged()
[ "def", "clearComputedProps", "(", "self", ")", ":", "self", ".", "_computedPropSelection", ".", "clear", "(", ")", "self", ".", "_computedPropSelectionChanged", "(", ")" ]
https://github.com/PixarAnimationStudios/USD/blob/faed18ce62c8736b02413635b584a2f637156bad/pxr/usdImaging/usdviewq/selectionDataModel.py#L967-L971
rapidsai/cudf
d5b2448fc69f17509304d594f029d0df56984962
python/cudf/cudf/core/column_accessor.py
python
ColumnAccessor.set_by_label
(self, key: Any, value: Any, validate: bool = True)
Add (or modify) column by name. Parameters ---------- key name of the column value : column-like The value to insert into the column. validate : bool If True, the provided value will be coerced to a column and validated before setting (Default value = True).
Add (or modify) column by name.
[ "Add", "(", "or", "modify", ")", "column", "by", "name", "." ]
def set_by_label(self, key: Any, value: Any, validate: bool = True): """ Add (or modify) column by name. Parameters ---------- key name of the column value : column-like The value to insert into the column. validate : bool If True, the provided value will be coerced to a column and validated before setting (Default value = True). """ key = self._pad_key(key) if validate: value = column.as_column(value) if len(self._data) > 0: if len(value) != self._column_length: raise ValueError("All columns must be of equal length") else: self._column_length = len(value) self._data[key] = value self._clear_cache()
[ "def", "set_by_label", "(", "self", ",", "key", ":", "Any", ",", "value", ":", "Any", ",", "validate", ":", "bool", "=", "True", ")", ":", "key", "=", "self", ".", "_pad_key", "(", "key", ")", "if", "validate", ":", "value", "=", "column", ".", "...
https://github.com/rapidsai/cudf/blob/d5b2448fc69f17509304d594f029d0df56984962/python/cudf/cudf/core/column_accessor.py#L371-L395
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/resmokelib/run/__init__.py
python
TestRunner.generate_multiversion_exclude_tags
(self)
Generate multiversion exclude tags file.
Generate multiversion exclude tags file.
[ "Generate", "multiversion", "exclude", "tags", "file", "." ]
def generate_multiversion_exclude_tags(self): """Generate multiversion exclude tags file.""" generate_multiversion_exclude_tags.generate_exclude_yaml( config.MULTIVERSION_BIN_VERSION, config.EXCLUDE_TAGS_FILE_PATH, self._resmoke_logger)
[ "def", "generate_multiversion_exclude_tags", "(", "self", ")", ":", "generate_multiversion_exclude_tags", ".", "generate_exclude_yaml", "(", "config", ".", "MULTIVERSION_BIN_VERSION", ",", "config", ".", "EXCLUDE_TAGS_FILE_PATH", ",", "self", ".", "_resmoke_logger", ")" ]
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/resmokelib/run/__init__.py#L186-L189
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPMT_KEYEDHASH_SCHEME.__init__
(self, details = None)
This structure is used for a hash signing object. Attributes: details (TPMU_SCHEME_KEYEDHASH): The scheme parameters One of: TPMS_SCHEME_HMAC, TPMS_SCHEME_XOR, TPMS_NULL_SCHEME_KEYEDHASH.
This structure is used for a hash signing object.
[ "This", "structure", "is", "used", "for", "a", "hash", "signing", "object", "." ]
def __init__(self, details = None): """ This structure is used for a hash signing object. Attributes: details (TPMU_SCHEME_KEYEDHASH): The scheme parameters One of: TPMS_SCHEME_HMAC, TPMS_SCHEME_XOR, TPMS_NULL_SCHEME_KEYEDHASH. """ self.details = details
[ "def", "__init__", "(", "self", ",", "details", "=", "None", ")", ":", "self", ".", "details", "=", "details" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L6359-L6366
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py
python
_singlefileMailbox.flush
(self)
Write any pending changes to disk.
Write any pending changes to disk.
[ "Write", "any", "pending", "changes", "to", "disk", "." ]
def flush(self): """Write any pending changes to disk.""" if not self._pending: if self._pending_sync: # Messages have only been added, so syncing the file # is enough. _sync_flush(self._file) self._pending_sync = False return # In order to be writing anything out at all, self._toc must # already have been generated (and presumably has been modified # by adding or deleting an item). assert self._toc is not None # Check length of self._file; if it's changed, some other process # has modified the mailbox since we scanned it. self._file.seek(0, 2) cur_len = self._file.tell() if cur_len != self._file_length: raise ExternalClashError('Size of mailbox file changed ' '(expected %i, found %i)' % (self._file_length, cur_len)) new_file = _create_temporary(self._path) try: new_toc = {} self._pre_mailbox_hook(new_file) for key in sorted(self._toc.keys()): start, stop = self._toc[key] self._file.seek(start) self._pre_message_hook(new_file) new_start = new_file.tell() while True: buffer = self._file.read(min(4096, stop - self._file.tell())) if buffer == '': break new_file.write(buffer) new_toc[key] = (new_start, new_file.tell()) self._post_message_hook(new_file) self._file_length = new_file.tell() except: new_file.close() os.remove(new_file.name) raise _sync_close(new_file) # self._file is about to get replaced, so no need to sync. self._file.close() # Make sure the new file's mode is the same as the old file's mode = os.stat(self._path).st_mode os.chmod(new_file.name, mode) try: os.rename(new_file.name, self._path) except OSError, e: if e.errno == errno.EEXIST or \ (os.name == 'os2' and e.errno == errno.EACCES): os.remove(self._path) os.rename(new_file.name, self._path) else: raise self._file = open(self._path, 'rb+') self._toc = new_toc self._pending = False self._pending_sync = False if self._locked: _lock_file(self._file, dotlock=False)
[ "def", "flush", "(", "self", ")", ":", "if", "not", "self", ".", "_pending", ":", "if", "self", ".", "_pending_sync", ":", "# Messages have only been added, so syncing the file", "# is enough.", "_sync_flush", "(", "self", ".", "_file", ")", "self", ".", "_pendi...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/mailbox.py#L634-L700
AMReX-Astro/Castro
5bf85dc1fe41909206d80ff71463f2baad22dab5
Util/scripts/write_probdata.py
python
write_probin
(prob_param_files, cxx_prefix)
write_probin will read through the list of parameter files and C++ header and source files to manage the runtime parameters
write_probin will read through the list of parameter files and C++ header and source files to manage the runtime parameters
[ "write_probin", "will", "read", "through", "the", "list", "of", "parameter", "files", "and", "C", "++", "header", "and", "source", "files", "to", "manage", "the", "runtime", "parameters" ]
def write_probin(prob_param_files, cxx_prefix): """write_probin will read through the list of parameter files and C++ header and source files to manage the runtime parameters""" params = [] print(" ") print(f"write_probdata.py: creating prob_param C++ files") # read the parameters defined in the parameter files for f in prob_param_files: err = parse_param_file(params, f) if err: abort(f"Error parsing {f}") # now handle the C++ -- we need to write a header and a .cpp file # for the parameters cxx_base = os.path.basename(cxx_prefix) ofile = f"{cxx_prefix}_parameters.H" with open(ofile, "w") as fout: fout.write(CXX_HEADER) fout.write(f" void init_{cxx_base}_parameters();\n\n") fout.write(" namespace problem {\n\n") for p in params: if p.dtype == "string": fout.write(f" extern std::string {p.name};\n\n") else: if p.is_array(): if p.size == "nspec": fout.write(f" extern AMREX_GPU_MANAGED {p.get_cxx_decl()} {p.name}[NumSpec];\n\n") else: fout.write(f" extern AMREX_GPU_MANAGED {p.get_cxx_decl()} {p.name}[{p.size}];\n\n") else: fout.write(f" extern AMREX_GPU_MANAGED {p.get_cxx_decl()} {p.name};\n\n") fout.write(" }\n\n") fout.write(CXX_FOOTER) # now the C++ job_info tests ofile = f"{cxx_prefix}_job_info_tests.H" with open(ofile, "w") as fout: for p in params: if not p.is_array(): if p.in_namelist: fout.write(p.get_job_info_test()) # now the C++ initialization routines ofile = f"{cxx_prefix}_parameters.cpp" with open(ofile, "w") as fout: fout.write(f"#include <{cxx_base}_parameters.H>\n") fout.write("#include <AMReX_ParmParse.H>\n") fout.write("#include <AMReX_REAL.H>\n\n") for p in params: if p.dtype == "string": fout.write(f" std::string problem::{p.name};\n\n") else: if p.is_array(): if p.size == "nspec": fout.write(f" AMREX_GPU_MANAGED {p.get_cxx_decl()} problem::{p.name}[NumSpec];\n\n") else: fout.write(f" AMREX_GPU_MANAGED {p.get_cxx_decl()} problem::{p.name}[{p.size}];\n\n") else: fout.write(f" AMREX_GPU_MANAGED {p.get_cxx_decl()} problem::{p.name};\n\n") fout.write("\n") fout.write(f" void init_{cxx_base}_parameters() {{\n") # now write the parmparse code to get the value from the C++ # inputs. This will overwrite the Fortran value. fout.write(" // get the value from the inputs file (this overwrites the Fortran value)\n\n") # open namespace fout.write(" {\n") # we need access to _rt fout.write(" using namespace amrex;\n") fout.write(f" amrex::ParmParse pp(\"problem\");\n\n") for p in params: if p.is_array(): size = p.size if (size == "nspec"): size = "NumSpec" fout.write(f" for (int n = 0; n < {size}; n++) {{\n") fout.write(f" problem::{p.name}[n] = {p.default_format(lang='C++')};\n") fout.write(f" }}\n") else: fout.write(f" {p.get_default_string()}") if p.in_namelist: fout.write(f" {p.get_query_string('C++')}") fout.write("\n") fout.write(" }\n") fout.write(" }\n")
[ "def", "write_probin", "(", "prob_param_files", ",", "cxx_prefix", ")", ":", "params", "=", "[", "]", "print", "(", "\" \"", ")", "print", "(", "f\"write_probdata.py: creating prob_param C++ files\"", ")", "# read the parameters defined in the parameter files", "for", "f"...
https://github.com/AMReX-Astro/Castro/blob/5bf85dc1fe41909206d80ff71463f2baad22dab5/Util/scripts/write_probdata.py#L150-L254
qboticslabs/mastering_ros
d83e78f30acc45b0f18522c1d5fae3a7f52974b9
chapter_10_codes/seven_dof_arm_gazebo/scripts/pick_and_place_working_1.py
python
CokeCanPickAndPlace._pickup
(self, group, target, width)
return True
Pick up a target using the planning group
Pick up a target using the planning group
[ "Pick", "up", "a", "target", "using", "the", "planning", "group" ]
def _pickup(self, group, target, width): """ Pick up a target using the planning group """ # Obtain possible grasps from the grasp generator server: grasps = self._generate_grasps(self._pose_coke_can, width) # Create and send Pickup goal: goal = self._create_pickup_goal(group, target, grasps) state = self._pickup_ac.send_goal_and_wait(goal) if state != GoalStatus.SUCCEEDED: rospy.logerr('Pick up goal failed!: %s' % self._pickup_ac.get_goal_status_text()) return None result = self._pickup_ac.get_result() # Check for error: err = result.error_code.val if err != MoveItErrorCodes.SUCCESS: rospy.logwarn('Group %s cannot pick up target %s!: %s' % (group, target, str(moveit_error_dict[err]))) return False return True
[ "def", "_pickup", "(", "self", ",", "group", ",", "target", ",", "width", ")", ":", "# Obtain possible grasps from the grasp generator server:", "grasps", "=", "self", ".", "_generate_grasps", "(", "self", ".", "_pose_coke_can", ",", "width", ")", "# Create and send...
https://github.com/qboticslabs/mastering_ros/blob/d83e78f30acc45b0f18522c1d5fae3a7f52974b9/chapter_10_codes/seven_dof_arm_gazebo/scripts/pick_and_place_working_1.py#L297-L322
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
DC.MaxX
(*args, **kwargs)
return _gdi_.DC_MaxX(*args, **kwargs)
MaxX(self) -> int Gets the maximum horizontal extent used in drawing commands so far.
MaxX(self) -> int
[ "MaxX", "(", "self", ")", "-", ">", "int" ]
def MaxX(*args, **kwargs): """ MaxX(self) -> int Gets the maximum horizontal extent used in drawing commands so far. """ return _gdi_.DC_MaxX(*args, **kwargs)
[ "def", "MaxX", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_MaxX", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L4676-L4682
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/mailbox.py
python
_singlefileMailbox._post_message_hook
(self, f)
return
Called after writing each message to file f.
Called after writing each message to file f.
[ "Called", "after", "writing", "each", "message", "to", "file", "f", "." ]
def _post_message_hook(self, f): """Called after writing each message to file f.""" return
[ "def", "_post_message_hook", "(", "self", ",", "f", ")", ":", "return" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/mailbox.py#L640-L642
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/skia_gold_common/skia_gold_session.py
python
SkiaGoldSession.Initialize
(self)
return rc, stdout
Initializes the working directory if necessary. This can technically be skipped if the same information is passed to the command used for image comparison, but that is less efficient under the hood. Doing it that way effectively requires an initialization for every comparison (~250 ms) instead of once at the beginning. Returns: A tuple (return_code, output). |return_code| is the return code of the initialization process. |output| is the stdout + stderr of the initialization process.
Initializes the working directory if necessary.
[ "Initializes", "the", "working", "directory", "if", "necessary", "." ]
def Initialize(self): """Initializes the working directory if necessary. This can technically be skipped if the same information is passed to the command used for image comparison, but that is less efficient under the hood. Doing it that way effectively requires an initialization for every comparison (~250 ms) instead of once at the beginning. Returns: A tuple (return_code, output). |return_code| is the return code of the initialization process. |output| is the stdout + stderr of the initialization process. """ if self._initialized: return 0, None if self._gold_properties.bypass_skia_gold_functionality: logging.warning('Not actually initializing Gold due to ' '--bypass-skia-gold-functionality being present.') return 0, None init_cmd = [ GOLDCTL_BINARY, 'imgtest', 'init', '--passfail', '--instance', self._instance, '--corpus', self._corpus, '--keys-file', self._keys_file, '--work-dir', self._working_dir, '--failure-file', self._triage_link_file, '--commit', self._gold_properties.git_revision, ] if self._bucket: init_cmd.extend(['--bucket', self._bucket]) if self._gold_properties.IsTryjobRun(): init_cmd.extend([ '--issue', str(self._gold_properties.issue), '--patchset', str(self._gold_properties.patchset), '--jobid', str(self._gold_properties.job_id), '--crs', str(self._gold_properties.code_review_system), '--cis', str(self._gold_properties.continuous_integration_system), ]) rc, stdout = self._RunCmdForRcAndOutput(init_cmd) if rc == 0: self._initialized = True return rc, stdout
[ "def", "Initialize", "(", "self", ")", ":", "if", "self", ".", "_initialized", ":", "return", "0", ",", "None", "if", "self", ".", "_gold_properties", ".", "bypass_skia_gold_functionality", ":", "logging", ".", "warning", "(", "'Not actually initializing Gold due ...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/skia_gold_common/skia_gold_session.py#L194-L251
google-ar/WebARonTango
e86965d2cbc652156b480e0fcf77c716745578cd
chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py
python
ImmediateFunction.WriteCmdInit
(self, f)
Overridden from Function
Overridden from Function
[ "Overridden", "from", "Function" ]
def WriteCmdInit(self, f): """Overridden from Function""" self.type_handler.WriteImmediateCmdInit(self, f)
[ "def", "WriteCmdInit", "(", "self", ",", "f", ")", ":", "self", ".", "type_handler", ".", "WriteImmediateCmdInit", "(", "self", ",", "f", ")" ]
https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L9767-L9769
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Build.py
python
BuildContext.get_variant_dir
(self)
return os.path.join(self.out_dir, self.variant)
Getter for the variant_dir attribute
Getter for the variant_dir attribute
[ "Getter", "for", "the", "variant_dir", "attribute" ]
def get_variant_dir(self): """Getter for the variant_dir attribute""" if not self.variant: return self.out_dir return os.path.join(self.out_dir, self.variant)
[ "def", "get_variant_dir", "(", "self", ")", ":", "if", "not", "self", ".", "variant", ":", "return", "self", ".", "out_dir", "return", "os", ".", "path", ".", "join", "(", "self", ".", "out_dir", ",", "self", ".", "variant", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Build.py#L128-L132
apache/impala
8ddac48f3428c86f2cbd037ced89cfb903298b12
shell/shell_output.py
python
DelimitedOutputFormatter.format
(self, rows)
return rows
Returns string containing UTF-8-encoded representation of the table data.
Returns string containing UTF-8-encoded representation of the table data.
[ "Returns", "string", "containing", "UTF", "-", "8", "-", "encoded", "representation", "of", "the", "table", "data", "." ]
def format(self, rows): """Returns string containing UTF-8-encoded representation of the table data.""" # csv.writer expects a file handle to the input. temp_buffer = StringIO() if sys.version_info.major == 2: # csv.writer in python2 requires an ascii string delimiter delim = self.field_delim.encode('ascii', 'ignore') else: delim = self.field_delim writer = csv.writer(temp_buffer, delimiter=delim, lineterminator='\n', quoting=csv.QUOTE_MINIMAL) for row in rows: if sys.version_info.major == 2: row = [val.encode('utf-8', 'replace') if isinstance(val, unicode) else val for val in row] writer.writerow(row) rows = temp_buffer.getvalue().rstrip() temp_buffer.close() return rows
[ "def", "format", "(", "self", ",", "rows", ")", ":", "# csv.writer expects a file handle to the input.", "temp_buffer", "=", "StringIO", "(", ")", "if", "sys", ".", "version_info", ".", "major", "==", "2", ":", "# csv.writer in python2 requires an ascii string delimiter...
https://github.com/apache/impala/blob/8ddac48f3428c86f2cbd037ced89cfb903298b12/shell/shell_output.py#L77-L95
lagadic/visp
e14e125ccc2d7cf38f3353efa01187ef782fbd0b
modules/java/generator/gen_java.py
python
JavaWrapperGenerator.isSmartClass
(self, ci)
return ci.smart
Check if class stores Ptr<T>* instead of T* in nativeObj field
Check if class stores Ptr<T>* instead of T* in nativeObj field
[ "Check", "if", "class", "stores", "Ptr<T", ">", "*", "instead", "of", "T", "*", "in", "nativeObj", "field" ]
def isSmartClass(self, ci): ''' Check if class stores Ptr<T>* instead of T* in nativeObj field ''' if ci.smart != None: return ci.smart # if parents are smart (we hope) then children are! # if not we believe the class is smart if it has "create" method ci.smart = False if ci.base or ci.name == 'Algorithm': ci.smart = True else: for fi in ci.methods: if fi.name == "create": ci.smart = True break return ci.smart
[ "def", "isSmartClass", "(", "self", ",", "ci", ")", ":", "if", "ci", ".", "smart", "!=", "None", ":", "return", "ci", ".", "smart", "# if parents are smart (we hope) then children are!", "# if not we believe the class is smart if it has \"create\" method", "ci", ".", "s...
https://github.com/lagadic/visp/blob/e14e125ccc2d7cf38f3353efa01187ef782fbd0b/modules/java/generator/gen_java.py#L1184-L1202
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/framework/ops.py
python
Tensor.eval
(self, feed_dict=None, session=None)
return _eval_using_default_session(self, feed_dict, self.graph, session)
Evaluates this tensor in a `Session`. Calling this method will execute all preceding operations that produce the inputs needed for the operation that produces this tensor. *N.B.* Before invoking `Tensor.eval()`, its graph must have been launched in a session, and either a default session must be available, or `session` must be specified explicitly. Args: feed_dict: A dictionary that maps `Tensor` objects to feed values. See [`Session.run()`](../../api_docs/python/client.md#Session.run) for a description of the valid feed values. session: (Optional.) The `Session` to be used to evaluate this tensor. If none, the default session will be used. Returns: A numpy array corresponding to the value of this tensor.
Evaluates this tensor in a `Session`.
[ "Evaluates", "this", "tensor", "in", "a", "Session", "." ]
def eval(self, feed_dict=None, session=None): """Evaluates this tensor in a `Session`. Calling this method will execute all preceding operations that produce the inputs needed for the operation that produces this tensor. *N.B.* Before invoking `Tensor.eval()`, its graph must have been launched in a session, and either a default session must be available, or `session` must be specified explicitly. Args: feed_dict: A dictionary that maps `Tensor` objects to feed values. See [`Session.run()`](../../api_docs/python/client.md#Session.run) for a description of the valid feed values. session: (Optional.) The `Session` to be used to evaluate this tensor. If none, the default session will be used. Returns: A numpy array corresponding to the value of this tensor. """ return _eval_using_default_session(self, feed_dict, self.graph, session)
[ "def", "eval", "(", "self", ",", "feed_dict", "=", "None", ",", "session", "=", "None", ")", ":", "return", "_eval_using_default_session", "(", "self", ",", "feed_dict", ",", "self", ".", "graph", ",", "session", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/ops.py#L537-L559
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/models.py
python
Response.links
(self)
return l
Returns the parsed header links of the response, if any.
Returns the parsed header links of the response, if any.
[ "Returns", "the", "parsed", "header", "links", "of", "the", "response", "if", "any", "." ]
def links(self): """Returns the parsed header links of the response, if any.""" header = self.headers.get('link') # l = MultiDict() l = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel') or link.get('url') l[key] = link return l
[ "def", "links", "(", "self", ")", ":", "header", "=", "self", ".", "headers", ".", "get", "(", "'link'", ")", "# l = MultiDict()", "l", "=", "{", "}", "if", "header", ":", "links", "=", "parse_header_links", "(", "header", ")", "for", "link", "in", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/requests/models.py#L901-L916
Slicer/Slicer
ba9fadf332cb0303515b68d8d06a344c82e3e3e5
Utilities/Templates/Modules/ScriptedSegmentEditorEffect/SegmentEditorTemplateKey.py
python
SegmentEditorTemplateKeyTest.setUp
(self)
Do whatever is needed to reset the state - typically a scene clear will be enough.
Do whatever is needed to reset the state - typically a scene clear will be enough.
[ "Do", "whatever", "is", "needed", "to", "reset", "the", "state", "-", "typically", "a", "scene", "clear", "will", "be", "enough", "." ]
def setUp(self): """ Do whatever is needed to reset the state - typically a scene clear will be enough. """ slicer.mrmlScene.Clear(0)
[ "def", "setUp", "(", "self", ")", ":", "slicer", ".", "mrmlScene", ".", "Clear", "(", "0", ")" ]
https://github.com/Slicer/Slicer/blob/ba9fadf332cb0303515b68d8d06a344c82e3e3e5/Utilities/Templates/Modules/ScriptedSegmentEditorEffect/SegmentEditorTemplateKey.py#L39-L42
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/learn/python/learn/preprocessing/categorical_vocabulary.py
python
CategoricalVocabulary.reverse
(self, class_id)
return self._reverse_mapping[class_id]
Given class id reverse to original class name. Args: class_id: Id of the class. Returns: Class name. Raises: ValueError: if this vocabulary wasn't initalized with support_reverse.
Given class id reverse to original class name.
[ "Given", "class", "id", "reverse", "to", "original", "class", "name", "." ]
def reverse(self, class_id): """Given class id reverse to original class name. Args: class_id: Id of the class. Returns: Class name. Raises: ValueError: if this vocabulary wasn't initalized with support_reverse. """ if not self._support_reverse: raise ValueError("This vocabulary wasn't initalized with " "support_reverse to support reverse() function.") return self._reverse_mapping[class_id]
[ "def", "reverse", "(", "self", ",", "class_id", ")", ":", "if", "not", "self", ".", "_support_reverse", ":", "raise", "ValueError", "(", "\"This vocabulary wasn't initalized with \"", "\"support_reverse to support reverse() function.\"", ")", "return", "self", ".", "_re...
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/learn/python/learn/preprocessing/categorical_vocabulary.py#L121-L136
tiny-dnn/tiny-dnn
c0f576f5cb7b35893f62127cb7aec18f77a3bcc5
third_party/gemmlowp/meta/generators/gemm_MxNxK.py
python
GenerateFullTempsCountersAndConsts
(emitter, result_type, rows)
Generates all the boilerplate variables for the int32 and float gemms.
Generates all the boilerplate variables for the int32 and float gemms.
[ "Generates", "all", "the", "boilerplate", "variables", "for", "the", "int32", "and", "float", "gemms", "." ]
def GenerateFullTempsCountersAndConsts(emitter, result_type, rows): """Generates all the boilerplate variables for the int32 and float gemms.""" GenerateCommonTempsCountersAndConsts(emitter, rows) emitter.EmitDeclare('const std::int32_t', 'const_offset', 'lhs_offset * rhs_offset * k') emitter.EmitDeclare(result_type, 'result_chunk', 'result') emitter.EmitDeclare(result_type, 'mul_result_chunk', 'result') emitter.EmitDeclare('const std::int32_t', 'mul_result_chunk_stride_bytes', 'result_stride * 4') emitter.EmitNewline()
[ "def", "GenerateFullTempsCountersAndConsts", "(", "emitter", ",", "result_type", ",", "rows", ")", ":", "GenerateCommonTempsCountersAndConsts", "(", "emitter", ",", "rows", ")", "emitter", ".", "EmitDeclare", "(", "'const std::int32_t'", ",", "'const_offset'", ",", "'...
https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/third_party/gemmlowp/meta/generators/gemm_MxNxK.py#L65-L74
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Util.py
python
flatten
(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten)
return result
Flatten a sequence to a non-nested list. Flatten() converts either a single scalar or a nested sequence to a non-nested list. Note that flatten() considers strings to be scalars instead of sequences like Python would.
Flatten a sequence to a non-nested list.
[ "Flatten", "a", "sequence", "to", "a", "non", "-", "nested", "list", "." ]
def flatten(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes, do_flatten=do_flatten): """Flatten a sequence to a non-nested list. Flatten() converts either a single scalar or a nested sequence to a non-nested list. Note that flatten() considers strings to be scalars instead of sequences like Python would. """ if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes): return [obj] result = [] for item in obj: if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes): result.append(item) else: do_flatten(item, result) return result
[ "def", "flatten", "(", "obj", ",", "isinstance", "=", "isinstance", ",", "StringTypes", "=", "StringTypes", ",", "SequenceTypes", "=", "SequenceTypes", ",", "do_flatten", "=", "do_flatten", ")", ":", "if", "isinstance", "(", "obj", ",", "StringTypes", ")", "...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/src/third_party/scons-3.1.2/scons-local-3.1.2/SCons/Util.py#L427-L443
tiny-dnn/tiny-dnn
c0f576f5cb7b35893f62127cb7aec18f77a3bcc5
third_party/cpplint.py
python
NestingState.UpdatePreprocessor
(self, line)
Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check.
Update preprocessor stack.
[ "Update", "preprocessor", "stack", "." ]
def UpdatePreprocessor(self, line): """Update preprocessor stack. We need to handle preprocessors due to classes like this: #ifdef SWIG struct ResultDetailsPageElementExtensionPoint { #else struct ResultDetailsPageElementExtensionPoint : public Extension { #endif We make the following assumptions (good enough for most files): - Preprocessor condition evaluates to true from #if up to first #else/#elif/#endif. - Preprocessor condition evaluates to false from #else/#elif up to #endif. We still perform lint checks on these lines, but these do not affect nesting stack. Args: line: current line to check. """ if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): # Beginning of #if block, save the nesting stack here. The saved # stack will allow us to restore the parsing state in the #else case. self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) elif Match(r'^\s*#\s*(else|elif)\b', line): # Beginning of #else block if self.pp_stack: if not self.pp_stack[-1].seen_else: # This is the first #else or #elif block. Remember the # whole nesting stack up to this point. This is what we # keep after the #endif. self.pp_stack[-1].seen_else = True self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) # Restore the stack to how it was before the #if self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) else: # TODO(unknown): unexpected #else, issue warning? pass elif Match(r'^\s*#\s*endif\b', line): # End of #if or #else blocks. if self.pp_stack: # If we saw an #else, we will need to restore the nesting # stack to its former state before the #else, otherwise we # will just continue from where we left off. if self.pp_stack[-1].seen_else: # Here we can just use a shallow copy since we are the last # reference to it. self.stack = self.pp_stack[-1].stack_before_else # Drop the corresponding #if self.pp_stack.pop() else: # TODO(unknown): unexpected #endif, issue warning? pass
[ "def", "UpdatePreprocessor", "(", "self", ",", "line", ")", ":", "if", "Match", "(", "r'^\\s*#\\s*(if|ifdef|ifndef)\\b'", ",", "line", ")", ":", "# Beginning of #if block, save the nesting stack here. The saved", "# stack will allow us to restore the parsing state in the #else cas...
https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/third_party/cpplint.py#L2633-L2687
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
PrintDialogData.GetFromPage
(*args, **kwargs)
return _windows_.PrintDialogData_GetFromPage(*args, **kwargs)
GetFromPage(self) -> int
GetFromPage(self) -> int
[ "GetFromPage", "(", "self", ")", "-", ">", "int" ]
def GetFromPage(*args, **kwargs): """GetFromPage(self) -> int""" return _windows_.PrintDialogData_GetFromPage(*args, **kwargs)
[ "def", "GetFromPage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PrintDialogData_GetFromPage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L5042-L5044
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/pydoc.py
python
Doc.document
(self, object, name=None, *args)
return self.docother(*args)
Generate documentation for an object.
Generate documentation for an object.
[ "Generate", "documentation", "for", "an", "object", "." ]
def document(self, object, name=None, *args): """Generate documentation for an object.""" args = (object, name) + args # 'try' clause is to attempt to handle the possibility that inspect # identifies something in a way that pydoc itself has issues handling; # think 'super' and how it is a descriptor (which raises the exception # by lacking a __name__ attribute) and an instance. try: if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): return self.docclass(*args) if inspect.isroutine(object): return self.docroutine(*args) except AttributeError: pass if inspect.isdatadescriptor(object): return self.docdata(*args) return self.docother(*args)
[ "def", "document", "(", "self", ",", "object", ",", "name", "=", "None", ",", "*", "args", ")", ":", "args", "=", "(", "object", ",", "name", ")", "+", "args", "# 'try' clause is to attempt to handle the possibility that inspect", "# identifies something in a way th...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/pydoc.py#L464-L478
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/xml/sax/xmlreader.py
python
XMLReader.getContentHandler
(self)
return self._cont_handler
Returns the current ContentHandler.
Returns the current ContentHandler.
[ "Returns", "the", "current", "ContentHandler", "." ]
def getContentHandler(self): "Returns the current ContentHandler." return self._cont_handler
[ "def", "getContentHandler", "(", "self", ")", ":", "return", "self", ".", "_cont_handler" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/xml/sax/xmlreader.py#L34-L36
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/toolkits/evaluation.py
python
recall
(targets, predictions, average="macro")
return _turicreate.extensions._supervised_streaming_evaluator( targets, predictions, "recall", opts )
r""" Compute the recall score for classification tasks. The recall score quantifies the ability of a classifier to predict `positive` examples. Recall can be interpreted as the probability that a randomly selected `positive` example is correctly identified by the classifier. The score is in the range [0,1] with 0 being the worst, and 1 being perfect. The recall score is defined as the ratio: .. math:: \frac{tp}{tp + fn} where `tp` is the number of true positives and `fn` the number of false negatives. Parameters ---------- targets : SArray Ground truth class labels. The SArray can be of any type. predictions : SArray The prediction that corresponds to each target value. This SArray must have the same length as ``targets`` and must be of the same type as the ``targets`` SArray. average : string, [None, 'macro' (default), 'micro'] Metric averaging strategies for multiclass classification. Averaging strategies can be one of the following: - None: No averaging is performed and a single metric is returned for each class. - 'micro': Calculate metrics globally by counting the total true positives, false negatives, and false positives. - 'macro': Calculate metrics for each label and find their unweighted mean. This does not take label imbalance into account. Returns ------- out : float (for binary classification) or dict[float] Score for the positive class (for binary classification) or an average score for each class for multi-class classification. If `average=None`, then a dictionary is returned where the key is the class label and the value is the score for the corresponding class label. Notes ----- - For binary classification, when the target label is of type "string", then the labels are sorted alphanumerically and the largest label is chosen as the "positive" label. For example, if the classifier labels are {"cat", "dog"}, then "dog" is chosen as the positive label for the binary classification case. See Also -------- confusion_matrix, accuracy, precision, f1_score Examples -------- .. sourcecode:: python # Targets and Predictions >>> targets = turicreate.SArray([0, 1, 2, 3, 0, 1, 2, 3]) >>> predictions = turicreate.SArray([1, 0, 2, 1, 3, 1, 2, 1]) # Micro average of the recall scores for each class. >>> turicreate.evaluation.recall(targets, predictions, ... average = 'micro') 0.375 # Macro average of the recall scores for each class. >>> turicreate.evaluation.recall(targets, predictions, ... average = 'macro') 0.375 # Recall score for each class. >>> turicreate.evaluation.recall(targets, predictions, ... average = None) {0: 0.0, 1: 0.5, 2: 1.0, 3: 0.0} This metric also works for string classes. .. sourcecode:: python # Targets and Predictions >>> targets = turicreate.SArray( ... ["cat", "dog", "foosa", "snake", "cat", "dog", "foosa", "snake"]) >>> predictions = turicreate.SArray( ... ["dog", "cat", "foosa", "dog", "snake", "dog", "cat", "dog"]) # Micro average of the recall scores for each class. >>> turicreate.evaluation.recall(targets, predictions, ... average = 'micro') 0.375 # Macro average of the recall scores for each class. >>> turicreate.evaluation.recall(targets, predictions, ... average = 'macro') 0.375 # Recall score for each class. >>> turicreate.evaluation.recall(targets, predictions, ... average = None) {0: 0.0, 1: 0.5, 2: 1.0, 3: 0.0}
r""" Compute the recall score for classification tasks. The recall score quantifies the ability of a classifier to predict `positive` examples. Recall can be interpreted as the probability that a randomly selected `positive` example is correctly identified by the classifier. The score is in the range [0,1] with 0 being the worst, and 1 being perfect.
[ "r", "Compute", "the", "recall", "score", "for", "classification", "tasks", ".", "The", "recall", "score", "quantifies", "the", "ability", "of", "a", "classifier", "to", "predict", "positive", "examples", ".", "Recall", "can", "be", "interpreted", "as", "the",...
def recall(targets, predictions, average="macro"): r""" Compute the recall score for classification tasks. The recall score quantifies the ability of a classifier to predict `positive` examples. Recall can be interpreted as the probability that a randomly selected `positive` example is correctly identified by the classifier. The score is in the range [0,1] with 0 being the worst, and 1 being perfect. The recall score is defined as the ratio: .. math:: \frac{tp}{tp + fn} where `tp` is the number of true positives and `fn` the number of false negatives. Parameters ---------- targets : SArray Ground truth class labels. The SArray can be of any type. predictions : SArray The prediction that corresponds to each target value. This SArray must have the same length as ``targets`` and must be of the same type as the ``targets`` SArray. average : string, [None, 'macro' (default), 'micro'] Metric averaging strategies for multiclass classification. Averaging strategies can be one of the following: - None: No averaging is performed and a single metric is returned for each class. - 'micro': Calculate metrics globally by counting the total true positives, false negatives, and false positives. - 'macro': Calculate metrics for each label and find their unweighted mean. This does not take label imbalance into account. Returns ------- out : float (for binary classification) or dict[float] Score for the positive class (for binary classification) or an average score for each class for multi-class classification. If `average=None`, then a dictionary is returned where the key is the class label and the value is the score for the corresponding class label. Notes ----- - For binary classification, when the target label is of type "string", then the labels are sorted alphanumerically and the largest label is chosen as the "positive" label. For example, if the classifier labels are {"cat", "dog"}, then "dog" is chosen as the positive label for the binary classification case. See Also -------- confusion_matrix, accuracy, precision, f1_score Examples -------- .. sourcecode:: python # Targets and Predictions >>> targets = turicreate.SArray([0, 1, 2, 3, 0, 1, 2, 3]) >>> predictions = turicreate.SArray([1, 0, 2, 1, 3, 1, 2, 1]) # Micro average of the recall scores for each class. >>> turicreate.evaluation.recall(targets, predictions, ... average = 'micro') 0.375 # Macro average of the recall scores for each class. >>> turicreate.evaluation.recall(targets, predictions, ... average = 'macro') 0.375 # Recall score for each class. >>> turicreate.evaluation.recall(targets, predictions, ... average = None) {0: 0.0, 1: 0.5, 2: 1.0, 3: 0.0} This metric also works for string classes. .. sourcecode:: python # Targets and Predictions >>> targets = turicreate.SArray( ... ["cat", "dog", "foosa", "snake", "cat", "dog", "foosa", "snake"]) >>> predictions = turicreate.SArray( ... ["dog", "cat", "foosa", "dog", "snake", "dog", "cat", "dog"]) # Micro average of the recall scores for each class. >>> turicreate.evaluation.recall(targets, predictions, ... average = 'micro') 0.375 # Macro average of the recall scores for each class. >>> turicreate.evaluation.recall(targets, predictions, ... average = 'macro') 0.375 # Recall score for each class. >>> turicreate.evaluation.recall(targets, predictions, ... average = None) {0: 0.0, 1: 0.5, 2: 1.0, 3: 0.0} """ _supervised_evaluation_error_checking(targets, predictions) _check_categorical_option_type("average", average, ["micro", "macro", None]) _check_same_type_not_float(targets, predictions) opts = {"average": average} return _turicreate.extensions._supervised_streaming_evaluator( targets, predictions, "recall", opts )
[ "def", "recall", "(", "targets", ",", "predictions", ",", "average", "=", "\"macro\"", ")", ":", "_supervised_evaluation_error_checking", "(", "targets", ",", "predictions", ")", "_check_categorical_option_type", "(", "\"average\"", ",", "average", ",", "[", "\"micr...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/toolkits/evaluation.py#L869-L982
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/composite/multitype_ops/setitem_impl.py
python
_tensor_setitem_by_none_with_tensor
(data, index, value)
return compile_utils.tensor_setitem_by_ellipsis_with_tensor(data, value)
Tensor assignment. Note: Syntax support: A[...] = u Restraint condition: A is a Tensor. u is a Tensor. Inputs: data (Tensor): Assigned tensor. index (None): Index is ``...``. value (Tensor): Assignment value. Outputs: Tensor, element type and shape is same as data.
Tensor assignment.
[ "Tensor", "assignment", "." ]
def _tensor_setitem_by_none_with_tensor(data, index, value): """ Tensor assignment. Note: Syntax support: A[...] = u Restraint condition: A is a Tensor. u is a Tensor. Inputs: data (Tensor): Assigned tensor. index (None): Index is ``...``. value (Tensor): Assignment value. Outputs: Tensor, element type and shape is same as data. """ return compile_utils.tensor_setitem_by_ellipsis_with_tensor(data, value)
[ "def", "_tensor_setitem_by_none_with_tensor", "(", "data", ",", "index", ",", "value", ")", ":", "return", "compile_utils", ".", "tensor_setitem_by_ellipsis_with_tensor", "(", "data", ",", "value", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/composite/multitype_ops/setitem_impl.py#L598-L614
intel/caffe
3f494b442ee3f9d17a07b09ecbd5fa2bbda00836
scripts/cpp_lint.py
python
CheckIncludeLine
(filename, clean_lines, linenum, include_state, error)
Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found.
Check rules that are applicable to #include lines.
[ "Check", "rules", "that", "are", "applicable", "to", "#include", "lines", "." ]
def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): """Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found. """ fileinfo = FileInfo(filename) line = clean_lines.lines[linenum] # "include" should use the new style "foo/bar.h" instead of just "bar.h" if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line): error(filename, linenum, 'build/include_dir', 4, 'Include the directory when naming .h files') # we shouldn't include a file more than once. actually, there are a # handful of instances where doing so is okay, but in general it's # not. match = _RE_PATTERN_INCLUDE.search(line) if match: include = match.group(2) is_system = (match.group(1) == '<') if include in include_state: error(filename, linenum, 'build/include', 4, '"%s" already included at %s:%s' % (include, filename, include_state[include])) else: include_state[include] = linenum # We want to ensure that headers appear in the right order: # 1) for foo.cc, foo.h (preferred location) # 2) c system files # 3) cpp system files # 4) for foo.cc, foo.h (deprecated location) # 5) other google headers # # We classify each include statement as one of those 5 types # using a number of techniques. The include_state object keeps # track of the highest type seen, and complains if we see a # lower type after that. error_message = include_state.CheckNextIncludeOrder( _ClassifyInclude(fileinfo, include, is_system)) if error_message: error(filename, linenum, 'build/include_order', 4, '%s. Should be: %s.h, c system, c++ system, other.' % (error_message, fileinfo.BaseName())) canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) if not include_state.IsInAlphabeticalOrder( clean_lines, linenum, canonical_include): error(filename, linenum, 'build/include_alpha', 4, 'Include "%s" not in alphabetical order' % include) include_state.SetLastHeader(canonical_include) # Look for any of the stream classes that are part of standard C++. match = _RE_PATTERN_INCLUDE.match(line) if match: include = match.group(2) if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include): # Many unit tests use cout, so we exempt them. if not _IsTestFilename(filename): error(filename, linenum, 'readability/streams', 3, 'Streams are highly discouraged.')
[ "def", "CheckIncludeLine", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "include_state", ",", "error", ")", ":", "fileinfo", "=", "FileInfo", "(", "filename", ")", "line", "=", "clean_lines", ".", "lines", "[", "linenum", "]", "# \"include\" shoul...
https://github.com/intel/caffe/blob/3f494b442ee3f9d17a07b09ecbd5fa2bbda00836/scripts/cpp_lint.py#L3684-L3753
psnonis/FinBERT
c0c555d833a14e2316a3701e59c0b5156f804b4e
bert-gpu/run_classifier_with_tfhub.py
python
create_model
(is_training, input_ids, input_mask, segment_ids, labels, num_labels, bert_hub_module_handle)
Creates a classification model.
Creates a classification model.
[ "Creates", "a", "classification", "model", "." ]
def create_model(is_training, input_ids, input_mask, segment_ids, labels, num_labels, bert_hub_module_handle): """Creates a classification model.""" tags = set() if is_training: tags.add("train") bert_module = hub.Module(bert_hub_module_handle, tags=tags, trainable=True) bert_inputs = dict( input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids) bert_outputs = bert_module( inputs=bert_inputs, signature="tokens", as_dict=True) # In the demo, we are doing a simple classification task on the entire # segment. # # If you want to use the token-level output, use # bert_outputs["sequence_output"] instead. output_layer = bert_outputs["pooled_output"] hidden_size = output_layer.shape[-1].value output_weights = tf.get_variable( "output_weights", [num_labels, hidden_size], initializer=tf.truncated_normal_initializer(stddev=0.02)) output_bias = tf.get_variable( "output_bias", [num_labels], initializer=tf.zeros_initializer()) with tf.variable_scope("loss"): if is_training: # I.e., 0.1 dropout output_layer = tf.nn.dropout(output_layer, keep_prob=0.9) logits = tf.matmul(output_layer, output_weights, transpose_b=True) logits = tf.nn.bias_add(logits, output_bias) probabilities = tf.nn.softmax(logits, axis=-1) log_probs = tf.nn.log_softmax(logits, axis=-1) one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32) per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1) loss = tf.reduce_mean(per_example_loss) return (loss, per_example_loss, logits, probabilities)
[ "def", "create_model", "(", "is_training", ",", "input_ids", ",", "input_mask", ",", "segment_ids", ",", "labels", ",", "num_labels", ",", "bert_hub_module_handle", ")", ":", "tags", "=", "set", "(", ")", "if", "is_training", ":", "tags", ".", "add", "(", ...
https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/run_classifier_with_tfhub.py#L37-L84
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/base/android/jni_generator/jni_registration_generator.py
python
HeaderGenerator._AddRegisterNativesFunctions
(self)
Returns the code for RegisterNatives.
Returns the code for RegisterNatives.
[ "Returns", "the", "code", "for", "RegisterNatives", "." ]
def _AddRegisterNativesFunctions(self): """Returns the code for RegisterNatives.""" natives = self._GetRegisterNativesImplString() if not natives: return '' template = string.Template("""\ JNI_REGISTRATION_EXPORT bool ${REGISTER_NAME}(JNIEnv* env) { ${NATIVES}\ return true; } """) values = { 'REGISTER_NAME': jni_generator.GetRegistrationFunctionName(self.fully_qualified_class), 'NATIVES': natives } self._SetDictValue('JNI_NATIVE_METHOD', template.substitute(values))
[ "def", "_AddRegisterNativesFunctions", "(", "self", ")", ":", "natives", "=", "self", ".", "_GetRegisterNativesImplString", "(", ")", "if", "not", "natives", ":", "return", "''", "template", "=", "string", ".", "Template", "(", "\"\"\"\\\nJNI_REGISTRATION_EXPORT boo...
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/base/android/jni_generator/jni_registration_generator.py#L498-L516
doyubkim/fluid-engine-dev
45b4bdbdb4c6d8c0beebc682180469198203b0ef
scripts/utils.py
python
is_linux
()
return guess_os() == 'linux'
Returns True if you are using Linux.
Returns True if you are using Linux.
[ "Returns", "True", "if", "you", "are", "using", "Linux", "." ]
def is_linux(): """ Returns True if you are using Linux. """ return guess_os() == 'linux'
[ "def", "is_linux", "(", ")", ":", "return", "guess_os", "(", ")", "==", "'linux'" ]
https://github.com/doyubkim/fluid-engine-dev/blob/45b4bdbdb4c6d8c0beebc682180469198203b0ef/scripts/utils.py#L148-L152
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/os.py
python
execlpe
(file, *args)
execlpe(file, *args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current process.
execlpe(file, *args, env)
[ "execlpe", "(", "file", "*", "args", "env", ")" ]
def execlpe(file, *args): """execlpe(file, *args, env) Execute the executable file (which is searched for along $PATH) with argument list args and environment env, replacing the current process. """ env = args[-1] execvpe(file, args[:-1], env)
[ "def", "execlpe", "(", "file", ",", "*", "args", ")", ":", "env", "=", "args", "[", "-", "1", "]", "execvpe", "(", "file", ",", "args", "[", ":", "-", "1", "]", ",", "env", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/os.py#L331-L338
BitMEX/api-connectors
37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812
auto-generated/python/swagger_client/models/trade_bin.py
python
TradeBin.trades
(self, trades)
Sets the trades of this TradeBin. :param trades: The trades of this TradeBin. # noqa: E501 :type: float
Sets the trades of this TradeBin.
[ "Sets", "the", "trades", "of", "this", "TradeBin", "." ]
def trades(self, trades): """Sets the trades of this TradeBin. :param trades: The trades of this TradeBin. # noqa: E501 :type: float """ self._trades = trades
[ "def", "trades", "(", "self", ",", "trades", ")", ":", "self", ".", "_trades", "=", "trades" ]
https://github.com/BitMEX/api-connectors/blob/37a3a5b806ad5d0e0fc975ab86d9ed43c3bcd812/auto-generated/python/swagger_client/models/trade_bin.py#L249-L257
verilog-to-routing/vtr-verilog-to-routing
d9719cf7374821156c3cee31d66991cb85578562
vtr_flow/scripts/python_libs/vtr/task.py
python
Job.circuit
(self)
return self._circuit
return the circuit file name of the job
return the circuit file name of the job
[ "return", "the", "circuit", "file", "name", "of", "the", "job" ]
def circuit(self): """ return the circuit file name of the job """ return self._circuit
[ "def", "circuit", "(", "self", ")", ":", "return", "self", ".", "_circuit" ]
https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/python_libs/vtr/task.py#L120-L124
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/series.py
python
Series.__matmul__
(self, other)
return self.dot(other)
Matrix multiplication using binary `@` operator in Python>=3.5.
Matrix multiplication using binary `
[ "Matrix", "multiplication", "using", "binary" ]
def __matmul__(self, other): """ Matrix multiplication using binary `@` operator in Python>=3.5. """ return self.dot(other)
[ "def", "__matmul__", "(", "self", ",", "other", ")", ":", "return", "self", ".", "dot", "(", "other", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/series.py#L2484-L2488
gnina/gnina
b9ae032f52fc7a8153987bde09c0efa3620d8bb6
caffe/scripts/cpp_lint.py
python
ResetNolintSuppressions
()
Resets the set of NOLINT suppressions to empty.
Resets the set of NOLINT suppressions to empty.
[ "Resets", "the", "set", "of", "NOLINT", "suppressions", "to", "empty", "." ]
def ResetNolintSuppressions(): "Resets the set of NOLINT suppressions to empty." _error_suppressions.clear()
[ "def", "ResetNolintSuppressions", "(", ")", ":", "_error_suppressions", ".", "clear", "(", ")" ]
https://github.com/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/scripts/cpp_lint.py#L499-L501
CaoWGG/TensorRT-CenterNet
f949252e37b51e60f873808f46d3683f15735e79
onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py
python
TokenKind.__init__
(self, value, name)
Create a new TokenKind instance from a numeric value and a name.
Create a new TokenKind instance from a numeric value and a name.
[ "Create", "a", "new", "TokenKind", "instance", "from", "a", "numeric", "value", "and", "a", "name", "." ]
def __init__(self, value, name): """Create a new TokenKind instance from a numeric value and a name.""" self.value = value self.name = name
[ "def", "__init__", "(", "self", ",", "value", ",", "name", ")", ":", "self", ".", "value", "=", "value", "self", ".", "name", "=", "name" ]
https://github.com/CaoWGG/TensorRT-CenterNet/blob/f949252e37b51e60f873808f46d3683f15735e79/onnx-tensorrt/third_party/onnx/third_party/pybind11/tools/clang/cindex.py#L483-L486
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/pydoc.py
python
Doc.getdocloc
(self, object, basedir=os.path.join(sys.exec_prefix, "lib", "python"+sys.version[0:3]))
return docloc
Return the location of module docs or None
Return the location of module docs or None
[ "Return", "the", "location", "of", "module", "docs", "or", "None" ]
def getdocloc(self, object, basedir=os.path.join(sys.exec_prefix, "lib", "python"+sys.version[0:3])): """Return the location of module docs or None""" try: file = inspect.getabsfile(object) except TypeError: file = '(built-in)' docloc = os.environ.get("PYTHONDOCS", "https://docs.python.org/library") basedir = os.path.normcase(basedir) if (isinstance(object, type(os)) and (object.__name__ in ('errno', 'exceptions', 'gc', 'imp', 'marshal', 'posix', 'signal', 'sys', 'thread', 'zipimport') or (file.startswith(basedir) and not file.startswith(os.path.join(basedir, 'site-packages')))) and object.__name__ not in ('xml.etree', 'test.pydoc_mod')): if docloc.startswith(("http://", "https://")): docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__.lower()) else: docloc = os.path.join(docloc, object.__name__.lower() + ".html") else: docloc = None return docloc
[ "def", "getdocloc", "(", "self", ",", "object", ",", "basedir", "=", "os", ".", "path", ".", "join", "(", "sys", ".", "exec_prefix", ",", "\"lib\"", ",", "\"python\"", "+", "sys", ".", "version", "[", "0", ":", "3", "]", ")", ")", ":", "try", ":"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pydoc.py#L377-L403
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/multiprocessing/managers.py
python
BaseManager.join
(self, timeout=None)
Join the manager process (if it has been spawned)
Join the manager process (if it has been spawned)
[ "Join", "the", "manager", "process", "(", "if", "it", "has", "been", "spawned", ")" ]
def join(self, timeout=None): ''' Join the manager process (if it has been spawned) ''' self._process.join(timeout)
[ "def", "join", "(", "self", ",", "timeout", "=", "None", ")", ":", "self", ".", "_process", ".", "join", "(", "timeout", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/multiprocessing/managers.py#L539-L543
9miao/CrossApp
1f5375e061bf69841eb19728598f5ae3f508d620
tools/bindings-generator/generator.py
python
Generator.sorted_classes
(self)
return no_dupes
sorted classes in order of inheritance
sorted classes in order of inheritance
[ "sorted", "classes", "in", "order", "of", "inheritance" ]
def sorted_classes(self): ''' sorted classes in order of inheritance ''' sorted_list = [] for class_name in self.generated_classes.iterkeys(): nclass = self.generated_classes[class_name] sorted_list += self._sorted_parents(nclass) # remove dupes from the list no_dupes = [] [no_dupes.append(i) for i in sorted_list if not no_dupes.count(i)] return no_dupes
[ "def", "sorted_classes", "(", "self", ")", ":", "sorted_list", "=", "[", "]", "for", "class_name", "in", "self", ".", "generated_classes", ".", "iterkeys", "(", ")", ":", "nclass", "=", "self", ".", "generated_classes", "[", "class_name", "]", "sorted_list",...
https://github.com/9miao/CrossApp/blob/1f5375e061bf69841eb19728598f5ae3f508d620/tools/bindings-generator/generator.py#L1158-L1169
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/msvc.py
python
msvc14_get_vc_env
(plat_spec)
Patched "distutils._msvccompiler._get_vc_env" for support extra Microsoft Visual C++ 14.X compilers. Set environment without use of "vcvarsall.bat". Parameters ---------- plat_spec: str Target architecture. Return ------ dict environment
Patched "distutils._msvccompiler._get_vc_env" for support extra Microsoft Visual C++ 14.X compilers.
[ "Patched", "distutils", ".", "_msvccompiler", ".", "_get_vc_env", "for", "support", "extra", "Microsoft", "Visual", "C", "++", "14", ".", "X", "compilers", "." ]
def msvc14_get_vc_env(plat_spec): """ Patched "distutils._msvccompiler._get_vc_env" for support extra Microsoft Visual C++ 14.X compilers. Set environment without use of "vcvarsall.bat". Parameters ---------- plat_spec: str Target architecture. Return ------ dict environment """ # Always use backport from CPython 3.8 try: return _msvc14_get_vc_env(plat_spec) except distutils.errors.DistutilsPlatformError as exc: _augment_exception(exc, 14.0) raise
[ "def", "msvc14_get_vc_env", "(", "plat_spec", ")", ":", "# Always use backport from CPython 3.8", "try", ":", "return", "_msvc14_get_vc_env", "(", "plat_spec", ")", "except", "distutils", ".", "errors", ".", "DistutilsPlatformError", "as", "exc", ":", "_augment_exceptio...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/msvc.py#L294-L317
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/pybind/mgr/dashboard/tools.py
python
NotificationQueue.register
(cls, func, n_types=None, priority=1)
Registers function to listen for notifications If the second parameter `n_types` is omitted, the function in `func` parameter will be called for any type of notifications. Args: func (function): python function ex: def foo(val) n_types (str|list): the single type to listen, or a list of types priority (int): the priority level (1=max, +inf=min)
Registers function to listen for notifications
[ "Registers", "function", "to", "listen", "for", "notifications" ]
def register(cls, func, n_types=None, priority=1): """Registers function to listen for notifications If the second parameter `n_types` is omitted, the function in `func` parameter will be called for any type of notifications. Args: func (function): python function ex: def foo(val) n_types (str|list): the single type to listen, or a list of types priority (int): the priority level (1=max, +inf=min) """ with cls._lock: if not n_types: n_types = [cls._ALL_TYPES_] elif isinstance(n_types, str): n_types = [n_types] elif not isinstance(n_types, list): raise Exception("n_types param is neither a string nor a list") for ev_type in n_types: if not cls._registered_handler(func, ev_type): cls._listeners[ev_type].add((priority, func)) cls.logger.debug( # type: ignore "function %s was registered for events of type %s", func, ev_type )
[ "def", "register", "(", "cls", ",", "func", ",", "n_types", "=", "None", ",", "priority", "=", "1", ")", ":", "with", "cls", ".", "_lock", ":", "if", "not", "n_types", ":", "n_types", "=", "[", "cls", ".", "_ALL_TYPES_", "]", "elif", "isinstance", ...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/pybind/mgr/dashboard/tools.py#L301-L325
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/variables.py
python
Variable._OverloadOperator
(operator)
Register _RunOp as the implementation of 'operator'. Args: operator: string. The operator name.
Register _RunOp as the implementation of 'operator'.
[ "Register", "_RunOp", "as", "the", "implementation", "of", "operator", "." ]
def _OverloadOperator(operator): """Register _RunOp as the implementation of 'operator'. Args: operator: string. The operator name. """ if operator in ["__invert__", "__neg__", "__abs__"]: setattr(Variable, operator, lambda a: Variable._RunOp(operator, a, None)) else: setattr(Variable, operator, lambda a, b: Variable._RunOp(operator, a, b))
[ "def", "_OverloadOperator", "(", "operator", ")", ":", "if", "operator", "in", "[", "\"__invert__\"", ",", "\"__neg__\"", ",", "\"__abs__\"", "]", ":", "setattr", "(", "Variable", ",", "operator", ",", "lambda", "a", ":", "Variable", ".", "_RunOp", "(", "o...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/variables.py#L606-L615
deepmind/streetlearn
ccf1d60b9c45154894d45a897748aee85d7eb69b
streetlearn/python/environment/observations.py
python
reshape_hwc
(array, c, w, h)
return np.ravel((arr[0], arr[1], arr[2]), order='F').reshape(h, w, 3)
Turn a planar RGB array into an interleaved one. Args: array: An array of bytes consisting the planar RGB image of size (c, w, h). c: Number of channels in the image. w: Width of the image. h: Height of the image. Returns: An interleaved array of bytes shape shaped (h, w, c).
Turn a planar RGB array into an interleaved one.
[ "Turn", "a", "planar", "RGB", "array", "into", "an", "interleaved", "one", "." ]
def reshape_hwc(array, c, w, h): """Turn a planar RGB array into an interleaved one. Args: array: An array of bytes consisting the planar RGB image of size (c, w, h). c: Number of channels in the image. w: Width of the image. h: Height of the image. Returns: An interleaved array of bytes shape shaped (h, w, c). """ arr = array.reshape(c, w * h) return np.ravel((arr[0], arr[1], arr[2]), order='F').reshape(h, w, 3)
[ "def", "reshape_hwc", "(", "array", ",", "c", ",", "w", ",", "h", ")", ":", "arr", "=", "array", ".", "reshape", "(", "c", ",", "w", "*", "h", ")", "return", "np", ".", "ravel", "(", "(", "arr", "[", "0", "]", ",", "arr", "[", "1", "]", "...
https://github.com/deepmind/streetlearn/blob/ccf1d60b9c45154894d45a897748aee85d7eb69b/streetlearn/python/environment/observations.py#L30-L43
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/EditorWindow.py
python
EditorWindow.ResetFont
(self)
Update the text widgets' font if it is changed
Update the text widgets' font if it is changed
[ "Update", "the", "text", "widgets", "font", "if", "it", "is", "changed" ]
def ResetFont(self): "Update the text widgets' font if it is changed" # Called from configDialog.py fontWeight='normal' if idleConf.GetOption('main','EditorWindow','font-bold',type='bool'): fontWeight='bold' self.text.config(font=(idleConf.GetOption('main','EditorWindow','font'), idleConf.GetOption('main','EditorWindow','font-size', type='int'), fontWeight))
[ "def", "ResetFont", "(", "self", ")", ":", "# Called from configDialog.py", "fontWeight", "=", "'normal'", "if", "idleConf", ".", "GetOption", "(", "'main'", ",", "'EditorWindow'", ",", "'font-bold'", ",", "type", "=", "'bool'", ")", ":", "fontWeight", "=", "'...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/EditorWindow.py#L766-L775
aimerykong/Low-Rank-Bilinear-Pooling
487eb2c857fd9c95357a5166b0c15ad0fe135b28
demo3_modelVisualization/vlfeat/docsrc/webdoc.py
python
DocNode.adopt
(self, orfan)
Adds ORFAN to the node children and make the node the parent of ORFAN. ORFAN can also be a sequence of orfans.
Adds ORFAN to the node children and make the node the parent of ORFAN. ORFAN can also be a sequence of orfans.
[ "Adds", "ORFAN", "to", "the", "node", "children", "and", "make", "the", "node", "the", "parent", "of", "ORFAN", ".", "ORFAN", "can", "also", "be", "a", "sequence", "of", "orfans", "." ]
def adopt(self, orfan): """ Adds ORFAN to the node children and make the node the parent of ORFAN. ORFAN can also be a sequence of orfans. """ self.children.append(orfan) orfan.setParent(self)
[ "def", "adopt", "(", "self", ",", "orfan", ")", ":", "self", ".", "children", ".", "append", "(", "orfan", ")", "orfan", ".", "setParent", "(", "self", ")" ]
https://github.com/aimerykong/Low-Rank-Bilinear-Pooling/blob/487eb2c857fd9c95357a5166b0c15ad0fe135b28/demo3_modelVisualization/vlfeat/docsrc/webdoc.py#L326-L332
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/importers/CNTK/lib/cntk_utilities.py
python
Utilities.get_model_nodes
(root)
return nodes
Returns a list of the high-level nodes (i.e. function blocks) that make up the CNTK model
Returns a list of the high-level nodes (i.e. function blocks) that make up the CNTK model
[ "Returns", "a", "list", "of", "the", "high", "-", "level", "nodes", "(", "i", ".", "e", ".", "function", "blocks", ")", "that", "make", "up", "the", "CNTK", "model" ]
def get_model_nodes(root): """Returns a list of the high-level nodes (i.e. function blocks) that make up the CNTK model """ stack = [root.root_function] # node nodes = [] # final result, list of all relevant layers visited = set() while stack: node = stack.pop(0) if node.uid in visited: continue from cntk import cntk_py # noqa 401 try: node = node.root_function # Function node stack = list(node.root_function.inputs) + stack except AttributeError: # OutputVariable node. We need process the owner node if this is an output. try: if node.is_output: stack.insert(0, node.owner) continue except AttributeError: pass # Add function nodes but skip Variable nodes. Only function nodes are # needed since they represent operations. if not isinstance(node, Variable) and node.uid not in visited: nodes.append(node) visited.add(node.uid) # Also add input variables for i in node.inputs: if i.is_input: i.op_name = "Input" nodes.append(i) nodes.reverse() return nodes
[ "def", "get_model_nodes", "(", "root", ")", ":", "stack", "=", "[", "root", ".", "root_function", "]", "# node", "nodes", "=", "[", "]", "# final result, list of all relevant layers", "visited", "=", "set", "(", ")", "while", "stack", ":", "node", "=", "stac...
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/importers/CNTK/lib/cntk_utilities.py#L214-L251
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/third_party/davclient/davclient.py
python
DAVClient.propfind
(self, path, properties='allprop', namespace='DAV:', depth=None, headers=None)
Property find. If properties arg is unspecified it defaults to 'allprop
Property find. If properties arg is unspecified it defaults to 'allprop
[ "Property", "find", ".", "If", "properties", "arg", "is", "unspecified", "it", "defaults", "to", "allprop" ]
def propfind(self, path, properties='allprop', namespace='DAV:', depth=None, headers=None): """Property find. If properties arg is unspecified it defaults to 'allprop'""" # Build propfind xml root = ElementTree.Element('{DAV:}propfind') if type(properties) is str: ElementTree.SubElement(root, '{DAV:}%s' % properties) else: props = ElementTree.SubElement(root, '{DAV:}prop') object_to_etree(props, properties, namespace=namespace) tree = ElementTree.ElementTree(root) # Etree won't just return a normal string, so we have to do this body = StringIO.StringIO() tree.write(body) body = body.getvalue() # Add proper headers if headers is None: headers = {} if depth is not None: headers['Depth'] = depth headers['Content-Type'] = 'text/xml; charset="utf-8"' # Body encoding must be utf-8, 207 is proper response self._request('PROPFIND', path, body=unicode('<?xml version="1.0" encoding="utf-8" ?>\n'+body, 'utf-8'), headers=headers) if self.response is not None and hasattr(self.response, 'tree') is True: property_responses = {} for response in self.response.tree._children: property_href = response.find('{DAV:}href') property_stat = response.find('{DAV:}propstat') def parse_props(props): property_dict = {} for prop in props: if prop.tag.find('{DAV:}') is not -1: name = prop.tag.split('}')[-1] else: name = prop.tag if len(prop._children) is not 0: property_dict[name] = parse_props(prop._children) else: property_dict[name] = prop.text return property_dict if property_href is not None and property_stat is not None: property_dict = parse_props(property_stat.find('{DAV:}prop')._children) property_responses[property_href.text] = property_dict return property_responses
[ "def", "propfind", "(", "self", ",", "path", ",", "properties", "=", "'allprop'", ",", "namespace", "=", "'DAV:'", ",", "depth", "=", "None", ",", "headers", "=", "None", ")", ":", "# Build propfind xml", "root", "=", "ElementTree", ".", "Element", "(", ...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/davclient/davclient.py#L195-L243
microsoft/AirSim
8057725712c0cd46979135396381784075ffc0f3
PythonClient/airsim/client.py
python
VehicleClient.simGetDistortionParams
(self, camera_name, vehicle_name = '', external = False)
return self.client.call('simGetDistortionParams', str(camera_name), vehicle_name, external)
Get camera distortion parameters Args: camera_name (str): Name of the camera, for backwards compatibility, ID numbers such as 0,1,etc. can also be used vehicle_name (str, optional): Vehicle which the camera is associated with external (bool, optional): Whether the camera is an External Camera Returns: List (float): List of distortion parameter values corresponding to K1, K2, K3, P1, P2 respectively.
Get camera distortion parameters
[ "Get", "camera", "distortion", "parameters" ]
def simGetDistortionParams(self, camera_name, vehicle_name = '', external = False): """ Get camera distortion parameters Args: camera_name (str): Name of the camera, for backwards compatibility, ID numbers such as 0,1,etc. can also be used vehicle_name (str, optional): Vehicle which the camera is associated with external (bool, optional): Whether the camera is an External Camera Returns: List (float): List of distortion parameter values corresponding to K1, K2, K3, P1, P2 respectively. """ return self.client.call('simGetDistortionParams', str(camera_name), vehicle_name, external)
[ "def", "simGetDistortionParams", "(", "self", ",", "camera_name", ",", "vehicle_name", "=", "''", ",", "external", "=", "False", ")", ":", "return", "self", ".", "client", ".", "call", "(", "'simGetDistortionParams'", ",", "str", "(", "camera_name", ")", ","...
https://github.com/microsoft/AirSim/blob/8057725712c0cd46979135396381784075ffc0f3/PythonClient/airsim/client.py#L723-L736
nyuwireless-unipd/ns3-mmwave
4ff9e87e8079764e04cbeccd8e85bff15ae16fb3
src/visualizer/visualizer/core.py
python
Visualizer._panning_motion
(self, widget, event)
return True
! Panning motion function. @param self: class object. @param widget: widget. @param event: event. @return true if successful
! Panning motion function.
[ "!", "Panning", "motion", "function", "." ]
def _panning_motion(self, widget, event): """! Panning motion function. @param self: class object. @param widget: widget. @param event: event. @return true if successful """ assert self._panning_state is not None if event.is_hint: pos = widget.get_window().get_device_position(event.device) x, y = pos.x, pos.y else: x, y = event.x, event.y hadj = self._scrolled_window.get_hadjustment() vadj = self._scrolled_window.get_vadjustment() mx0, my0 = self._panning_state.initial_mouse_pos cx0, cy0 = self._panning_state.initial_canvas_pos dx = x - mx0 dy = y - my0 hadj.set_value(cx0 - dx) vadj.set_value(cy0 - dy) return True
[ "def", "_panning_motion", "(", "self", ",", "widget", ",", "event", ")", ":", "assert", "self", ".", "_panning_state", "is", "not", "None", "if", "event", ".", "is_hint", ":", "pos", "=", "widget", ".", "get_window", "(", ")", ".", "get_device_position", ...
https://github.com/nyuwireless-unipd/ns3-mmwave/blob/4ff9e87e8079764e04cbeccd8e85bff15ae16fb3/src/visualizer/visualizer/core.py#L924-L949
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/amp/grad_scaler.py
python
GradScaler.load_state_dict
(self, state_dict)
Loads the scaler state. Args: state_dict(dict): scaler state. Should be an object returned from a call to `GradScaler.state_dict()`. Examples: .. code-block:: python # required: gpu,xpu import paddle scaler = paddle.amp.GradScaler(enable=True, init_loss_scaling=1024, incr_ratio=2.0, decr_ratio=0.5, incr_every_n_steps=1000, decr_every_n_nan_or_inf=2, use_dynamic_loss_scaling=True) scaler_state = scaler.state_dict() scaler.load_state_dict(scaler_state)
Loads the scaler state. Args: state_dict(dict): scaler state. Should be an object returned from a call to `GradScaler.state_dict()`. Examples:
[ "Loads", "the", "scaler", "state", ".", "Args", ":", "state_dict", "(", "dict", ")", ":", "scaler", "state", ".", "Should", "be", "an", "object", "returned", "from", "a", "call", "to", "GradScaler", ".", "state_dict", "()", ".", "Examples", ":" ]
def load_state_dict(self, state_dict): """ Loads the scaler state. Args: state_dict(dict): scaler state. Should be an object returned from a call to `GradScaler.state_dict()`. Examples: .. code-block:: python # required: gpu,xpu import paddle scaler = paddle.amp.GradScaler(enable=True, init_loss_scaling=1024, incr_ratio=2.0, decr_ratio=0.5, incr_every_n_steps=1000, decr_every_n_nan_or_inf=2, use_dynamic_loss_scaling=True) scaler_state = scaler.state_dict() scaler.load_state_dict(scaler_state) """ super(GradScaler, self).load_state_dict(state_dict)
[ "def", "load_state_dict", "(", "self", ",", "state_dict", ")", ":", "super", "(", "GradScaler", ",", "self", ")", ".", "load_state_dict", "(", "state_dict", ")" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/amp/grad_scaler.py#L610-L634
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/problems/problem.py
python
Problem.is_dcp
(self, dpp: bool = False)
return all( expr.is_dcp(dpp) for expr in self.constraints + [self.objective])
Does the problem satisfy DCP rules? Arguments --------- dpp : bool, optional If True, enforce the disciplined parametrized programming (DPP) ruleset; only relevant when the problem involves Parameters. DPP is a mild restriction of DCP. When a problem involving Parameters is DPP, subsequent solves can be much faster than the first one. For more information, consult the documentation at https://www.cvxpy.org/tutorial/advanced/index.html#disciplined-parametrized-programming Returns ------- bool True if the Expression is DCP, False otherwise.
Does the problem satisfy DCP rules?
[ "Does", "the", "problem", "satisfy", "DCP", "rules?" ]
def is_dcp(self, dpp: bool = False) -> bool: """Does the problem satisfy DCP rules? Arguments --------- dpp : bool, optional If True, enforce the disciplined parametrized programming (DPP) ruleset; only relevant when the problem involves Parameters. DPP is a mild restriction of DCP. When a problem involving Parameters is DPP, subsequent solves can be much faster than the first one. For more information, consult the documentation at https://www.cvxpy.org/tutorial/advanced/index.html#disciplined-parametrized-programming Returns ------- bool True if the Expression is DCP, False otherwise. """ return all( expr.is_dcp(dpp) for expr in self.constraints + [self.objective])
[ "def", "is_dcp", "(", "self", ",", "dpp", ":", "bool", "=", "False", ")", "->", "bool", ":", "return", "all", "(", "expr", ".", "is_dcp", "(", "dpp", ")", "for", "expr", "in", "self", ".", "constraints", "+", "[", "self", ".", "objective", "]", "...
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/problems/problem.py#L222-L242
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
clang/bindings/python/clang/cindex.py
python
Cursor.availability
(self)
return AvailabilityKind.from_id(self._availability)
Retrieves the availability of the entity pointed at by the cursor.
Retrieves the availability of the entity pointed at by the cursor.
[ "Retrieves", "the", "availability", "of", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
def availability(self): """ Retrieves the availability of the entity pointed at by the cursor. """ if not hasattr(self, '_availability'): self._availability = conf.lib.clang_getCursorAvailability(self) return AvailabilityKind.from_id(self._availability)
[ "def", "availability", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_availability'", ")", ":", "self", ".", "_availability", "=", "conf", ".", "lib", ".", "clang_getCursorAvailability", "(", "self", ")", "return", "AvailabilityKind", "....
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/clang/bindings/python/clang/cindex.py#L1623-L1630
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/vm/theano/tensor/extra_ops.py
python
cumprod
(x, axis=None)
Compute the cumulative product along the given axis. Parameters ---------- x : Tensor The input tensor. axis : int The axis to sum. Default is ``None`` (Along all axes).
Compute the cumulative product along the given axis.
[ "Compute", "the", "cumulative", "product", "along", "the", "given", "axis", "." ]
def cumprod(x, axis=None): """Compute the cumulative product along the given axis. Parameters ---------- x : Tensor The input tensor. axis : int The axis to sum. Default is ``None`` (Along all axes). """ raise NotImplementedError()
[ "def", "cumprod", "(", "x", ",", "axis", "=", "None", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/vm/theano/tensor/extra_ops.py#L24-L35
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
python
logical_or
(attrs, inputs, proto_obj)
return 'broadcast_logical_or', attrs, inputs
Logical or of two input arrays.
Logical or of two input arrays.
[ "Logical", "or", "of", "two", "input", "arrays", "." ]
def logical_or(attrs, inputs, proto_obj): """Logical or of two input arrays.""" return 'broadcast_logical_or', attrs, inputs
[ "def", "logical_or", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "return", "'broadcast_logical_or'", ",", "attrs", ",", "inputs" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py#L121-L123
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/v8/third_party/jinja2/environment.py
python
Template.is_up_to_date
(self)
return self._uptodate()
If this variable is `False` there is a newer version available.
If this variable is `False` there is a newer version available.
[ "If", "this", "variable", "is", "False", "there", "is", "a", "newer", "version", "available", "." ]
def is_up_to_date(self): """If this variable is `False` there is a newer version available.""" if self._uptodate is None: return True return self._uptodate()
[ "def", "is_up_to_date", "(", "self", ")", ":", "if", "self", ".", "_uptodate", "is", "None", ":", "return", "True", "return", "self", ".", "_uptodate", "(", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/environment.py#L1118-L1122
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npyufunc/parfor.py
python
compute_def_once_internal
(loop_body, def_once, def_more, getattr_taken, typemap, module_assigns)
Compute the set of variables defined exactly once in the given set of blocks and use the given sets for storing which variables are defined once, more than once and which have had a getattr call on them.
Compute the set of variables defined exactly once in the given set of blocks and use the given sets for storing which variables are defined once, more than once and which have had a getattr call on them.
[ "Compute", "the", "set", "of", "variables", "defined", "exactly", "once", "in", "the", "given", "set", "of", "blocks", "and", "use", "the", "given", "sets", "for", "storing", "which", "variables", "are", "defined", "once", "more", "than", "once", "and", "w...
def compute_def_once_internal(loop_body, def_once, def_more, getattr_taken, typemap, module_assigns): '''Compute the set of variables defined exactly once in the given set of blocks and use the given sets for storing which variables are defined once, more than once and which have had a getattr call on them. ''' # For each block... for label, block in loop_body.items(): # Scan this block and effect changes to def_once, def_more, and getattr_taken # based on the instructions in that block. compute_def_once_block(block, def_once, def_more, getattr_taken, typemap, module_assigns) # Have to recursively process parfors manually here. for inst in block.body: if isinstance(inst, parfor.Parfor): # Recursively compute for the parfor's init block. compute_def_once_block(inst.init_block, def_once, def_more, getattr_taken, typemap, module_assigns) # Recursively compute for the parfor's loop body. compute_def_once_internal(inst.loop_body, def_once, def_more, getattr_taken, typemap, module_assigns)
[ "def", "compute_def_once_internal", "(", "loop_body", ",", "def_once", ",", "def_more", ",", "getattr_taken", ",", "typemap", ",", "module_assigns", ")", ":", "# For each block...", "for", "label", ",", "block", "in", "loop_body", ".", "items", "(", ")", ":", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/npyufunc/parfor.py#L601-L617
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py
python
Menu.insert_radiobutton
(self, index, cnf={}, **kw)
Addd radio menu item at INDEX.
Addd radio menu item at INDEX.
[ "Addd", "radio", "menu", "item", "at", "INDEX", "." ]
def insert_radiobutton(self, index, cnf={}, **kw): """Addd radio menu item at INDEX.""" self.insert(index, 'radiobutton', cnf or kw)
[ "def", "insert_radiobutton", "(", "self", ",", "index", ",", "cnf", "=", "{", "}", ",", "*", "*", "kw", ")", ":", "self", ".", "insert", "(", "index", ",", "'radiobutton'", ",", "cnf", "or", "kw", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/Tkinter.py#L2703-L2705
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py
python
WorldWideWeb_suite_Events.get_window_info
(self, _object=None, _attributes={}, **_arguments)
get window info: Returns the information about the window as a list. Currently the list contains the window title and the URL. You can get the same information using standard Apple Event GetProperty. Required argument: window ID Keyword argument _attributes: AppleEvent attribute dictionary Returns: undocumented, typecode 'list'
get window info: Returns the information about the window as a list. Currently the list contains the window title and the URL. You can get the same information using standard Apple Event GetProperty. Required argument: window ID Keyword argument _attributes: AppleEvent attribute dictionary Returns: undocumented, typecode 'list'
[ "get", "window", "info", ":", "Returns", "the", "information", "about", "the", "window", "as", "a", "list", ".", "Currently", "the", "list", "contains", "the", "window", "title", "and", "the", "URL", ".", "You", "can", "get", "the", "same", "information", ...
def get_window_info(self, _object=None, _attributes={}, **_arguments): """get window info: Returns the information about the window as a list. Currently the list contains the window title and the URL. You can get the same information using standard Apple Event GetProperty. Required argument: window ID Keyword argument _attributes: AppleEvent attribute dictionary Returns: undocumented, typecode 'list' """ _code = 'WWW!' _subcode = 'WNFO' if _arguments: raise TypeError, 'No optional args expected' _arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----'): return _arguments['----']
[ "def", "get_window_info", "(", "self", ",", "_object", "=", "None", ",", "_attributes", "=", "{", "}", ",", "*", "*", "_arguments", ")", ":", "_code", "=", "'WWW!'", "_subcode", "=", "'WNFO'", "if", "_arguments", ":", "raise", "TypeError", ",", "'No opti...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py#L127-L146
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
GetEigVec
(*args)
return _snap.GetEigVec(*args)
GetEigVec(PUNGraph const & Graph, TFltV & EigVecV) Parameters: Graph: PUNGraph const & EigVecV: TFltV & GetEigVec(PUNGraph const & Graph, int const & EigVecs, TFltV & EigValV, TVec< TFltV > & EigVecV) Parameters: Graph: PUNGraph const & EigVecs: int const & EigValV: TFltV & EigVecV: TVec< TFltV > &
GetEigVec(PUNGraph const & Graph, TFltV & EigVecV)
[ "GetEigVec", "(", "PUNGraph", "const", "&", "Graph", "TFltV", "&", "EigVecV", ")" ]
def GetEigVec(*args): """ GetEigVec(PUNGraph const & Graph, TFltV & EigVecV) Parameters: Graph: PUNGraph const & EigVecV: TFltV & GetEigVec(PUNGraph const & Graph, int const & EigVecs, TFltV & EigValV, TVec< TFltV > & EigVecV) Parameters: Graph: PUNGraph const & EigVecs: int const & EigValV: TFltV & EigVecV: TVec< TFltV > & """ return _snap.GetEigVec(*args)
[ "def", "GetEigVec", "(", "*", "args", ")", ":", "return", "_snap", ".", "GetEigVec", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L5599-L5616
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/Image.py
python
Image.reduce
(self, factor, box=None)
return self._new(self.im.reduce(factor, box))
Returns a copy of the image reduced by `factor` times. If the size of the image is not dividable by the `factor`, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used.
Returns a copy of the image reduced by `factor` times. If the size of the image is not dividable by the `factor`, the resulting size will be rounded up.
[ "Returns", "a", "copy", "of", "the", "image", "reduced", "by", "factor", "times", ".", "If", "the", "size", "of", "the", "image", "is", "not", "dividable", "by", "the", "factor", "the", "resulting", "size", "will", "be", "rounded", "up", "." ]
def reduce(self, factor, box=None): """ Returns a copy of the image reduced by `factor` times. If the size of the image is not dividable by the `factor`, the resulting size will be rounded up. :param factor: A greater than 0 integer or tuple of two integers for width and height separately. :param box: An optional 4-tuple of ints providing the source image region to be reduced. The values must be within (0, 0, width, height) rectangle. If omitted or None, the entire source is used. """ if not isinstance(factor, (list, tuple)): factor = (factor, factor) if box is None: box = (0, 0) + self.size else: box = tuple(box) if factor == (1, 1) and box == (0, 0) + self.size: return self.copy() if self.mode in ["LA", "RGBA"]: im = self.convert(self.mode[:-1] + "a") im = im.reduce(factor, box) return im.convert(self.mode) self.load() return self._new(self.im.reduce(factor, box))
[ "def", "reduce", "(", "self", ",", "factor", ",", "box", "=", "None", ")", ":", "if", "not", "isinstance", "(", "factor", ",", "(", "list", ",", "tuple", ")", ")", ":", "factor", "=", "(", "factor", ",", "factor", ")", "if", "box", "is", "None", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemDefectReporter/v1/AWS/common-code/Lib/PIL/Image.py#L1907-L1938
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Validator.Validate
(*args, **kwargs)
return _core_.Validator_Validate(*args, **kwargs)
Validate(self, Window parent) -> bool
Validate(self, Window parent) -> bool
[ "Validate", "(", "self", "Window", "parent", ")", "-", ">", "bool" ]
def Validate(*args, **kwargs): """Validate(self, Window parent) -> bool""" return _core_.Validator_Validate(*args, **kwargs)
[ "def", "Validate", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Validator_Validate", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L11880-L11882
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/traci/_overheadwire.py
python
OverheadWireDomain.getName
(self, stopID)
return self._getUniversal(tc.VAR_NAME, stopID)
getName(string) -> string Returns the name of this stop
getName(string) -> string
[ "getName", "(", "string", ")", "-", ">", "string" ]
def getName(self, stopID): """getName(string) -> string Returns the name of this stop """ return self._getUniversal(tc.VAR_NAME, stopID)
[ "def", "getName", "(", "self", ",", "stopID", ")", ":", "return", "self", ".", "_getUniversal", "(", "tc", ".", "VAR_NAME", ",", "stopID", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/traci/_overheadwire.py#L50-L55
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/utils.py
python
post_order_recursive
(root, root_t)
return nodes, weights, inputs
return a list by the topological ordering (postorder of Depth-first search) Args: root: singa operator root_t: tensor Returns: deque[int]
return a list by the topological ordering (postorder of Depth-first search) Args: root: singa operator root_t: tensor Returns: deque[int]
[ "return", "a", "list", "by", "the", "topological", "ordering", "(", "postorder", "of", "Depth", "-", "first", "search", ")", "Args", ":", "root", ":", "singa", "operator", "root_t", ":", "tensor", "Returns", ":", "deque", "[", "int", "]" ]
def post_order_recursive(root, root_t): """ return a list by the topological ordering (postorder of Depth-first search) Args: root: singa operator root_t: tensor Returns: deque[int] """ def recursive(root, yid, root_t): if root: # srcop: operator for a input of root # yid: id(output of this operator) # y: output of this operator for srcop, yid, y, _ in root.src: recursive(srcop, yid, y) if type(root).__name__ == 'Dummy': if root_t != None: # constant within a node: weight weights[root.name] = root_t else: # constant outside a node: input inputs[root.name] = root_t else: nodes[root.name] = root nodes = OrderedDict() weights = OrderedDict() inputs = OrderedDict() recursive(root, None, root_t) return nodes, weights, inputs
[ "def", "post_order_recursive", "(", "root", ",", "root_t", ")", ":", "def", "recursive", "(", "root", ",", "yid", ",", "root_t", ")", ":", "if", "root", ":", "# srcop: operator for a input of root", "# yid: id(output of this operator)", "# y: output of this operator", ...
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/utils.py#L234-L267
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/reshape/tile.py
python
_coerce_to_type
(x)
return x, dtype
if the passed data is of datetime/timedelta, bool or nullable int type, this method converts it to numeric so that cut or qcut method can handle it
if the passed data is of datetime/timedelta, bool or nullable int type, this method converts it to numeric so that cut or qcut method can handle it
[ "if", "the", "passed", "data", "is", "of", "datetime", "/", "timedelta", "bool", "or", "nullable", "int", "type", "this", "method", "converts", "it", "to", "numeric", "so", "that", "cut", "or", "qcut", "method", "can", "handle", "it" ]
def _coerce_to_type(x): """ if the passed data is of datetime/timedelta, bool or nullable int type, this method converts it to numeric so that cut or qcut method can handle it """ dtype = None if is_datetime64tz_dtype(x): dtype = x.dtype elif is_datetime64_dtype(x): x = to_datetime(x) dtype = np.dtype("datetime64[ns]") elif is_timedelta64_dtype(x): x = to_timedelta(x) dtype = np.dtype("timedelta64[ns]") elif is_bool_dtype(x): # GH 20303 x = x.astype(np.int64) # To support cut and qcut for IntegerArray we convert to float dtype. # Will properly support in the future. # https://github.com/pandas-dev/pandas/pull/31290 # https://github.com/pandas-dev/pandas/issues/31389 elif is_extension_array_dtype(x) and is_integer_dtype(x): x = x.to_numpy(dtype=np.float64, na_value=np.nan) if dtype is not None: # GH 19768: force NaT to NaN during integer conversion x = np.where(x.notna(), x.view(np.int64), np.nan) return x, dtype
[ "def", "_coerce_to_type", "(", "x", ")", ":", "dtype", "=", "None", "if", "is_datetime64tz_dtype", "(", "x", ")", ":", "dtype", "=", "x", ".", "dtype", "elif", "is_datetime64_dtype", "(", "x", ")", ":", "x", "=", "to_datetime", "(", "x", ")", "dtype", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/reshape/tile.py#L429-L459
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/gtk+/gtk/compose-parse.py
python
download_hook
(blocks_transferred, block_size, file_size)
A download hook to provide some feedback when downloading
A download hook to provide some feedback when downloading
[ "A", "download", "hook", "to", "provide", "some", "feedback", "when", "downloading" ]
def download_hook(blocks_transferred, block_size, file_size): """ A download hook to provide some feedback when downloading """ if blocks_transferred == 0: if file_size > 0: if opt_verbose: print "Downloading", file_size, "bytes: ", else: if opt_verbose: print "Downloading: ", sys.stdout.write('#') sys.stdout.flush()
[ "def", "download_hook", "(", "blocks_transferred", ",", "block_size", ",", "file_size", ")", ":", "if", "blocks_transferred", "==", "0", ":", "if", "file_size", ">", "0", ":", "if", "opt_verbose", ":", "print", "\"Downloading\"", ",", "file_size", ",", "\"byte...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/gtk+/gtk/compose-parse.py#L206-L216
google-ar/WebARonTango
e86965d2cbc652156b480e0fcf77c716745578cd
chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py
python
StateSetFrontBackSeparateHandler.WriteHandlerImplementation
(self, func, f)
Overrriden from TypeHandler.
Overrriden from TypeHandler.
[ "Overrriden", "from", "TypeHandler", "." ]
def WriteHandlerImplementation(self, func, f): """Overrriden from TypeHandler.""" state_name = func.GetInfo('state') state = _STATES[state_name] states = state['states'] args = func.GetOriginalArgs() face = args[0].name num_args = len(args) f.write(" bool changed = false;\n") for group_ndx, group in enumerate(Grouper(num_args - 1, states)): f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" % (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face)) code = [] for ndx, item in enumerate(group): code.append("state_.%s != %s" % (item['name'], args[ndx + 1].name)) f.write(" changed |= %s;\n" % " ||\n ".join(code)) f.write(" }\n") f.write(" if (changed) {\n") for group_ndx, group in enumerate(Grouper(num_args - 1, states)): f.write(" if (%s == %s || %s == GL_FRONT_AND_BACK) {\n" % (face, ('GL_FRONT', 'GL_BACK')[group_ndx], face)) for ndx, item in enumerate(group): f.write(" state_.%s = %s;\n" % (item['name'], args[ndx + 1].name)) f.write(" }\n") if 'state_flag' in state: f.write(" %s = true;\n" % state['state_flag']) if not func.GetInfo("no_gl"): f.write(" %s(%s);\n" % (func.GetGLFunctionName(), func.MakeOriginalArgString(""))) f.write(" }\n")
[ "def", "WriteHandlerImplementation", "(", "self", ",", "func", ",", "f", ")", ":", "state_name", "=", "func", ".", "GetInfo", "(", "'state'", ")", "state", "=", "_STATES", "[", "state_name", "]", "states", "=", "state", "[", "'states'", "]", "args", "=",...
https://github.com/google-ar/WebARonTango/blob/e86965d2cbc652156b480e0fcf77c716745578cd/chromium/src/gpu/command_buffer/build_gles2_cmd_buffer.py#L5575-L5605
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/framework/ops.py
python
name_scope
(name, default_name=None, values=None)
Returns a context manager for use when defining a Python op. This context manager validates that the given `values` are from the same graph, makes that graph the default graph, and pushes a name scope in that graph (see @{tf.Graph.name_scope} for more details on that). For example, to define a new Python op called `my_op`: ```python def my_op(a, b, c, name=None): with tf.name_scope(name, "MyOp", [a, b, c]) as scope: a = tf.convert_to_tensor(a, name="a") b = tf.convert_to_tensor(b, name="b") c = tf.convert_to_tensor(c, name="c") # Define some computation that uses `a`, `b`, and `c`. return foo_op(..., name=scope) ``` Args: name: The name argument that is passed to the op function. default_name: The default name to use if the `name` argument is `None`. values: The list of `Tensor` arguments that are passed to the op function. Returns: A context manager for use in defining Python ops. Yields the name scope. Raises: ValueError: if neither `name` nor `default_name` is provided but `values` are.
Returns a context manager for use when defining a Python op.
[ "Returns", "a", "context", "manager", "for", "use", "when", "defining", "a", "Python", "op", "." ]
def name_scope(name, default_name=None, values=None): """Returns a context manager for use when defining a Python op. This context manager validates that the given `values` are from the same graph, makes that graph the default graph, and pushes a name scope in that graph (see @{tf.Graph.name_scope} for more details on that). For example, to define a new Python op called `my_op`: ```python def my_op(a, b, c, name=None): with tf.name_scope(name, "MyOp", [a, b, c]) as scope: a = tf.convert_to_tensor(a, name="a") b = tf.convert_to_tensor(b, name="b") c = tf.convert_to_tensor(c, name="c") # Define some computation that uses `a`, `b`, and `c`. return foo_op(..., name=scope) ``` Args: name: The name argument that is passed to the op function. default_name: The default name to use if the `name` argument is `None`. values: The list of `Tensor` arguments that are passed to the op function. Returns: A context manager for use in defining Python ops. Yields the name scope. Raises: ValueError: if neither `name` nor `default_name` is provided but `values` are. """ n = default_name if name is None else name if n is None and values is not None: # We only raise an error if values is not None (provided) because currently # tf.name_scope(None) (values=None then) is sometimes used as an idiom # to reset to top scope. raise ValueError( "At least one of name (%s) and default_name (%s) must be provided." % ( name, default_name)) if values is None: values = [] g = _get_graph_from_inputs(values) with g.as_default(), g.name_scope(n) as scope: yield scope
[ "def", "name_scope", "(", "name", ",", "default_name", "=", "None", ",", "values", "=", "None", ")", ":", "n", "=", "default_name", "if", "name", "is", "None", "else", "name", "if", "n", "is", "None", "and", "values", "is", "not", "None", ":", "# We ...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/framework/ops.py#L4478-L4523
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
parserCtxt.parseStartTag
(self)
return ret
parse a start of tag either for rule element or EmptyElement. In both case we don't parse the tag closing chars. [40] STag ::= '<' Name (S Attribute)* S? '>' [ WFC: Unique Att Spec ] No attribute name may appear more than once in the same start-tag or empty-element tag. [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>' [ WFC: Unique Att Spec ] No attribute name may appear more than once in the same start-tag or empty-element tag. With namespace: [NS 8] STag ::= '<' QName (S Attribute)* S? '>' [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>'
parse a start of tag either for rule element or EmptyElement. In both case we don't parse the tag closing chars. [40] STag ::= '<' Name (S Attribute)* S? '>' [ WFC: Unique Att Spec ] No attribute name may appear more than once in the same start-tag or empty-element tag. [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>' [ WFC: Unique Att Spec ] No attribute name may appear more than once in the same start-tag or empty-element tag. With namespace: [NS 8] STag ::= '<' QName (S Attribute)* S? '>' [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>'
[ "parse", "a", "start", "of", "tag", "either", "for", "rule", "element", "or", "EmptyElement", ".", "In", "both", "case", "we", "don", "t", "parse", "the", "tag", "closing", "chars", ".", "[", "40", "]", "STag", "::", "=", "<", "Name", "(", "S", "At...
def parseStartTag(self): """parse a start of tag either for rule element or EmptyElement. In both case we don't parse the tag closing chars. [40] STag ::= '<' Name (S Attribute)* S? '>' [ WFC: Unique Att Spec ] No attribute name may appear more than once in the same start-tag or empty-element tag. [44] EmptyElemTag ::= '<' Name (S Attribute)* S? '/>' [ WFC: Unique Att Spec ] No attribute name may appear more than once in the same start-tag or empty-element tag. With namespace: [NS 8] STag ::= '<' QName (S Attribute)* S? '>' [NS 10] EmptyElement ::= '<' QName (S Attribute)* S? '/>' """ ret = libxml2mod.xmlParseStartTag(self._o) return ret
[ "def", "parseStartTag", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlParseStartTag", "(", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L5388-L5400
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/array_ops.py
python
concat
(concat_dim, values, name="concat")
return gen_array_ops._concat(concat_dim=concat_dim, values=values, name=name)
Concatenates tensors along one dimension. Concatenates the list of tensors `values` along dimension `concat_dim`. If `values[i].shape = [D0, D1, ... Dconcat_dim(i), ...Dn]`, the concatenated result has shape [D0, D1, ... Rconcat_dim, ...Dn] where Rconcat_dim = sum(Dconcat_dim(i)) That is, the data from the input tensors is joined along the `concat_dim` dimension. The number of dimensions of the input tensors must match, and all dimensions except `concat_dim` must be equal. For example: ```python t1 = [[1, 2, 3], [4, 5, 6]] t2 = [[7, 8, 9], [10, 11, 12]] tf.concat(0, [t1, t2]) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] tf.concat(1, [t1, t2]) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]] # tensor t3 with shape [2, 3] # tensor t4 with shape [2, 3] tf.shape(tf.concat(0, [t3, t4])) ==> [4, 3] tf.shape(tf.concat(1, [t3, t4])) ==> [2, 6] ``` Note: If you are concatenating along a new axis consider using pack. E.g. ```python tf.concat(axis, [tf.expand_dims(t, axis) for t in tensors]) ``` can be rewritten as ```python tf.pack(tensors, axis=axis) ``` Args: concat_dim: 0-D `int32` `Tensor`. Dimension along which to concatenate. values: A list of `Tensor` objects or a single `Tensor`. name: A name for the operation (optional). Returns: A `Tensor` resulting from concatenation of the input tensors.
Concatenates tensors along one dimension.
[ "Concatenates", "tensors", "along", "one", "dimension", "." ]
def concat(concat_dim, values, name="concat"): """Concatenates tensors along one dimension. Concatenates the list of tensors `values` along dimension `concat_dim`. If `values[i].shape = [D0, D1, ... Dconcat_dim(i), ...Dn]`, the concatenated result has shape [D0, D1, ... Rconcat_dim, ...Dn] where Rconcat_dim = sum(Dconcat_dim(i)) That is, the data from the input tensors is joined along the `concat_dim` dimension. The number of dimensions of the input tensors must match, and all dimensions except `concat_dim` must be equal. For example: ```python t1 = [[1, 2, 3], [4, 5, 6]] t2 = [[7, 8, 9], [10, 11, 12]] tf.concat(0, [t1, t2]) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] tf.concat(1, [t1, t2]) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]] # tensor t3 with shape [2, 3] # tensor t4 with shape [2, 3] tf.shape(tf.concat(0, [t3, t4])) ==> [4, 3] tf.shape(tf.concat(1, [t3, t4])) ==> [2, 6] ``` Note: If you are concatenating along a new axis consider using pack. E.g. ```python tf.concat(axis, [tf.expand_dims(t, axis) for t in tensors]) ``` can be rewritten as ```python tf.pack(tensors, axis=axis) ``` Args: concat_dim: 0-D `int32` `Tensor`. Dimension along which to concatenate. values: A list of `Tensor` objects or a single `Tensor`. name: A name for the operation (optional). Returns: A `Tensor` resulting from concatenation of the input tensors. """ if not isinstance(values, (list, tuple)): values = [values] # TODO(mrry): Change to return values? if len(values) == 1: # Degenerate case of one tensor. # Make a throwaway call to convert_to_tensor to make sure # that concat_dim is of the correct type, and make sure that # the returned tensor is a scalar. # TODO(keveman): Implement a standalone type and shape checker. with ops.name_scope(name) as scope: ops.convert_to_tensor(concat_dim, name="concat_dim", dtype=dtypes.int32).get_shape( ).assert_is_compatible_with(tensor_shape.scalar()) return identity(values[0], name=scope) return gen_array_ops._concat(concat_dim=concat_dim, values=values, name=name)
[ "def", "concat", "(", "concat_dim", ",", "values", ",", "name", "=", "\"concat\"", ")", ":", "if", "not", "isinstance", "(", "values", ",", "(", "list", ",", "tuple", ")", ")", ":", "values", "=", "[", "values", "]", "# TODO(mrry): Change to return values?...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/array_ops.py#L627-L697
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/reshape/reshape.py
python
stack
(frame, level=-1, dropna=True)
return frame._constructor_sliced(new_values, index=new_index)
Convert DataFrame to Series with multi-level Index. Columns become the second level of the resulting hierarchical index Returns ------- stacked : Series
Convert DataFrame to Series with multi-level Index. Columns become the second level of the resulting hierarchical index
[ "Convert", "DataFrame", "to", "Series", "with", "multi", "-", "level", "Index", ".", "Columns", "become", "the", "second", "level", "of", "the", "resulting", "hierarchical", "index" ]
def stack(frame, level=-1, dropna=True): """ Convert DataFrame to Series with multi-level Index. Columns become the second level of the resulting hierarchical index Returns ------- stacked : Series """ def factorize(index): if index.is_unique: return index, np.arange(len(index)) codes, categories = factorize_from_iterable(index) return categories, codes N, K = frame.shape # Will also convert negative level numbers and check if out of bounds. level_num = frame.columns._get_level_number(level) if isinstance(frame.columns, MultiIndex): return _stack_multi_columns(frame, level_num=level_num, dropna=dropna) elif isinstance(frame.index, MultiIndex): new_levels = list(frame.index.levels) new_codes = [lab.repeat(K) for lab in frame.index.codes] clev, clab = factorize(frame.columns) new_levels.append(clev) new_codes.append(np.tile(clab, N).ravel()) new_names = list(frame.index.names) new_names.append(frame.columns.name) new_index = MultiIndex( levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False ) else: levels, (ilab, clab) = zip(*map(factorize, (frame.index, frame.columns))) codes = ilab.repeat(K), np.tile(clab, N).ravel() new_index = MultiIndex( levels=levels, codes=codes, names=[frame.index.name, frame.columns.name], verify_integrity=False, ) if not frame.empty and frame._is_homogeneous_type: # For homogeneous EAs, frame._values will coerce to object. So # we concatenate instead. dtypes = list(frame.dtypes._values) dtype = dtypes[0] if is_extension_array_dtype(dtype): arr = dtype.construct_array_type() new_values = arr._concat_same_type( [col._values for _, col in frame.items()] ) new_values = _reorder_for_extension_array_stack(new_values, N, K) else: # homogeneous, non-EA new_values = frame._values.ravel() else: # non-homogeneous new_values = frame._values.ravel() if dropna: mask = notna(new_values) new_values = new_values[mask] new_index = new_index[mask] return frame._constructor_sliced(new_values, index=new_index)
[ "def", "stack", "(", "frame", ",", "level", "=", "-", "1", ",", "dropna", "=", "True", ")", ":", "def", "factorize", "(", "index", ")", ":", "if", "index", ".", "is_unique", ":", "return", "index", ",", "np", ".", "arange", "(", "len", "(", "inde...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/reshape/reshape.py#L509-L580
utilForever/RosettaStone
80a409e35749116b8da87034ea7b4825421f37cc
Scripts/utils.py
python
is64
()
return guess_word_size() == '64'
Returns True if running on 64-bit machine
Returns True if running on 64-bit machine
[ "Returns", "True", "if", "running", "on", "64", "-", "bit", "machine" ]
def is64(): """ Returns True if running on 64-bit machine """ return guess_word_size() == '64'
[ "def", "is64", "(", ")", ":", "return", "guess_word_size", "(", ")", "==", "'64'" ]
https://github.com/utilForever/RosettaStone/blob/80a409e35749116b8da87034ea7b4825421f37cc/Scripts/utils.py#L156-L160
RapidsAtHKUST/CommunityDetectionCodes
23dbafd2e57ab0f5f0528b1322c4a409f21e5892
Algorithms/2015-LEMON/python_yche_refactor/io_helper.py
python
read_edge_list
(filename, delimiter=None, nodetype=int)
return graph_linklist, node_number, edge_number, degree
Generate the adjacent matrix of a graph with overlapping communities. Input: A two-clumn edgelist Return: An adjacency matrix in the form of ndarray corresponding to the given edge list.
Generate the adjacent matrix of a graph with overlapping communities. Input: A two-clumn edgelist Return: An adjacency matrix in the form of ndarray corresponding to the given edge list.
[ "Generate", "the", "adjacent", "matrix", "of", "a", "graph", "with", "overlapping", "communities", ".", "Input", ":", "A", "two", "-", "clumn", "edgelist", "Return", ":", "An", "adjacency", "matrix", "in", "the", "form", "of", "ndarray", "corresponding", "to...
def read_edge_list(filename, delimiter=None, nodetype=int): """Generate the adjacent matrix of a graph with overlapping communities. Input: A two-clumn edgelist Return: An adjacency matrix in the form of ndarray corresponding to the given edge list. """ edgeset = set() nodeset = set() print "Reading the edgelist..." with open(filename) as f: for line in f.readlines(): if not line.strip().startswith("#"): L = line.strip().split(delimiter) ni, nj = nodetype(L[0]), nodetype(L[1]) nodeset.add(ni) nodeset.add(nj) if ni != nj: edgeset.add(sort_two_vertices(ni, nj)) node_number = len(list(nodeset)) edge_number = len(list(edgeset)) del edgeset print "The network has", node_number, "nodes with", edge_number, "edges." graph_linklist = [set() for i in range(0, node_number)] # Initialize the graph in the format of linked list del nodeset for i in range(node_number): graph_linklist[i].add(i) with open(filename, 'U') as f: for line in f.readlines(): if not line.strip().startswith("#"): L = line.strip().split(delimiter) ni, nj = nodetype(L[0]), nodetype(L[1]) if ni != nj: a = ni - 1 b = nj - 1 graph_linklist[a].add(b) graph_linklist[b].add(a) gc.collect() degree = [] for node in range(node_number): degree.append(len(graph_linklist[node])) print "Finish constructing graph." print "-------------------------------------------------------" return graph_linklist, node_number, edge_number, degree
[ "def", "read_edge_list", "(", "filename", ",", "delimiter", "=", "None", ",", "nodetype", "=", "int", ")", ":", "edgeset", "=", "set", "(", ")", "nodeset", "=", "set", "(", ")", "print", "\"Reading the edgelist...\"", "with", "open", "(", "filename", ")", ...
https://github.com/RapidsAtHKUST/CommunityDetectionCodes/blob/23dbafd2e57ab0f5f0528b1322c4a409f21e5892/Algorithms/2015-LEMON/python_yche_refactor/io_helper.py#L14-L61
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/msvc.py
python
msvc9_query_vcvarsall
(ver, arch='x86', *args, **kwargs)
Patched "distutils.msvc9compiler.query_vcvarsall" for support extra compilers. Set environment without use of "vcvarsall.bat". Known supported compilers ------------------------- Microsoft Visual C++ 9.0: Microsoft Visual C++ Compiler for Python 2.7 (x86, amd64) Microsoft Windows SDK 6.1 (x86, x64, ia64) Microsoft Windows SDK 7.0 (x86, x64, ia64) Microsoft Visual C++ 10.0: Microsoft Windows SDK 7.1 (x86, x64, ia64) Parameters ---------- ver: float Required Microsoft Visual C++ version. arch: str Target architecture. Return ------ environment: dict
Patched "distutils.msvc9compiler.query_vcvarsall" for support extra compilers.
[ "Patched", "distutils", ".", "msvc9compiler", ".", "query_vcvarsall", "for", "support", "extra", "compilers", "." ]
def msvc9_query_vcvarsall(ver, arch='x86', *args, **kwargs): """ Patched "distutils.msvc9compiler.query_vcvarsall" for support extra compilers. Set environment without use of "vcvarsall.bat". Known supported compilers ------------------------- Microsoft Visual C++ 9.0: Microsoft Visual C++ Compiler for Python 2.7 (x86, amd64) Microsoft Windows SDK 6.1 (x86, x64, ia64) Microsoft Windows SDK 7.0 (x86, x64, ia64) Microsoft Visual C++ 10.0: Microsoft Windows SDK 7.1 (x86, x64, ia64) Parameters ---------- ver: float Required Microsoft Visual C++ version. arch: str Target architecture. Return ------ environment: dict """ # Try to get environement from vcvarsall.bat (Classical way) try: orig = get_unpatched(msvc9_query_vcvarsall) return orig(ver, arch, *args, **kwargs) except distutils.errors.DistutilsPlatformError: # Pass error if Vcvarsall.bat is missing pass except ValueError: # Pass error if environment not set after executing vcvarsall.bat pass # If error, try to set environment directly try: return EnvironmentInfo(arch, ver).return_env() except distutils.errors.DistutilsPlatformError as exc: _augment_exception(exc, ver, arch) raise
[ "def", "msvc9_query_vcvarsall", "(", "ver", ",", "arch", "=", "'x86'", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Try to get environement from vcvarsall.bat (Classical way)", "try", ":", "orig", "=", "get_unpatched", "(", "msvc9_query_vcvarsall", ")", ...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/msvc.py#L106-L150
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/_common.py
python
wrap_numbers
(input_dict, name)
Given an `input_dict` and a function `name`, adjust the numbers which "wrap" (restart from zero) across different calls by adding "old value" to "new value" and return an updated dict.
Given an `input_dict` and a function `name`, adjust the numbers which "wrap" (restart from zero) across different calls by adding "old value" to "new value" and return an updated dict.
[ "Given", "an", "input_dict", "and", "a", "function", "name", "adjust", "the", "numbers", "which", "wrap", "(", "restart", "from", "zero", ")", "across", "different", "calls", "by", "adding", "old", "value", "to", "new", "value", "and", "return", "an", "upd...
def wrap_numbers(input_dict, name): """Given an `input_dict` and a function `name`, adjust the numbers which "wrap" (restart from zero) across different calls by adding "old value" to "new value" and return an updated dict. """ with _wn.lock: return _wn.run(input_dict, name)
[ "def", "wrap_numbers", "(", "input_dict", ",", "name", ")", ":", "with", "_wn", ".", "lock", ":", "return", "_wn", ".", "run", "(", "input_dict", ",", "name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/psutil/_common.py#L698-L704
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pickletools.py
python
genops
(pickle)
return _genops(pickle)
Generate all the opcodes in a pickle. 'pickle' is a file-like object, or string, containing the pickle. Each opcode in the pickle is generated, from the current pickle position, stopping after a STOP opcode is delivered. A triple is generated for each opcode: opcode, arg, pos opcode is an OpcodeInfo record, describing the current opcode. If the opcode has an argument embedded in the pickle, arg is its decoded value, as a Python object. If the opcode doesn't have an argument, arg is None. If the pickle has a tell() method, pos was the value of pickle.tell() before reading the current opcode. If the pickle is a bytes object, it's wrapped in a BytesIO object, and the latter's tell() result is used. Else (the pickle doesn't have a tell(), and it's not obvious how to query its current position) pos is None.
Generate all the opcodes in a pickle.
[ "Generate", "all", "the", "opcodes", "in", "a", "pickle", "." ]
def genops(pickle): """Generate all the opcodes in a pickle. 'pickle' is a file-like object, or string, containing the pickle. Each opcode in the pickle is generated, from the current pickle position, stopping after a STOP opcode is delivered. A triple is generated for each opcode: opcode, arg, pos opcode is an OpcodeInfo record, describing the current opcode. If the opcode has an argument embedded in the pickle, arg is its decoded value, as a Python object. If the opcode doesn't have an argument, arg is None. If the pickle has a tell() method, pos was the value of pickle.tell() before reading the current opcode. If the pickle is a bytes object, it's wrapped in a BytesIO object, and the latter's tell() result is used. Else (the pickle doesn't have a tell(), and it's not obvious how to query its current position) pos is None. """ return _genops(pickle)
[ "def", "genops", "(", "pickle", ")", ":", "return", "_genops", "(", "pickle", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/pickletools.py#L2222-L2245
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pexpect/pexpect/screen.py
python
screen.lf
(self)
This moves the cursor down with scrolling.
This moves the cursor down with scrolling.
[ "This", "moves", "the", "cursor", "down", "with", "scrolling", "." ]
def lf (self): '''This moves the cursor down with scrolling. ''' old_r = self.cur_r self.cursor_down() if old_r == self.cur_r: self.scroll_up () self.erase_line()
[ "def", "lf", "(", "self", ")", ":", "old_r", "=", "self", ".", "cur_r", "self", ".", "cursor_down", "(", ")", "if", "old_r", "==", "self", ".", "cur_r", ":", "self", ".", "scroll_up", "(", ")", "self", ".", "erase_line", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pexpect/pexpect/screen.py#L176-L184
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/mimetypes.py
python
MimeTypes.readfp
(self, fp, strict=True)
Read a single mime.types-format file. If strict is true, information will be added to list of standard types, else to the list of non-standard types.
Read a single mime.types-format file.
[ "Read", "a", "single", "mime", ".", "types", "-", "format", "file", "." ]
def readfp(self, fp, strict=True): """ Read a single mime.types-format file. If strict is true, information will be added to list of standard types, else to the list of non-standard types. """ while 1: line = fp.readline() if not line: break words = line.split() for i in range(len(words)): if words[i][0] == '#': del words[i:] break if not words: continue type, suffixes = words[0], words[1:] for suff in suffixes: self.add_type(type, '.' + suff, strict)
[ "def", "readfp", "(", "self", ",", "fp", ",", "strict", "=", "True", ")", ":", "while", "1", ":", "line", "=", "fp", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "words", "=", "line", ".", "split", "(", ")", "for", "i", "in", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/mimetypes.py#L208-L229
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/eclib/filterdlg.py
python
FilterPanel.SetIncludes
(self, items)
return self._right.SetItems(items)
Set the items in the includes list @param items: list of strings
Set the items in the includes list @param items: list of strings
[ "Set", "the", "items", "in", "the", "includes", "list", "@param", "items", ":", "list", "of", "strings" ]
def SetIncludes(self, items): """Set the items in the includes list @param items: list of strings """ return self._right.SetItems(items)
[ "def", "SetIncludes", "(", "self", ",", "items", ")", ":", "return", "self", ".", "_right", ".", "SetItems", "(", "items", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/eclib/filterdlg.py#L110-L115
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/metrics_impl.py
python
_expand_and_tile
(tensor, multiple, dim=0, name=None)
Slice `tensor` shape in 2, then tile along the sliced dimension. A new dimension is inserted in shape of `tensor` before `dim`, then values are tiled `multiple` times along the new dimension. Args: tensor: Input `Tensor` or `SparseTensor`. multiple: Integer, number of times to tile. dim: Integer, dimension along which to tile. name: Name of operation. Returns: `Tensor` result of expanding and tiling `tensor`. Raises: ValueError: if `multiple` is less than 1, or `dim` is not in `[-rank(tensor), rank(tensor)]`.
Slice `tensor` shape in 2, then tile along the sliced dimension.
[ "Slice", "tensor", "shape", "in", "2", "then", "tile", "along", "the", "sliced", "dimension", "." ]
def _expand_and_tile(tensor, multiple, dim=0, name=None): """Slice `tensor` shape in 2, then tile along the sliced dimension. A new dimension is inserted in shape of `tensor` before `dim`, then values are tiled `multiple` times along the new dimension. Args: tensor: Input `Tensor` or `SparseTensor`. multiple: Integer, number of times to tile. dim: Integer, dimension along which to tile. name: Name of operation. Returns: `Tensor` result of expanding and tiling `tensor`. Raises: ValueError: if `multiple` is less than 1, or `dim` is not in `[-rank(tensor), rank(tensor)]`. """ if multiple < 1: raise ValueError('Invalid multiple %s, must be > 0.' % multiple) with ops.name_scope( name, 'expand_and_tile', (tensor, multiple, dim)) as scope: # Sparse. tensor = sparse_tensor.convert_to_tensor_or_sparse_tensor(tensor) if isinstance(tensor, sparse_tensor.SparseTensor): if dim < 0: expand_dims = array_ops.reshape( array_ops.size(tensor.dense_shape) + dim, [1]) else: expand_dims = [dim] expanded_shape = array_ops.concat( (array_ops.slice(tensor.dense_shape, [0], expand_dims), [1], array_ops.slice(tensor.dense_shape, expand_dims, [-1])), 0, name='expanded_shape') expanded = sparse_ops.sparse_reshape( tensor, shape=expanded_shape, name='expand') if multiple == 1: return expanded return sparse_ops.sparse_concat( dim - 1 if dim < 0 else dim, [expanded] * multiple, name=scope) # Dense. expanded = array_ops.expand_dims( tensor, dim if (dim >= 0) else (dim - 1), name='expand') if multiple == 1: return expanded ones = array_ops.ones_like(array_ops.shape(tensor)) tile_multiples = array_ops.concat( (ones[:dim], (multiple,), ones[dim:]), 0, name='multiples') return array_ops.tile(expanded, tile_multiples, name=scope)
[ "def", "_expand_and_tile", "(", "tensor", ",", "multiple", ",", "dim", "=", "0", ",", "name", "=", "None", ")", ":", "if", "multiple", "<", "1", ":", "raise", "ValueError", "(", "'Invalid multiple %s, must be > 0.'", "%", "multiple", ")", "with", "ops", "....
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/metrics_impl.py#L2233-L2284
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
Clipboard.Clear
(*args, **kwargs)
return _misc_.Clipboard_Clear(*args, **kwargs)
Clear(self) Clears data from the clipboard object and also the system's clipboard if possible.
Clear(self)
[ "Clear", "(", "self", ")" ]
def Clear(*args, **kwargs): """ Clear(self) Clears data from the clipboard object and also the system's clipboard if possible. """ return _misc_.Clipboard_Clear(*args, **kwargs)
[ "def", "Clear", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "Clipboard_Clear", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L5865-L5872
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/logging/__init__.py
python
Handler.emit
(self, record)
Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError.
Do whatever it takes to actually log the specified logging record.
[ "Do", "whatever", "it", "takes", "to", "actually", "log", "the", "specified", "logging", "record", "." ]
def emit(self, record): """ Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError. """ raise NotImplementedError, 'emit must be implemented '\ 'by Handler subclasses'
[ "def", "emit", "(", "self", ",", "record", ")", ":", "raise", "NotImplementedError", ",", "'emit must be implemented '", "'by Handler subclasses'" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/logging/__init__.py#L650-L658
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
CommandEvent.__init__
(self, *args, **kwargs)
__init__(self, EventType commandType=wxEVT_NULL, int winid=0) -> CommandEvent This event class contains information about command events, which originate from a variety of simple controls, as well as menus and toolbars.
__init__(self, EventType commandType=wxEVT_NULL, int winid=0) -> CommandEvent
[ "__init__", "(", "self", "EventType", "commandType", "=", "wxEVT_NULL", "int", "winid", "=", "0", ")", "-", ">", "CommandEvent" ]
def __init__(self, *args, **kwargs): """ __init__(self, EventType commandType=wxEVT_NULL, int winid=0) -> CommandEvent This event class contains information about command events, which originate from a variety of simple controls, as well as menus and toolbars. """ _core_.CommandEvent_swiginit(self,_core_.new_CommandEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "CommandEvent_swiginit", "(", "self", ",", "_core_", ".", "new_CommandEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L5203-L5211
leela-zero/leela-zero
e3ed6310d33d75078ba74c3adf887d18439fc2e3
scripts/cpplint.py
python
CheckInvalidIncrement
(filename, clean_lines, linenum, error)
Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for invalid increment *count++.
[ "Checks", "for", "invalid", "increment", "*", "count", "++", "." ]
def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. 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] if _RE_PATTERN_INVALID_INCREMENT.match(line): error(filename, linenum, 'runtime/invalid_increment', 5, 'Changing pointer instead of value (or unused value of operator*).')
[ "def", "CheckInvalidIncrement", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "_RE_PATTERN_INVALID_INCREMENT", ".", "match", "(", "line", ")", ":", "error", ...
https://github.com/leela-zero/leela-zero/blob/e3ed6310d33d75078ba74c3adf887d18439fc2e3/scripts/cpplint.py#L1961-L1980
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/control/robotinterface.py
python
RobotInterfaceBase.reset
(self)
If the robot has a non-normal status code, attempt to reset it to normal operation. The caller should poll until status()=='ok'
If the robot has a non-normal status code, attempt to reset it to normal operation. The caller should poll until status()=='ok'
[ "If", "the", "robot", "has", "a", "non", "-", "normal", "status", "code", "attempt", "to", "reset", "it", "to", "normal", "operation", ".", "The", "caller", "should", "poll", "until", "status", "()", "==", "ok" ]
def reset(self) -> None: """If the robot has a non-normal status code, attempt to reset it to normal operation. The caller should poll until status()=='ok' """ raise NotImplementedError("Reset is not implemented")
[ "def", "reset", "(", "self", ")", "->", "None", ":", "raise", "NotImplementedError", "(", "\"Reset is not implemented\"", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/robotinterface.py#L369-L373
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/array_algos/replace.py
python
compare_or_regex_search
( a: ArrayLike, b: Scalar | Pattern, regex: bool, mask: np.ndarray )
return result
Compare two array-like inputs of the same shape or two scalar values Calls operator.eq or re.search, depending on regex argument. If regex is True, perform an element-wise regex matching. Parameters ---------- a : array-like b : scalar or regex pattern regex : bool mask : np.ndarray[bool] Returns ------- mask : array-like of bool
Compare two array-like inputs of the same shape or two scalar values
[ "Compare", "two", "array", "-", "like", "inputs", "of", "the", "same", "shape", "or", "two", "scalar", "values" ]
def compare_or_regex_search( a: ArrayLike, b: Scalar | Pattern, regex: bool, mask: np.ndarray ) -> ArrayLike | bool: """ Compare two array-like inputs of the same shape or two scalar values Calls operator.eq or re.search, depending on regex argument. If regex is True, perform an element-wise regex matching. Parameters ---------- a : array-like b : scalar or regex pattern regex : bool mask : np.ndarray[bool] Returns ------- mask : array-like of bool """ if isna(b): return ~mask def _check_comparison_types( result: ArrayLike | bool, a: ArrayLike, b: Scalar | Pattern ): """ Raises an error if the two arrays (a,b) cannot be compared. Otherwise, returns the comparison result as expected. """ if is_scalar(result) and isinstance(a, np.ndarray): type_names = [type(a).__name__, type(b).__name__] type_names[0] = f"ndarray(dtype={a.dtype})" raise TypeError( f"Cannot compare types {repr(type_names[0])} and {repr(type_names[1])}" ) if not regex: op = lambda x: operator.eq(x, b) else: op = np.vectorize( lambda x: bool(re.search(b, x)) if isinstance(x, str) and isinstance(b, (str, Pattern)) else False ) # GH#32621 use mask to avoid comparing to NAs if isinstance(a, np.ndarray): a = a[mask] if is_numeric_v_string_like(a, b): # GH#29553 avoid deprecation warnings from numpy return np.zeros(a.shape, dtype=bool) elif is_datetimelike_v_numeric(a, b): # GH#29553 avoid deprecation warnings from numpy _check_comparison_types(False, a, b) return False result = op(a) if isinstance(result, np.ndarray) and mask is not None: # The shape of the mask can differ to that of the result # since we may compare only a subset of a's or b's elements tmp = np.zeros(mask.shape, dtype=np.bool_) tmp[mask] = result result = tmp _check_comparison_types(result, a, b) return result
[ "def", "compare_or_regex_search", "(", "a", ":", "ArrayLike", ",", "b", ":", "Scalar", "|", "Pattern", ",", "regex", ":", "bool", ",", "mask", ":", "np", ".", "ndarray", ")", "->", "ArrayLike", "|", "bool", ":", "if", "isna", "(", "b", ")", ":", "r...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/array_algos/replace.py#L44-L115
grpc/grpc
27bc6fe7797e43298dc931b96dc57322d0852a9f
src/python/grpcio/grpc/framework/interfaces/face/face.py
python
Call.terminal_metadata
(self)
Accesses the terminal metadata from the service-side of the RPC. This method blocks until the value is available or is known not to have been emitted from the service-side of the RPC. Returns: The terminal metadata object emitted by the service-side of the RPC, or None if there was no such value.
Accesses the terminal metadata from the service-side of the RPC.
[ "Accesses", "the", "terminal", "metadata", "from", "the", "service", "-", "side", "of", "the", "RPC", "." ]
def terminal_metadata(self): """Accesses the terminal metadata from the service-side of the RPC. This method blocks until the value is available or is known not to have been emitted from the service-side of the RPC. Returns: The terminal metadata object emitted by the service-side of the RPC, or None if there was no such value. """ raise NotImplementedError()
[ "def", "terminal_metadata", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/grpc/grpc/blob/27bc6fe7797e43298dc931b96dc57322d0852a9f/src/python/grpcio/grpc/framework/interfaces/face/face.py#L210-L220
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/linear_model/base.py
python
_rescale_data
(X, y, sample_weight)
return X, y
Rescale data so as to support sample_weight
Rescale data so as to support sample_weight
[ "Rescale", "data", "so", "as", "to", "support", "sample_weight" ]
def _rescale_data(X, y, sample_weight): """Rescale data so as to support sample_weight""" n_samples = X.shape[0] sample_weight = sample_weight * np.ones(n_samples) sample_weight = np.sqrt(sample_weight) sw_matrix = sparse.dia_matrix((sample_weight, 0), shape=(n_samples, n_samples)) X = safe_sparse_dot(sw_matrix, X) y = safe_sparse_dot(sw_matrix, y) return X, y
[ "def", "_rescale_data", "(", "X", ",", "y", ",", "sample_weight", ")", ":", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "sample_weight", "=", "sample_weight", "*", "np", ".", "ones", "(", "n_samples", ")", "sample_weight", "=", "np", ".", "sqrt...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/linear_model/base.py#L213-L222
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/Crf.py
python
Crf.dropout_rate
(self, dropout_rate)
Sets the variational dropout rate.
Sets the variational dropout rate.
[ "Sets", "the", "variational", "dropout", "rate", "." ]
def dropout_rate(self, dropout_rate): """Sets the variational dropout rate. """ if float(dropout_rate) < 0 or float(dropout_rate) >= 1: raise ValueError('The `dropout_rate` must be in [0, 1).') self._internal.set_dropout_rate(float(dropout_rate))
[ "def", "dropout_rate", "(", "self", ",", "dropout_rate", ")", ":", "if", "float", "(", "dropout_rate", ")", "<", "0", "or", "float", "(", "dropout_rate", ")", ">=", "1", ":", "raise", "ValueError", "(", "'The `dropout_rate` must be in [0, 1).'", ")", "self", ...
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Crf.py#L138-L144
scribusproject/scribus
41ec7c775a060912cf251682a8b1437f753f80f4
codegen/cheetah/Cheetah/Tools/MondoReport.py
python
RecordStats.__call__
(self)
This instance is not callable, so we override the super method.
This instance is not callable, so we override the super method.
[ "This", "instance", "is", "not", "callable", "so", "we", "override", "the", "super", "method", "." ]
def __call__(self): # Overrides IndexFormats.__call__ """This instance is not callable, so we override the super method. """ raise NotImplementedError()
[ "def", "__call__", "(", "self", ")", ":", "# Overrides IndexFormats.__call__", "raise", "NotImplementedError", "(", ")" ]
https://github.com/scribusproject/scribus/blob/41ec7c775a060912cf251682a8b1437f753f80f4/codegen/cheetah/Cheetah/Tools/MondoReport.py#L240-L243
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_windows.py
python
Dialog.ShowWindowModal
(*args, **kwargs)
return _windows_.Dialog_ShowWindowModal(*args, **kwargs)
ShowWindowModal(self)
ShowWindowModal(self)
[ "ShowWindowModal", "(", "self", ")" ]
def ShowWindowModal(*args, **kwargs): """ShowWindowModal(self)""" return _windows_.Dialog_ShowWindowModal(*args, **kwargs)
[ "def", "ShowWindowModal", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "Dialog_ShowWindowModal", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_windows.py#L811-L813
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
src/cephadm/box/util.py
python
Target.set_args
(self)
adding the required arguments of the target should go here, example: self.parser.add_argument(..)
adding the required arguments of the target should go here, example: self.parser.add_argument(..)
[ "adding", "the", "required", "arguments", "of", "the", "target", "should", "go", "here", "example", ":", "self", ".", "parser", ".", "add_argument", "(", "..", ")" ]
def set_args(self): """ adding the required arguments of the target should go here, example: self.parser.add_argument(..) """ raise NotImplementedError()
[ "def", "set_args", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/src/cephadm/box/util.py#L36-L41
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
GraphicsGradientStops.__len__
(*args, **kwargs)
return _gdi_.GraphicsGradientStops___len__(*args, **kwargs)
__len__(self) -> unsigned int
__len__(self) -> unsigned int
[ "__len__", "(", "self", ")", "-", ">", "unsigned", "int" ]
def __len__(*args, **kwargs): """__len__(self) -> unsigned int""" return _gdi_.GraphicsGradientStops___len__(*args, **kwargs)
[ "def", "__len__", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "GraphicsGradientStops___len__", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L5957-L5959
tensorflow/io
92b44e180674a8af0e12e405530f7343e3e693e4
tensorflow_io/python/ops/io_tensor.py
python
IOTensor.from_csv
(cls, filename, **kwargs)
Creates an `IOTensor` from an csv file. Args: filename: A string, the filename of an csv file. name: A name prefix for the IOTensor (optional). Returns: A `IOTensor`.
Creates an `IOTensor` from an csv file.
[ "Creates", "an", "IOTensor", "from", "an", "csv", "file", "." ]
def from_csv(cls, filename, **kwargs): """Creates an `IOTensor` from an csv file. Args: filename: A string, the filename of an csv file. name: A name prefix for the IOTensor (optional). Returns: A `IOTensor`. """ with tf.name_scope(kwargs.get("name", "IOFromCSV")): return csv_io_tensor_ops.CSVIOTensor(filename, internal=True)
[ "def", "from_csv", "(", "cls", ",", "filename", ",", "*", "*", "kwargs", ")", ":", "with", "tf", ".", "name_scope", "(", "kwargs", ".", "get", "(", "\"name\"", ",", "\"IOFromCSV\"", ")", ")", ":", "return", "csv_io_tensor_ops", ".", "CSVIOTensor", "(", ...
https://github.com/tensorflow/io/blob/92b44e180674a8af0e12e405530f7343e3e693e4/tensorflow_io/python/ops/io_tensor.py#L381-L393
OpenNI/OpenNI
1e9524ffd759841789dadb4ca19fb5d4ac5820e7
Platform/Win32/Driver/Build/UpdateVersion.py
python
regx_replace
(findStr,repStr,filePath)
replaces all findStr by repStr in file filePath using regualr expression
replaces all findStr by repStr in file filePath using regualr expression
[ "replaces", "all", "findStr", "by", "repStr", "in", "file", "filePath", "using", "regualr", "expression" ]
def regx_replace(findStr,repStr,filePath): "replaces all findStr by repStr in file filePath using regualr expression" findStrRegx = re.compile(findStr) tempName=filePath+'~~~' os.system("attrib -r " + filePath) input = open(filePath) output = open(tempName,'w') for s in input: output.write(findStrRegx.sub(repStr,s)) output.close() input.close() os.remove(filePath) os.rename(tempName,filePath)
[ "def", "regx_replace", "(", "findStr", ",", "repStr", ",", "filePath", ")", ":", "findStrRegx", "=", "re", ".", "compile", "(", "findStr", ")", "tempName", "=", "filePath", "+", "'~~~'", "os", ".", "system", "(", "\"attrib -r \"", "+", "filePath", ")", "...
https://github.com/OpenNI/OpenNI/blob/1e9524ffd759841789dadb4ca19fb5d4ac5820e7/Platform/Win32/Driver/Build/UpdateVersion.py#L35-L47
papyrussolution/OpenPapyrus
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/well_known_types.py
python
Timestamp.FromDatetime
(self, dt)
Converts datetime to Timestamp.
Converts datetime to Timestamp.
[ "Converts", "datetime", "to", "Timestamp", "." ]
def FromDatetime(self, dt): """Converts datetime to Timestamp.""" # Using this guide: http://wiki.python.org/moin/WorkingWithTime # And this conversion guide: http://docs.python.org/library/time.html # Turn the date parameter into a tuple (struct_time) that can then be # manipulated into a long value of seconds. During the conversion from # struct_time to long, the source date in UTC, and so it follows that the # correct transformation is calendar.timegm() self.seconds = calendar.timegm(dt.utctimetuple()) self.nanos = dt.microsecond * _NANOS_PER_MICROSECOND
[ "def", "FromDatetime", "(", "self", ",", "dt", ")", ":", "# Using this guide: http://wiki.python.org/moin/WorkingWithTime", "# And this conversion guide: http://docs.python.org/library/time.html", "# Turn the date parameter into a tuple (struct_time) that can then be", "# manipulated into a lo...
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/internal/well_known_types.py#L240-L250
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/mimetypes.py
python
guess_extension
(type, strict=True)
return _db.guess_extension(type, strict)
Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types.
Guess the extension for a file based on its MIME type.
[ "Guess", "the", "extension", "for", "a", "file", "based", "on", "its", "MIME", "type", "." ]
def guess_extension(type, strict=True): """Guess the extension for a file based on its MIME type. Return value is a string giving a filename extension, including the leading dot ('.'). The extension is not guaranteed to have been associated with any particular data stream, but would be mapped to the MIME type `type' by guess_type(). If no extension can be guessed for `type', None is returned. Optional `strict' argument when false adds a bunch of commonly found, but non-standard types. """ if _db is None: init() return _db.guess_extension(type, strict)
[ "def", "guess_extension", "(", "type", ",", "strict", "=", "True", ")", ":", "if", "_db", "is", "None", ":", "init", "(", ")", "return", "_db", ".", "guess_extension", "(", "type", ",", "strict", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/mimetypes.py#L312-L326
linyouhappy/kongkongxiyou
7a69b2913eb29f4be77f9a62fb90cdd72c4160f1
cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py
python
Cursor.is_static_method
(self)
return conf.lib.clang_CXXMethod_isStatic(self)
Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'.
Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'.
[ "Returns", "True", "if", "the", "cursor", "refers", "to", "a", "C", "++", "member", "function", "or", "member", "function", "template", "that", "is", "declared", "static", "." ]
def is_static_method(self): """Returns True if the cursor refers to a C++ member function or member function template that is declared 'static'. """ return conf.lib.clang_CXXMethod_isStatic(self)
[ "def", "is_static_method", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_CXXMethod_isStatic", "(", "self", ")" ]
https://github.com/linyouhappy/kongkongxiyou/blob/7a69b2913eb29f4be77f9a62fb90cdd72c4160f1/cocosjs/frameworks/cocos2d-x/tools/bindings-generator/clang/cindex.py#L1219-L1223
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
Treebook.ExpandNode
(*args, **kwargs)
return _controls_.Treebook_ExpandNode(*args, **kwargs)
ExpandNode(self, size_t pos, bool expand=True) -> bool
ExpandNode(self, size_t pos, bool expand=True) -> bool
[ "ExpandNode", "(", "self", "size_t", "pos", "bool", "expand", "=", "True", ")", "-", ">", "bool" ]
def ExpandNode(*args, **kwargs): """ExpandNode(self, size_t pos, bool expand=True) -> bool""" return _controls_.Treebook_ExpandNode(*args, **kwargs)
[ "def", "ExpandNode", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "Treebook_ExpandNode", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L3327-L3329
cyberbotics/webots
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
scripts/image_tools/images/regular_image.py
python
RegularImage.create_black_image
(cls, width, height)
return ri
Create an black image.
Create an black image.
[ "Create", "an", "black", "image", "." ]
def create_black_image(cls, width, height): """Create an black image.""" ri = RegularImage() ri.im = Image.new('RGB', (width, height)) ri.width = width ri.height = height return ri
[ "def", "create_black_image", "(", "cls", ",", "width", ",", "height", ")", ":", "ri", "=", "RegularImage", "(", ")", "ri", ".", "im", "=", "Image", ".", "new", "(", "'RGB'", ",", "(", "width", ",", "height", ")", ")", "ri", ".", "width", "=", "wi...
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/scripts/image_tools/images/regular_image.py#L28-L34
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/filters.py
python
do_replace
(eval_ctx, s, old, new, count=None)
return s.replace(soft_unicode(old), soft_unicode(new), count)
Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the first ``count`` occurrences are replaced: .. sourcecode:: jinja {{ "Hello World"|replace("Hello", "Goodbye") }} -> Goodbye World {{ "aaaaargh"|replace("a", "d'oh, ", 2) }} -> d'oh, d'oh, aaargh
Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the first ``count`` occurrences are replaced:
[ "Return", "a", "copy", "of", "the", "value", "with", "all", "occurrences", "of", "a", "substring", "replaced", "with", "a", "new", "one", ".", "The", "first", "argument", "is", "the", "substring", "that", "should", "be", "replaced", "the", "second", "is", ...
def do_replace(eval_ctx, s, old, new, count=None): """Return a copy of the value with all occurrences of a substring replaced with a new one. The first argument is the substring that should be replaced, the second is the replacement string. If the optional third argument ``count`` is given, only the first ``count`` occurrences are replaced: .. sourcecode:: jinja {{ "Hello World"|replace("Hello", "Goodbye") }} -> Goodbye World {{ "aaaaargh"|replace("a", "d'oh, ", 2) }} -> d'oh, d'oh, aaargh """ if count is None: count = -1 if not eval_ctx.autoescape: return text_type(s).replace(text_type(old), text_type(new), count) if hasattr(old, '__html__') or hasattr(new, '__html__') and \ not hasattr(s, '__html__'): s = escape(s) else: s = soft_unicode(s) return s.replace(soft_unicode(old), soft_unicode(new), count)
[ "def", "do_replace", "(", "eval_ctx", ",", "s", ",", "old", ",", "new", ",", "count", "=", "None", ")", ":", "if", "count", "is", "None", ":", "count", "=", "-", "1", "if", "not", "eval_ctx", ".", "autoescape", ":", "return", "text_type", "(", "s",...
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/filters.py#L116-L140