nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_gdi.py
python
DC.DrawBitmap
(*args, **kwargs)
return _gdi_.DC_DrawBitmap(*args, **kwargs)
DrawBitmap(self, Bitmap bmp, int x, int y, bool useMask=False) Draw a bitmap on the device context at the specified point. If *transparent* is true and the bitmap has a transparency mask, (or alpha channel on the platforms that support it) then the bitmap will be drawn transparently.
DrawBitmap(self, Bitmap bmp, int x, int y, bool useMask=False)
[ "DrawBitmap", "(", "self", "Bitmap", "bmp", "int", "x", "int", "y", "bool", "useMask", "=", "False", ")" ]
def DrawBitmap(*args, **kwargs): """ DrawBitmap(self, Bitmap bmp, int x, int y, bool useMask=False) Draw a bitmap on the device context at the specified point. If *transparent* is true and the bitmap has a transparency mask, (or alpha channel on the platforms that support it) then the bitmap will be drawn transparently. """ return _gdi_.DC_DrawBitmap(*args, **kwargs)
[ "def", "DrawBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "DC_DrawBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_gdi.py#L3689-L3698
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/YouCompleteMe/third_party/pythonfutures/concurrent/futures/_base.py
python
Executor.submit
(self, fn, *args, **kwargs)
Submits a callable to be executed with the given arguments. Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable. Returns: A Future representing the given call.
Submits a callable to be executed with the given arguments.
[ "Submits", "a", "callable", "to", "be", "executed", "with", "the", "given", "arguments", "." ]
def submit(self, fn, *args, **kwargs): """Submits a callable to be executed with the given arguments. Schedules the callable to be executed as fn(*args, **kwargs) and returns a Future instance representing the execution of the callable. Returns: A Future representing the given call. """ raise NotImplementedError()
[ "def", "submit", "(", "self", ",", "fn", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/pythonfutures/concurrent/futures/_base.py#L511-L520
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
GridCellBoolEditor.UseStringValues
(*args, **kwargs)
return _grid.GridCellBoolEditor_UseStringValues(*args, **kwargs)
UseStringValues(String valueTrue=OneString, String valueFalse=EmptyString)
UseStringValues(String valueTrue=OneString, String valueFalse=EmptyString)
[ "UseStringValues", "(", "String", "valueTrue", "=", "OneString", "String", "valueFalse", "=", "EmptyString", ")" ]
def UseStringValues(*args, **kwargs): """UseStringValues(String valueTrue=OneString, String valueFalse=EmptyString)""" return _grid.GridCellBoolEditor_UseStringValues(*args, **kwargs)
[ "def", "UseStringValues", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "GridCellBoolEditor_UseStringValues", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L460-L462
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py2/jinja2/runtime.py
python
make_logging_undefined
(logger=None, base=None)
return LoggingUndefined
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`.
Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created.
[ "Given", "a", "logger", "object", "this", "returns", "a", "new", "undefined", "class", "that", "will", "log", "certain", "failures", ".", "It", "will", "log", "iterations", "and", "printing", ".", "If", "no", "logger", "is", "given", "a", "default", "logge...
def make_logging_undefined(logger=None, base=None): """Given a logger object this returns a new undefined class that will log certain failures. It will log iterations and printing. If no logger is given a default logger is created. Example:: logger = logging.getLogger(__name__) LoggingUndefined = make_logging_undefined( logger=logger, base=Undefined ) .. versionadded:: 2.8 :param logger: the logger to use. If not provided, a default logger is created. :param base: the base class to add logging functionality to. This defaults to :class:`Undefined`. """ if logger is None: import logging logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler(sys.stderr)) if base is None: base = Undefined def _log_message(undef): if undef._undefined_hint is None: if undef._undefined_obj is missing: hint = "%s is undefined" % undef._undefined_name elif not isinstance(undef._undefined_name, string_types): hint = "%s has no element %s" % ( object_type_repr(undef._undefined_obj), undef._undefined_name, ) else: hint = "%s has no attribute %s" % ( object_type_repr(undef._undefined_obj), undef._undefined_name, ) else: hint = undef._undefined_hint logger.warning("Template variable warning: %s", hint) class LoggingUndefined(base): def _fail_with_undefined_error(self, *args, **kwargs): try: return base._fail_with_undefined_error(self, *args, **kwargs) except self._undefined_exception as e: logger.error("Template variable error: %s", str(e)) raise e def __str__(self): rv = base.__str__(self) _log_message(self) return rv def __iter__(self): rv = base.__iter__(self) _log_message(self) return rv if PY2: def __nonzero__(self): rv = base.__nonzero__(self) _log_message(self) return rv def __unicode__(self): rv = base.__unicode__(self) _log_message(self) return rv else: def __bool__(self): rv = base.__bool__(self) _log_message(self) return rv return LoggingUndefined
[ "def", "make_logging_undefined", "(", "logger", "=", "None", ",", "base", "=", "None", ")", ":", "if", "logger", "is", "None", ":", "import", "logging", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "addHandler", "(", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/runtime.py#L829-L912
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/dataclasses.py
python
fields
(class_or_instance)
return tuple(f for f in fields.values() if f._field_type is _FIELD)
Return a tuple describing the fields of this dataclass. Accepts a dataclass or an instance of one. Tuple elements are of type Field.
Return a tuple describing the fields of this dataclass.
[ "Return", "a", "tuple", "describing", "the", "fields", "of", "this", "dataclass", "." ]
def fields(class_or_instance): """Return a tuple describing the fields of this dataclass. Accepts a dataclass or an instance of one. Tuple elements are of type Field. """ # Might it be worth caching this, per class? try: fields = getattr(class_or_instance, _FIELDS) except AttributeError: raise TypeError('must be called with a dataclass type or instance') # Exclude pseudo-fields. Note that fields is sorted by insertion # order, so the order of the tuple is as the fields were defined. return tuple(f for f in fields.values() if f._field_type is _FIELD)
[ "def", "fields", "(", "class_or_instance", ")", ":", "# Might it be worth caching this, per class?", "try", ":", "fields", "=", "getattr", "(", "class_or_instance", ",", "_FIELDS", ")", "except", "AttributeError", ":", "raise", "TypeError", "(", "'must be called with a ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/dataclasses.py#L1013-L1028
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/dist.py
python
Distribution.__init__
(self, attrs=None)
Construct a new Distribution instance: initialize all the attributes of a Distribution, and then use 'attrs' (a dictionary mapping attribute names to values) to assign some of those attributes their "real" values. (Any attributes not mentioned in 'attrs' will be assigned to some null value: 0, None, an empty list or dictionary, etc.) Most importantly, initialize the 'command_obj' attribute to the empty dictionary; this will be filled in with real command objects by 'parse_command_line()'.
Construct a new Distribution instance: initialize all the attributes of a Distribution, and then use 'attrs' (a dictionary mapping attribute names to values) to assign some of those attributes their "real" values. (Any attributes not mentioned in 'attrs' will be assigned to some null value: 0, None, an empty list or dictionary, etc.) Most importantly, initialize the 'command_obj' attribute to the empty dictionary; this will be filled in with real command objects by 'parse_command_line()'.
[ "Construct", "a", "new", "Distribution", "instance", ":", "initialize", "all", "the", "attributes", "of", "a", "Distribution", "and", "then", "use", "attrs", "(", "a", "dictionary", "mapping", "attribute", "names", "to", "values", ")", "to", "assign", "some", ...
def __init__(self, attrs=None): """Construct a new Distribution instance: initialize all the attributes of a Distribution, and then use 'attrs' (a dictionary mapping attribute names to values) to assign some of those attributes their "real" values. (Any attributes not mentioned in 'attrs' will be assigned to some null value: 0, None, an empty list or dictionary, etc.) Most importantly, initialize the 'command_obj' attribute to the empty dictionary; this will be filled in with real command objects by 'parse_command_line()'. """ # Default values for our command-line options self.verbose = 1 self.dry_run = 0 self.help = 0 for attr in self.display_option_names: setattr(self, attr, 0) # Store the distribution meta-data (name, version, author, and so # forth) in a separate object -- we're getting to have enough # information here (and enough command-line options) that it's # worth it. Also delegate 'get_XXX()' methods to the 'metadata' # object in a sneaky and underhanded (but efficient!) way. self.metadata = DistributionMetadata() for basename in self.metadata._METHOD_BASENAMES: method_name = "get_" + basename setattr(self, method_name, getattr(self.metadata, method_name)) # 'cmdclass' maps command names to class objects, so we # can 1) quickly figure out which class to instantiate when # we need to create a new command object, and 2) have a way # for the setup script to override command classes self.cmdclass = {} # 'command_packages' is a list of packages in which commands # are searched for. The factory for command 'foo' is expected # to be named 'foo' in the module 'foo' in one of the packages # named here. This list is searched from the left; an error # is raised if no named package provides the command being # searched for. (Always access using get_command_packages().) self.command_packages = None # 'script_name' and 'script_args' are usually set to sys.argv[0] # and sys.argv[1:], but they can be overridden when the caller is # not necessarily a setup script run from the command-line. self.script_name = None self.script_args = None # 'command_options' is where we store command options between # parsing them (from config files, the command-line, etc.) and when # they are actually needed -- ie. when the command in question is # instantiated. It is a dictionary of dictionaries of 2-tuples: # command_options = { command_name : { option : (source, value) } } self.command_options = {} # 'dist_files' is the list of (command, pyversion, file) that # have been created by any dist commands run so far. This is # filled regardless of whether the run is dry or not. pyversion # gives sysconfig.get_python_version() if the dist file is # specific to a Python version, 'any' if it is good for all # Python versions on the target platform, and '' for a source # file. pyversion should not be used to specify minimum or # maximum required Python versions; use the metainfo for that # instead. self.dist_files = [] # These options are really the business of various commands, rather # than of the Distribution itself. We provide aliases for them in # Distribution as a convenience to the developer. self.packages = None self.package_data = {} self.package_dir = None self.py_modules = None self.libraries = None self.headers = None self.ext_modules = None self.ext_package = None self.include_dirs = None self.extra_path = None self.scripts = None self.data_files = None self.password = '' # And now initialize bookkeeping stuff that can't be supplied by # the caller at all. 'command_obj' maps command names to # Command instances -- that's how we enforce that every command # class is a singleton. self.command_obj = {} # 'have_run' maps command names to boolean values; it keeps track # of whether we have actually run a particular command, to make it # cheap to "run" a command whenever we think we might need to -- if # it's already been done, no need for expensive filesystem # operations, we just check the 'have_run' dictionary and carry on. # It's only safe to query 'have_run' for a command class that has # been instantiated -- a false value will be inserted when the # command object is created, and replaced with a true value when # the command is successfully run. Thus it's probably best to use # '.get()' rather than a straight lookup. self.have_run = {} # Now we'll use the attrs dictionary (ultimately, keyword args from # the setup script) to possibly override any or all of these # distribution options. if attrs: # Pull out the set of command options and work on them # specifically. Note that this order guarantees that aliased # command options will override any supplied redundantly # through the general options dictionary. options = attrs.get('options') if options is not None: del attrs['options'] for (command, cmd_options) in options.items(): opt_dict = self.get_option_dict(command) for (opt, val) in cmd_options.items(): opt_dict[opt] = ("setup script", val) if 'licence' in attrs: attrs['license'] = attrs['licence'] del attrs['licence'] msg = "'licence' distribution option is deprecated; use 'license'" if warnings is not None: warnings.warn(msg) else: sys.stderr.write(msg + "\n") # Now work on the rest of the attributes. Any attribute that's # not already defined is invalid! for (key, val) in attrs.items(): if hasattr(self.metadata, "set_" + key): getattr(self.metadata, "set_" + key)(val) elif hasattr(self.metadata, key): setattr(self.metadata, key, val) elif hasattr(self, key): setattr(self, key, val) else: msg = "Unknown distribution option: %s" % repr(key) warnings.warn(msg) # no-user-cfg is handled before other command line args # because other args override the config files, and this # one is needed before we can load the config files. # If attrs['script_args'] wasn't passed, assume false. # # This also make sure we just look at the global options self.want_user_cfg = True if self.script_args is not None: for arg in self.script_args: if not arg.startswith('-'): break if arg == '--no-user-cfg': self.want_user_cfg = False break self.finalize_options()
[ "def", "__init__", "(", "self", ",", "attrs", "=", "None", ")", ":", "# Default values for our command-line options", "self", ".", "verbose", "=", "1", "self", ".", "dry_run", "=", "0", "self", ".", "help", "=", "0", "for", "attr", "in", "self", ".", "di...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/dist.py#L136-L292
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/layers/python/layers/feature_column.py
python
_LazyBuilderByColumnsToTensor.get
(self, key)
return self._columns_to_tensors[key]
Gets the transformed feature column.
Gets the transformed feature column.
[ "Gets", "the", "transformed", "feature", "column", "." ]
def get(self, key): """Gets the transformed feature column.""" if key in self._columns_to_tensors: return self._columns_to_tensors[key] if isinstance(key, str): raise ValueError( "features dictionary doesn't contain key ({})".format(key)) if not isinstance(key, _FeatureColumn): raise TypeError('"key" must be either a "str" or "_FeatureColumn". ' "Provided: {}".format(key)) key.insert_transformed_feature(self._columns_to_tensors) return self._columns_to_tensors[key]
[ "def", "get", "(", "self", ",", "key", ")", ":", "if", "key", "in", "self", ".", "_columns_to_tensors", ":", "return", "self", ".", "_columns_to_tensors", "[", "key", "]", "if", "isinstance", "(", "key", ",", "str", ")", ":", "raise", "ValueError", "("...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/layers/python/layers/feature_column.py#L2360-L2372
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/ply/example/GardenSnake/GardenSnake.py
python
p_comparison
(p)
comparison : comparison PLUS comparison | comparison MINUS comparison | comparison MULT comparison | comparison DIV comparison | comparison LT comparison | comparison EQ comparison | comparison GT comparison | PLUS comparison | MINUS comparison | power
comparison : comparison PLUS comparison | comparison MINUS comparison | comparison MULT comparison | comparison DIV comparison | comparison LT comparison | comparison EQ comparison | comparison GT comparison | PLUS comparison | MINUS comparison | power
[ "comparison", ":", "comparison", "PLUS", "comparison", "|", "comparison", "MINUS", "comparison", "|", "comparison", "MULT", "comparison", "|", "comparison", "DIV", "comparison", "|", "comparison", "LT", "comparison", "|", "comparison", "EQ", "comparison", "|", "co...
def p_comparison(p): """comparison : comparison PLUS comparison | comparison MINUS comparison | comparison MULT comparison | comparison DIV comparison | comparison LT comparison | comparison EQ comparison | comparison GT comparison | PLUS comparison | MINUS comparison | power""" if len(p) == 4: p[0] = binary_ops[p[2]]((p[1], p[3])) elif len(p) == 3: p[0] = unary_ops[p[1]](p[2]) else: p[0] = p[1]
[ "def", "p_comparison", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "4", ":", "p", "[", "0", "]", "=", "binary_ops", "[", "p", "[", "2", "]", "]", "(", "(", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")", ")", "elif", "len", ...
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/GardenSnake/GardenSnake.py#L522-L538
metashell/metashell
f4177e4854ea00c8dbc722cadab26ef413d798ea
3rd/templight/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
IsDecltype
(clean_lines, linenum, column)
return False
Check if the token ending on (linenum, column) is decltype(). Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is decltype() expression, False otherwise.
Check if the token ending on (linenum, column) is decltype().
[ "Check", "if", "the", "token", "ending", "on", "(", "linenum", "column", ")", "is", "decltype", "()", "." ]
def IsDecltype(clean_lines, linenum, column): """Check if the token ending on (linenum, column) is decltype(). Args: clean_lines: A CleansedLines instance containing the file. linenum: the number of the line to check. column: end column of the token to check. Returns: True if this token is decltype() expression, False otherwise. """ (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column) if start_col < 0: return False if Search(r'\bdecltype\s*$', text[0:start_col]): return True return False
[ "def", "IsDecltype", "(", "clean_lines", ",", "linenum", ",", "column", ")", ":", "(", "text", ",", "_", ",", "start_col", ")", "=", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "column", ")", "if", "start_col", "<", "0", ":", "retu...
https://github.com/metashell/metashell/blob/f4177e4854ea00c8dbc722cadab26ef413d798ea/3rd/templight/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L3640-L3655
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/balloontip.py
python
BalloonTip.SetTitleColour
(self, colour=None)
Sets the colour for the top title. :param `colour`: a valid :class:`Colour` instance.
Sets the colour for the top title.
[ "Sets", "the", "colour", "for", "the", "top", "title", "." ]
def SetTitleColour(self, colour=None): """ Sets the colour for the top title. :param `colour`: a valid :class:`Colour` instance. """ if colour is None: colour = wx.BLACK self._balloontitlecolour = colour
[ "def", "SetTitleColour", "(", "self", ",", "colour", "=", "None", ")", ":", "if", "colour", "is", "None", ":", "colour", "=", "wx", ".", "BLACK", "self", ".", "_balloontitlecolour", "=", "colour" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/balloontip.py#L1010-L1020
InsightSoftwareConsortium/ITK
87acfce9a93d928311c38bc371b666b515b9f19d
Modules/ThirdParty/pygccxml/src/pygccxml/declarations/class_declaration.py
python
hierarchy_info_t.related_class
(self)
return self._related_class
reference to base or derived :class:`class <class_t>`
reference to base or derived :class:`class <class_t>`
[ "reference", "to", "base", "or", "derived", ":", "class", ":", "class", "<class_t", ">" ]
def related_class(self): """reference to base or derived :class:`class <class_t>`""" return self._related_class
[ "def", "related_class", "(", "self", ")", ":", "return", "self", ".", "_related_class" ]
https://github.com/InsightSoftwareConsortium/ITK/blob/87acfce9a93d928311c38bc371b666b515b9f19d/Modules/ThirdParty/pygccxml/src/pygccxml/declarations/class_declaration.py#L97-L99
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/processpool.py
python
TransferMonitor.notify_done
(self, transfer_id)
Notify a particular transfer is complete :param transfer_id: Unique identifier for the transfer
Notify a particular transfer is complete
[ "Notify", "a", "particular", "transfer", "is", "complete" ]
def notify_done(self, transfer_id): """Notify a particular transfer is complete :param transfer_id: Unique identifier for the transfer """ self._transfer_states[transfer_id].set_done()
[ "def", "notify_done", "(", "self", ",", "transfer_id", ")", ":", "self", ".", "_transfer_states", "[", "transfer_id", "]", ".", "set_done", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/s3transfer/processpool.py#L599-L604
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/serve/push/search/core/search_manager.py
python
SearchManager.HandlePingRequest
(self, request, response)
Handles ping database request. Args: request: request object. response: response object Raises: psycopg2.Error/Warning.
Handles ping database request.
[ "Handles", "ping", "database", "request", "." ]
def HandlePingRequest(self, request, response): """Handles ping database request. Args: request: request object. response: response object Raises: psycopg2.Error/Warning. """ cmd = request.GetParameter(constants.CMD) assert cmd == "Ping" # Fire off a pinq query to make sure we have a valid db connection. query_string = "SELECT 'ping'" results = self._DbQuery(query_string) if results and results[0] == "ping": http_io.ResponseWriter.AddBodyElement( response, constants.HDR_STATUS_CODE, constants.STATUS_SUCCESS) else: http_io.ResponseWriter.AddBodyElement( response, constants.HDR_STATUS_MESSAGE, "Cannot ping gesearch database.") http_io.ResponseWriter.AddBodyElement( response, constants.HDR_STATUS_CODE, constants.STATUS_FAILURE)
[ "def", "HandlePingRequest", "(", "self", ",", "request", ",", "response", ")", ":", "cmd", "=", "request", ".", "GetParameter", "(", "constants", ".", "CMD", ")", "assert", "cmd", "==", "\"Ping\"", "# Fire off a pinq query to make sure we have a valid db connection."...
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/serve/push/search/core/search_manager.py#L63-L85
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/landuse/landuse.py
python
Facilities.get_ids_building
(self, ids=None)
return ids[self.get_landusetypes().are_area[self.ids_landusetype[ids]] == False]
Returns all building type of facilities
Returns all building type of facilities
[ "Returns", "all", "building", "type", "of", "facilities" ]
def get_ids_building(self, ids=None): """Returns all building type of facilities""" # print 'get_ids_building' if ids is None: ids = self.get_ids() # debug #landusetypes = self.get_landusetypes() # for id_fac in ids[self.get_landusetypes().are_area[self.ids_landusetype[ids]] == False]: # id_landusetype = self.ids_landusetype[id_fac] # print ' id_fac',id_fac,id_landusetype,'is_area',landusetypes.are_area[id_landusetype] return ids[self.get_landusetypes().are_area[self.ids_landusetype[ids]] == False]
[ "def", "get_ids_building", "(", "self", ",", "ids", "=", "None", ")", ":", "# print 'get_ids_building'", "if", "ids", "is", "None", ":", "ids", "=", "self", ".", "get_ids", "(", ")", "# debug", "#landusetypes = self.get_landusetypes()", "# for id_fac in ids[self.ge...
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/landuse/landuse.py#L1536-L1547
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBHostOS_GetLLDBPath
(*args)
return _lldb.SBHostOS_GetLLDBPath(*args)
SBHostOS_GetLLDBPath(PathType path_type) -> SBFileSpec
SBHostOS_GetLLDBPath(PathType path_type) -> SBFileSpec
[ "SBHostOS_GetLLDBPath", "(", "PathType", "path_type", ")", "-", ">", "SBFileSpec" ]
def SBHostOS_GetLLDBPath(*args): """SBHostOS_GetLLDBPath(PathType path_type) -> SBFileSpec""" return _lldb.SBHostOS_GetLLDBPath(*args)
[ "def", "SBHostOS_GetLLDBPath", "(", "*", "args", ")", ":", "return", "_lldb", ".", "SBHostOS_GetLLDBPath", "(", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L5133-L5135
YannickJadoul/Parselmouth
355c4746531c948faaaf9b13b828e5afea621efd
pybind11/pybind11/setup_helpers.py
python
ParallelCompile.function
(self)
return compile_function
Builds a function object usable as distutils.ccompiler.CCompiler.compile.
Builds a function object usable as distutils.ccompiler.CCompiler.compile.
[ "Builds", "a", "function", "object", "usable", "as", "distutils", ".", "ccompiler", ".", "CCompiler", ".", "compile", "." ]
def function(self): """ Builds a function object usable as distutils.ccompiler.CCompiler.compile. """ def compile_function( compiler, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None, ): # These lines are directly from distutils.ccompiler.CCompiler macros, objects, extra_postargs, pp_opts, build = compiler._setup_compile( output_dir, macros, include_dirs, sources, depends, extra_postargs ) cc_args = compiler._get_cc_args(pp_opts, debug, extra_preargs) # The number of threads; start with default. threads = self.default # Determine the number of compilation threads, unless set by an environment variable. if self.envvar is not None: threads = int(os.environ.get(self.envvar, self.default)) def _single_compile(obj): try: src, ext = build[obj] except KeyError: return if not os.path.exists(obj) or self.needs_recompile(obj, src): compiler._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) try: import multiprocessing from multiprocessing.pool import ThreadPool except ImportError: threads = 1 if threads == 0: try: threads = multiprocessing.cpu_count() threads = self.max if self.max and self.max < threads else threads except NotImplementedError: threads = 1 if threads > 1: for _ in ThreadPool(threads).imap_unordered(_single_compile, objects): pass else: for ob in objects: _single_compile(ob) return objects return compile_function
[ "def", "function", "(", "self", ")", ":", "def", "compile_function", "(", "compiler", ",", "sources", ",", "output_dir", "=", "None", ",", "macros", "=", "None", ",", "include_dirs", "=", "None", ",", "debug", "=", "0", ",", "extra_preargs", "=", "None",...
https://github.com/YannickJadoul/Parselmouth/blob/355c4746531c948faaaf9b13b828e5afea621efd/pybind11/pybind11/setup_helpers.py#L372-L433
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/idl/idl/ast.py
python
ServerParameterClass.__init__
(self, file_name, line, column)
Construct a ServerParameterClass.
Construct a ServerParameterClass.
[ "Construct", "a", "ServerParameterClass", "." ]
def __init__(self, file_name, line, column): # type: (str, int, int) -> None """Construct a ServerParameterClass.""" self.name = None # type: str self.data = None # type: str self.override_ctor = False # type: bool self.override_set = False # type: bool super(ServerParameterClass, self).__init__(file_name, line, column)
[ "def", "__init__", "(", "self", ",", "file_name", ",", "line", ",", "column", ")", ":", "# type: (str, int, int) -> None", "self", ".", "name", "=", "None", "# type: str", "self", ".", "data", "=", "None", "# type: str", "self", ".", "override_ctor", "=", "F...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/idl/idl/ast.py#L386-L395
limbo018/DREAMPlace
146c3b9fd003d1acd52c96d9fd02e3f0a05154e4
dreamplace/PlaceObj.py
python
PlaceObj.build_weighted_average_wl
(self, params, placedb, data_collections, pin_pos_op)
return build_wirelength_op, build_update_gamma_op
@brief build the op to compute weighted average wirelength @param params parameters @param placedb placement database @param data_collections a collection of data and variables required for constructing ops @param pin_pos_op the op to compute pin locations according to cell locations
[]
def build_weighted_average_wl(self, params, placedb, data_collections, pin_pos_op): """ @brief build the op to compute weighted average wirelength @param params parameters @param placedb placement database @param data_collections a collection of data and variables required for constructing ops @param pin_pos_op the op to compute pin locations according to cell locations """ # use WeightedAverageWirelength atomic wirelength_for_pin_op = weighted_average_wirelength.WeightedAverageWirelength( flat_netpin=data_collections.flat_net2pin_map, netpin_start=data_collections.flat_net2pin_start_map, pin2net_map=data_collections.pin2net_map, net_weights=data_collections.net_weights, net_mask=data_collections.net_mask_ignore_large_degrees, pin_mask=data_collections.pin_mask_ignore_fixed_macros, gamma=self.gamma, algorithm='merged') # wirelength for position def build_wirelength_op(pos): return wirelength_for_pin_op(pin_pos_op(pos)) # update gamma base_gamma = self.base_gamma(params, placedb) def build_update_gamma_op(iteration, overflow): self.update_gamma(iteration, overflow, base_gamma) #logging.debug("update gamma to %g" % (wirelength_for_pin_op.gamma.data)) return build_wirelength_op, build_update_gamma_op
[ "def", "build_weighted_average_wl", "(", "self", ",", "params", ",", "placedb", ",", "data_collections", ",", "pin_pos_op", ")", ":", "# use WeightedAverageWirelength atomic", "wirelength_for_pin_op", "=", "weighted_average_wirelength", ".", "WeightedAverageWirelength", "(", ...
https://github.com/limbo018/DREAMPlace/blob/146c3b9fd003d1acd52c96d9fd02e3f0a05154e4/dreamplace/PlaceObj.py#L438-L470
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/distutils/_shell_utils.py
python
CommandLineParser.split
(cmd)
Split a command line string into a list of arguments
Split a command line string into a list of arguments
[ "Split", "a", "command", "line", "string", "into", "a", "list", "of", "arguments" ]
def split(cmd): """ Split a command line string into a list of arguments """ raise NotImplementedError
[ "def", "split", "(", "cmd", ")", ":", "raise", "NotImplementedError" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/distutils/_shell_utils.py#L30-L32
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-utils/modtool/templates/gr-newmod/docs/doxygen/other/doxypy.py
python
Doxypy.resetCommentSearch
(self, match)
Restarts a new comment search for a different triggering line. Closes the current commentblock and starts a new comment search.
Restarts a new comment search for a different triggering line.
[ "Restarts", "a", "new", "comment", "search", "for", "a", "different", "triggering", "line", "." ]
def resetCommentSearch(self, match): """Restarts a new comment search for a different triggering line. Closes the current commentblock and starts a new comment search. """ if args.debug: print("# CALLBACK: resetCommentSearch", file=sys.stderr) self.__closeComment() self.startCommentSearch(match)
[ "def", "resetCommentSearch", "(", "self", ",", "match", ")", ":", "if", "args", ".", "debug", ":", "print", "(", "\"# CALLBACK: resetCommentSearch\"", ",", "file", "=", "sys", ".", "stderr", ")", "self", ".", "__closeComment", "(", ")", "self", ".", "start...
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-utils/modtool/templates/gr-newmod/docs/doxygen/other/doxypy.py#L258-L266
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/grid.py
python
Grid.GetGridColLabelWindow
(*args, **kwargs)
return _grid.Grid_GetGridColLabelWindow(*args, **kwargs)
GetGridColLabelWindow(self) -> Window
GetGridColLabelWindow(self) -> Window
[ "GetGridColLabelWindow", "(", "self", ")", "-", ">", "Window" ]
def GetGridColLabelWindow(*args, **kwargs): """GetGridColLabelWindow(self) -> Window""" return _grid.Grid_GetGridColLabelWindow(*args, **kwargs)
[ "def", "GetGridColLabelWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_GetGridColLabelWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/grid.py#L2141-L2143
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
Log.SetComponentLevel
(*args, **kwargs)
return _misc_.Log_SetComponentLevel(*args, **kwargs)
SetComponentLevel(String component, LogLevel level)
SetComponentLevel(String component, LogLevel level)
[ "SetComponentLevel", "(", "String", "component", "LogLevel", "level", ")" ]
def SetComponentLevel(*args, **kwargs): """SetComponentLevel(String component, LogLevel level)""" return _misc_.Log_SetComponentLevel(*args, **kwargs)
[ "def", "SetComponentLevel", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "Log_SetComponentLevel", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L1481-L1483
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
samples/networking/01-simple-connection/client.py
python
GameClientRepository.connectSuccess
(self)
Successfully connected. But we still can't really do anything until we've got the doID range.
Successfully connected. But we still can't really do anything until we've got the doID range.
[ "Successfully", "connected", ".", "But", "we", "still", "can", "t", "really", "do", "anything", "until", "we", "ve", "got", "the", "doID", "range", "." ]
def connectSuccess(self): """ Successfully connected. But we still can't really do anything until we've got the doID range. """ # Mark interest for zone 1, 2 and 3. There won't be anything in them, # it's just to display how it works for this small example. self.setInterestZones([1, 2, 3]) # This method checks whether we actually have a valid doID range # to create distributed objects yet if self.haveCreateAuthority(): # we already have one self.gotCreateReady() else: # Not yet, keep waiting a bit longer. self.accept(self.uniqueName('createReady'), self.gotCreateReady)
[ "def", "connectSuccess", "(", "self", ")", ":", "# Mark interest for zone 1, 2 and 3. There won't be anything in them,", "# it's just to display how it works for this small example.", "self", ".", "setInterestZones", "(", "[", "1", ",", "2", ",", "3", "]", ")", "# This metho...
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/samples/networking/01-simple-connection/client.py#L87-L102
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/__init__.py
python
EntryPoint.parse_map
(cls, data, dist=None)
return maps
Parse a map of entry point groups
Parse a map of entry point groups
[ "Parse", "a", "map", "of", "entry", "point", "groups" ]
def parse_map(cls, data, dist=None): """Parse a map of entry point groups""" if isinstance(data, dict): data = data.items() else: data = split_sections(data) maps = {} for group, lines in data: if group is None: if not lines: continue raise ValueError("Entry points must be listed in groups") group = group.strip() if group in maps: raise ValueError("Duplicate group name", group) maps[group] = cls.parse_group(group, lines, dist) return maps
[ "def", "parse_map", "(", "cls", ",", "data", ",", "dist", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "data", "=", "data", ".", "items", "(", ")", "else", ":", "data", "=", "split_sections", "(", "data", ")", "m...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pkg_resources/__init__.py#L2539-L2555
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPMS_AUTH_COMMAND.fromBytes
(buffer)
return TpmBuffer(buffer).createObj(TPMS_AUTH_COMMAND)
Returns new TPMS_AUTH_COMMAND object constructed from its marshaled representation in the given byte buffer
Returns new TPMS_AUTH_COMMAND object constructed from its marshaled representation in the given byte buffer
[ "Returns", "new", "TPMS_AUTH_COMMAND", "object", "constructed", "from", "its", "marshaled", "representation", "in", "the", "given", "byte", "buffer" ]
def fromBytes(buffer): """ Returns new TPMS_AUTH_COMMAND object constructed from its marshaled representation in the given byte buffer """ return TpmBuffer(buffer).createObj(TPMS_AUTH_COMMAND)
[ "def", "fromBytes", "(", "buffer", ")", ":", "return", "TpmBuffer", "(", "buffer", ")", ".", "createObj", "(", "TPMS_AUTH_COMMAND", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L5549-L5553
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/protorpc/gen_protorpc.py
python
registry_command
(options, host, service_name=None, registry_path='/protorpc')
Generate source directory structure from remote registry service. Args: options: Parsed command line options. host: Web service host where registry service is located. May include port. service_name: Name of specific service to read. Will generate only Python files that service is dependent on. If None, will generate source code for all services known by the registry. registry_path: Path to find registry if not the default 'protorpc'.
Generate source directory structure from remote registry service.
[ "Generate", "source", "directory", "structure", "from", "remote", "registry", "service", "." ]
def registry_command(options, host, service_name=None, registry_path='/protorpc'): """Generate source directory structure from remote registry service. Args: options: Parsed command line options. host: Web service host where registry service is located. May include port. service_name: Name of specific service to read. Will generate only Python files that service is dependent on. If None, will generate source code for all services known by the registry. registry_path: Path to find registry if not the default 'protorpc'. """ dest_dir = os.path.expanduser(options.dest_dir) url = 'http://%s%s' % (host, registry_path) reg = registry.RegistryService.Stub(transport.HttpTransport(url)) if service_name is None: service_names = [service.name for service in reg.services().services] else: service_names = [service_name] file_set = reg.get_file_set(names=service_names).file_set for file_descriptor in file_set.files: generate_file_descriptor(dest_dir, file_descriptor=file_descriptor, force_overwrite=options.force)
[ "def", "registry_command", "(", "options", ",", "host", ",", "service_name", "=", "None", ",", "registry_path", "=", "'/protorpc'", ")", ":", "dest_dir", "=", "os", ".", "path", ".", "expanduser", "(", "options", ".", "dest_dir", ")", "url", "=", "'http://...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/protorpc/gen_protorpc.py#L219-L248
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/kfac/examples/convnet.py
python
_num_gradient_tasks
(num_tasks)
return int(np.ceil(0.6 * num_tasks))
Number of tasks that will update weights.
Number of tasks that will update weights.
[ "Number", "of", "tasks", "that", "will", "update", "weights", "." ]
def _num_gradient_tasks(num_tasks): """Number of tasks that will update weights.""" if num_tasks < 3: return num_tasks return int(np.ceil(0.6 * num_tasks))
[ "def", "_num_gradient_tasks", "(", "num_tasks", ")", ":", "if", "num_tasks", "<", "3", ":", "return", "num_tasks", "return", "int", "(", "np", ".", "ceil", "(", "0.6", "*", "num_tasks", ")", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/kfac/examples/convnet.py#L247-L251
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/contrib/graph_editor/util.py
python
check_graphs
(*args)
Check that all the element in args belong to the same graph. Args: *args: a list of object with a obj.graph property. Raises: ValueError: if all the elements do not belong to the same graph.
Check that all the element in args belong to the same graph.
[ "Check", "that", "all", "the", "element", "in", "args", "belong", "to", "the", "same", "graph", "." ]
def check_graphs(*args): """Check that all the element in args belong to the same graph. Args: *args: a list of object with a obj.graph property. Raises: ValueError: if all the elements do not belong to the same graph. """ graph = None for i, sgv in enumerate(args): if graph is None and sgv.graph is not None: graph = sgv.graph elif sgv.graph is not None and sgv.graph is not graph: raise ValueError("Argument[{}]: Wrong graph!".format(i))
[ "def", "check_graphs", "(", "*", "args", ")", ":", "graph", "=", "None", "for", "i", ",", "sgv", "in", "enumerate", "(", "args", ")", ":", "if", "graph", "is", "None", "and", "sgv", ".", "graph", "is", "not", "None", ":", "graph", "=", "sgv", "."...
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/contrib/graph_editor/util.py#L72-L85
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py
python
Menu.index
(self, index)
return self.tk.getint(i)
Return the index of a menu item identified by INDEX.
Return the index of a menu item identified by INDEX.
[ "Return", "the", "index", "of", "a", "menu", "item", "identified", "by", "INDEX", "." ]
def index(self, index): """Return the index of a menu item identified by INDEX.""" i = self.tk.call(self._w, 'index', index) if i == 'none': return None return self.tk.getint(i)
[ "def", "index", "(", "self", ",", "index", ")", ":", "i", "=", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'index'", ",", "index", ")", "if", "i", "==", "'none'", ":", "return", "None", "return", "self", ".", "tk", ".", "getin...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L2935-L2939
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/combo.py
python
ComboPopup.Create
(*args, **kwargs)
return _combo.ComboPopup_Create(*args, **kwargs)
Create(self, Window parent) -> bool The derived class must implement this method to create the popup control. It should be a child of the ``parent`` passed in, but other than that there is much flexibility in what the widget can be, its style, etc. Return ``True`` for success, ``False`` otherwise. (NOTE: this return value is not currently checked...)
Create(self, Window parent) -> bool
[ "Create", "(", "self", "Window", "parent", ")", "-", ">", "bool" ]
def Create(*args, **kwargs): """ Create(self, Window parent) -> bool The derived class must implement this method to create the popup control. It should be a child of the ``parent`` passed in, but other than that there is much flexibility in what the widget can be, its style, etc. Return ``True`` for success, ``False`` otherwise. (NOTE: this return value is not currently checked...) """ return _combo.ComboPopup_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "ComboPopup_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/combo.py#L621-L631
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/utils/git-svn/convert.py
python
do_convert
(file)
Skip all preceding mail message headers until 'From: ' is encountered. Then for each line ('From: ' header included), replace the dos style CRLF end-of-line with unix style LF end-of-line.
Skip all preceding mail message headers until 'From: ' is encountered. Then for each line ('From: ' header included), replace the dos style CRLF end-of-line with unix style LF end-of-line.
[ "Skip", "all", "preceding", "mail", "message", "headers", "until", "From", ":", "is", "encountered", ".", "Then", "for", "each", "line", "(", "From", ":", "header", "included", ")", "replace", "the", "dos", "style", "CRLF", "end", "-", "of", "-", "line",...
def do_convert(file): """Skip all preceding mail message headers until 'From: ' is encountered. Then for each line ('From: ' header included), replace the dos style CRLF end-of-line with unix style LF end-of-line. """ print "converting %s ..." % file with open(file, 'r') as f_in: content = f_in.read() # The new content to be written back to the same file. new_content = StringIO.StringIO() # Boolean flag controls whether to start printing lines. from_header_seen = False # By default, splitlines() don't include line breaks. CRLF should be gone. for line in content.splitlines(): # Wait till we scan the 'From: ' header before start printing the # lines. if not from_header_seen: if not line.startswith('From: '): continue else: from_header_seen = True print >> new_content, line with open(file, 'w') as f_out: f_out.write(new_content.getvalue()) print "done"
[ "def", "do_convert", "(", "file", ")", ":", "print", "\"converting %s ...\"", "%", "file", "with", "open", "(", "file", ",", "'r'", ")", "as", "f_in", ":", "content", "=", "f_in", ".", "read", "(", ")", "# The new content to be written back to the same file.", ...
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/utils/git-svn/convert.py#L27-L58
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/json_schema_compiler/cpp_type_generator.py
python
CppTypeGenerator.GetEnumNoneValue
(self, prop)
return '%s_NONE' % prop.unix_name.upper()
Gets the enum value in the given model.Property indicating no value has been set.
Gets the enum value in the given model.Property indicating no value has been set.
[ "Gets", "the", "enum", "value", "in", "the", "given", "model", ".", "Property", "indicating", "no", "value", "has", "been", "set", "." ]
def GetEnumNoneValue(self, prop): """Gets the enum value in the given model.Property indicating no value has been set. """ return '%s_NONE' % prop.unix_name.upper()
[ "def", "GetEnumNoneValue", "(", "self", ",", "prop", ")", ":", "return", "'%s_NONE'", "%", "prop", ".", "unix_name", ".", "upper", "(", ")" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/json_schema_compiler/cpp_type_generator.py#L89-L93
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pyrsistent/_field_common.py
python
field
(type=PFIELD_NO_TYPE, invariant=PFIELD_NO_INVARIANT, initial=PFIELD_NO_INITIAL, mandatory=False, factory=PFIELD_NO_FACTORY, serializer=PFIELD_NO_SERIALIZER)
return field
Field specification factory for :py:class:`PRecord`. :param type: a type or iterable with types that are allowed for this field :param invariant: a function specifying an invariant that must hold for the field :param initial: value of field if not specified when instantiating the record :param mandatory: boolean specifying if the field is mandatory or not :param factory: function called when field is set. :param serializer: function that returns a serialized version of the field
Field specification factory for :py:class:`PRecord`.
[ "Field", "specification", "factory", "for", ":", "py", ":", "class", ":", "PRecord", "." ]
def field(type=PFIELD_NO_TYPE, invariant=PFIELD_NO_INVARIANT, initial=PFIELD_NO_INITIAL, mandatory=False, factory=PFIELD_NO_FACTORY, serializer=PFIELD_NO_SERIALIZER): """ Field specification factory for :py:class:`PRecord`. :param type: a type or iterable with types that are allowed for this field :param invariant: a function specifying an invariant that must hold for the field :param initial: value of field if not specified when instantiating the record :param mandatory: boolean specifying if the field is mandatory or not :param factory: function called when field is set. :param serializer: function that returns a serialized version of the field """ # NB: We have to check this predicate separately from the predicates in # `maybe_parse_user_type` et al. because this one is related to supporting # the argspec for `field`, while those are related to supporting the valid # ways to specify types. # Multiple types must be passed in one of the following containers. Note # that a type that is a subclass of one of these containers, like a # `collections.namedtuple`, will work as expected, since we check # `isinstance` and not `issubclass`. if isinstance(type, (list, set, tuple)): types = set(maybe_parse_many_user_types(type)) else: types = set(maybe_parse_user_type(type)) invariant_function = wrap_invariant(invariant) if invariant != PFIELD_NO_INVARIANT and callable(invariant) else invariant field = _PField(type=types, invariant=invariant_function, initial=initial, mandatory=mandatory, factory=factory, serializer=serializer) _check_field_parameters(field) return field
[ "def", "field", "(", "type", "=", "PFIELD_NO_TYPE", ",", "invariant", "=", "PFIELD_NO_INVARIANT", ",", "initial", "=", "PFIELD_NO_INITIAL", ",", "mandatory", "=", "False", ",", "factory", "=", "PFIELD_NO_FACTORY", ",", "serializer", "=", "PFIELD_NO_SERIALIZER", ")...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/pyrsistent/_field_common.py#L104-L137
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
grc/core/base.py
python
Element.validate
(self)
Validate this element and call validate on all children. Call this base method before adding error messages in the subclass.
Validate this element and call validate on all children. Call this base method before adding error messages in the subclass.
[ "Validate", "this", "element", "and", "call", "validate", "on", "all", "children", ".", "Call", "this", "base", "method", "before", "adding", "error", "messages", "in", "the", "subclass", "." ]
def validate(self): """ Validate this element and call validate on all children. Call this base method before adding error messages in the subclass. """ for child in self.children(): child.validate()
[ "def", "validate", "(", "self", ")", ":", "for", "child", "in", "self", ".", "children", "(", ")", ":", "child", ".", "validate", "(", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/base.py#L21-L27
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
Window.GetScreenPosition
(*args, **kwargs)
return _core_.Window_GetScreenPosition(*args, **kwargs)
GetScreenPosition(self) -> Point Get the position of the window in screen coordinantes.
GetScreenPosition(self) -> Point
[ "GetScreenPosition", "(", "self", ")", "-", ">", "Point" ]
def GetScreenPosition(*args, **kwargs): """ GetScreenPosition(self) -> Point Get the position of the window in screen coordinantes. """ return _core_.Window_GetScreenPosition(*args, **kwargs)
[ "def", "GetScreenPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Window_GetScreenPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L9476-L9482
intel/llvm
e6d0547e9d99b5a56430c4749f6c7e328bf221ab
mlir/utils/spirv/gen_spirv_dialect.py
python
update_td_opcodes
(path, instructions, filter_list)
Updates SPIRBase.td with new generated opcode cases. Arguments: - path: the path to SPIRBase.td - instructions: a list containing all SPIR-V instructions' grammar - filter_list: a list containing new opnames to add
Updates SPIRBase.td with new generated opcode cases.
[ "Updates", "SPIRBase", ".", "td", "with", "new", "generated", "opcode", "cases", "." ]
def update_td_opcodes(path, instructions, filter_list): """Updates SPIRBase.td with new generated opcode cases. Arguments: - path: the path to SPIRBase.td - instructions: a list containing all SPIR-V instructions' grammar - filter_list: a list containing new opnames to add """ with open(path, 'r') as f: content = f.read() content = content.split(AUTOGEN_OPCODE_SECTION_MARKER) assert len(content) == 3 # Extend opcode list with existing list existing_opcodes = [k[11:] for k in re.findall('def SPV_OC_\w+', content[1])] filter_list.extend(existing_opcodes) filter_list = list(set(filter_list)) # Generate the opcode for all instructions in SPIR-V filter_instrs = list( filter(lambda inst: (inst['opname'] in filter_list), instructions)) # Sort instruction based on opcode filter_instrs.sort(key=lambda inst: inst['opcode']) opcode = gen_opcode(filter_instrs) # Substitute the opcode content = content[0] + AUTOGEN_OPCODE_SECTION_MARKER + '\n\n' + \ opcode + '\n\n// End ' + AUTOGEN_OPCODE_SECTION_MARKER \ + content[2] with open(path, 'w') as f: f.write(content)
[ "def", "update_td_opcodes", "(", "path", ",", "instructions", ",", "filter_list", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "content", "=", "f", ".", "read", "(", ")", "content", "=", "content", ".", "split", "(", "AUTOG...
https://github.com/intel/llvm/blob/e6d0547e9d99b5a56430c4749f6c7e328bf221ab/mlir/utils/spirv/gen_spirv_dialect.py#L532-L565
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
parserCtxt.parsePubidLiteral
(self)
return ret
parse an XML public literal [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
parse an XML public literal [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
[ "parse", "an", "XML", "public", "literal", "[", "12", "]", "PubidLiteral", "::", "=", "PubidChar", "*", "|", "(", "PubidChar", "-", ")", "*" ]
def parsePubidLiteral(self): """parse an XML public literal [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'" """ ret = libxml2mod.xmlParsePubidLiteral(self._o) return ret
[ "def", "parsePubidLiteral", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlParsePubidLiteral", "(", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L5407-L5411
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/tensor_forest/data/data_ops.py
python
ParseLabelTensorOrDict
(labels)
Return a tensor to use for input labels to tensor_forest. The incoming targets can be a dict where keys are the string names of the columns, which we turn into a single 1-D tensor for classification or 2-D tensor for regression. Converts sparse tensors to dense ones. Args: labels: `Tensor` or `dict` of `Tensor` objects. Returns: A 2-D tensor for labels/outputs.
Return a tensor to use for input labels to tensor_forest.
[ "Return", "a", "tensor", "to", "use", "for", "input", "labels", "to", "tensor_forest", "." ]
def ParseLabelTensorOrDict(labels): """Return a tensor to use for input labels to tensor_forest. The incoming targets can be a dict where keys are the string names of the columns, which we turn into a single 1-D tensor for classification or 2-D tensor for regression. Converts sparse tensors to dense ones. Args: labels: `Tensor` or `dict` of `Tensor` objects. Returns: A 2-D tensor for labels/outputs. """ if isinstance(labels, dict): return math_ops.to_float(array_ops.concat( 1, [sparse_ops.sparse_tensor_to_dense(labels[ k], default_value=-1) if isinstance(labels, ops.SparseTensor) else labels[k] for k in sorted(labels.keys())])) else: if isinstance(labels, ops.SparseTensor): return math_ops.to_float(sparse_ops.sparse_tensor_to_dense( labels, default_value=-1)) else: return math_ops.to_float(labels)
[ "def", "ParseLabelTensorOrDict", "(", "labels", ")", ":", "if", "isinstance", "(", "labels", ",", "dict", ")", ":", "return", "math_ops", ".", "to_float", "(", "array_ops", ".", "concat", "(", "1", ",", "[", "sparse_ops", ".", "sparse_tensor_to_dense", "(", ...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/tensor_forest/data/data_ops.py#L176-L201
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/distributions/python/ops/bijector.py
python
_Bijector.name
(self)
return self._name
Returns the string name of this `Bijector`.
Returns the string name of this `Bijector`.
[ "Returns", "the", "string", "name", "of", "this", "Bijector", "." ]
def name(self): """Returns the string name of this `Bijector`.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/distributions/python/ops/bijector.py#L235-L237
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.WriteList
(self, value_list, variable=None, prefix='', quoter=QuoteIfNecessary)
Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style.
Write a variable definition that is a list of values.
[ "Write", "a", "variable", "definition", "that", "is", "a", "list", "of", "values", "." ]
def WriteList(self, value_list, variable=None, prefix='', quoter=QuoteIfNecessary): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = '' if value_list: value_list = [quoter(prefix + l) for l in value_list] values = ' \\\n\t' + ' \\\n\t'.join(value_list) self.fp.write('%s :=%s\n\n' % (variable, values))
[ "def", "WriteList", "(", "self", ",", "value_list", ",", "variable", "=", "None", ",", "prefix", "=", "''", ",", "quoter", "=", "QuoteIfNecessary", ")", ":", "values", "=", "''", "if", "value_list", ":", "value_list", "=", "[", "quoter", "(", "prefix", ...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/gyp/pylib/gyp/generator/make.py#L1694-L1706
xhzdeng/crpn
a5aef0f80dbe486103123f740c634fb01e6cc9a1
caffe-fast-rcnn/python/caffe/classifier.py
python
Classifier.predict
(self, inputs, oversample=True)
return predictions
Predict classification probabilities of inputs. Parameters ---------- inputs : iterable of (H x W x K) input ndarrays. oversample : boolean average predictions across center, corners, and mirrors when True (default). Center-only prediction when False. Returns ------- predictions: (N x C) ndarray of class probabilities for N images and C classes.
Predict classification probabilities of inputs.
[ "Predict", "classification", "probabilities", "of", "inputs", "." ]
def predict(self, inputs, oversample=True): """ Predict classification probabilities of inputs. Parameters ---------- inputs : iterable of (H x W x K) input ndarrays. oversample : boolean average predictions across center, corners, and mirrors when True (default). Center-only prediction when False. Returns ------- predictions: (N x C) ndarray of class probabilities for N images and C classes. """ # Scale to standardize input dimensions. input_ = np.zeros((len(inputs), self.image_dims[0], self.image_dims[1], inputs[0].shape[2]), dtype=np.float32) for ix, in_ in enumerate(inputs): input_[ix] = caffe.io.resize_image(in_, self.image_dims) if oversample: # Generate center, corner, and mirrored crops. input_ = caffe.io.oversample(input_, self.crop_dims) else: # Take center crop. center = np.array(self.image_dims) / 2.0 crop = np.tile(center, (1, 2))[0] + np.concatenate([ -self.crop_dims / 2.0, self.crop_dims / 2.0 ]) crop = crop.astype(int) input_ = input_[:, crop[0]:crop[2], crop[1]:crop[3], :] # Classify caffe_in = np.zeros(np.array(input_.shape)[[0, 3, 1, 2]], dtype=np.float32) for ix, in_ in enumerate(input_): caffe_in[ix] = self.transformer.preprocess(self.inputs[0], in_) out = self.forward_all(**{self.inputs[0]: caffe_in}) predictions = out[self.outputs[0]] # For oversampling, average predictions across crops. if oversample: predictions = predictions.reshape((len(predictions) / 10, 10, -1)) predictions = predictions.mean(1) return predictions
[ "def", "predict", "(", "self", ",", "inputs", ",", "oversample", "=", "True", ")", ":", "# Scale to standardize input dimensions.", "input_", "=", "np", ".", "zeros", "(", "(", "len", "(", "inputs", ")", ",", "self", ".", "image_dims", "[", "0", "]", ","...
https://github.com/xhzdeng/crpn/blob/a5aef0f80dbe486103123f740c634fb01e6cc9a1/caffe-fast-rcnn/python/caffe/classifier.py#L47-L98
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/util/fslike/path.py
python
Path._resolve_w
(self)
return self.fsobj.resolve_w(self.parts)
Flatten the path recursively for write access. Used to cancel out some wrappers in between.
Flatten the path recursively for write access. Used to cancel out some wrappers in between.
[ "Flatten", "the", "path", "recursively", "for", "write", "access", ".", "Used", "to", "cancel", "out", "some", "wrappers", "in", "between", "." ]
def _resolve_w(self): """ Flatten the path recursively for write access. Used to cancel out some wrappers in between. """ return self.fsobj.resolve_w(self.parts)
[ "def", "_resolve_w", "(", "self", ")", ":", "return", "self", ".", "fsobj", ".", "resolve_w", "(", "self", ".", "parts", ")" ]
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/util/fslike/path.py#L158-L163
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/v7.9.317/third_party/jinja2/sandbox.py
python
modifies_known_mutable
(obj, attr)
return False
This function checks if an attribute on a builtin mutable object (list, dict, set or deque) would modify it if called. It also supports the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and with Python 2.6 onwards the abstract base classes `MutableSet`, `MutableMapping`, and `MutableSequence`. >>> modifies_known_mutable({}, "clear") True >>> modifies_known_mutable({}, "keys") False >>> modifies_known_mutable([], "append") True >>> modifies_known_mutable([], "index") False If called with an unsupported object (such as unicode) `False` is returned. >>> modifies_known_mutable("foo", "upper") False
This function checks if an attribute on a builtin mutable object (list, dict, set or deque) would modify it if called. It also supports the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and with Python 2.6 onwards the abstract base classes `MutableSet`, `MutableMapping`, and `MutableSequence`.
[ "This", "function", "checks", "if", "an", "attribute", "on", "a", "builtin", "mutable", "object", "(", "list", "dict", "set", "or", "deque", ")", "would", "modify", "it", "if", "called", ".", "It", "also", "supports", "the", "user", "-", "versions", "of"...
def modifies_known_mutable(obj, attr): """This function checks if an attribute on a builtin mutable object (list, dict, set or deque) would modify it if called. It also supports the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and with Python 2.6 onwards the abstract base classes `MutableSet`, `MutableMapping`, and `MutableSequence`. >>> modifies_known_mutable({}, "clear") True >>> modifies_known_mutable({}, "keys") False >>> modifies_known_mutable([], "append") True >>> modifies_known_mutable([], "index") False If called with an unsupported object (such as unicode) `False` is returned. >>> modifies_known_mutable("foo", "upper") False """ for typespec, unsafe in _mutable_spec: if isinstance(obj, typespec): return attr in unsafe return False
[ "def", "modifies_known_mutable", "(", "obj", ",", "attr", ")", ":", "for", "typespec", ",", "unsafe", "in", "_mutable_spec", ":", "if", "isinstance", "(", "obj", ",", "typespec", ")", ":", "return", "attr", "in", "unsafe", "return", "False" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/v7.9.317/third_party/jinja2/sandbox.py#L207-L232
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/gs/key.py
python
Key.set_contents_from_stream
(self, *args, **kwargs)
Store an object using the name of the Key object as the key in cloud and the contents of the data stream pointed to by 'fp' as the contents. The stream object is not seekable and total size is not known. This has the implication that we can't specify the Content-Size and Content-MD5 in the header. So for huge uploads, the delay in calculating MD5 is avoided but with a penalty of inability to verify the integrity of the uploaded data. :type fp: file :param fp: the file whose contents are to be uploaded :type headers: dict :param headers: additional HTTP headers to be sent with the PUT request. :type replace: bool :param replace: If this parameter is False, the method will first check to see if an object exists in the bucket with the same key. If it does, it won't overwrite it. The default value is True which will overwrite the object. :type cb: function :param cb: a callback function that will be called to report progress on the upload. The callback should accept two integer parameters, the first representing the number of bytes that have been successfully transmitted to GS and the second representing the total number of bytes that need to be transmitted. :type num_cb: int :param num_cb: (optional) If a callback is specified with the cb parameter, this parameter determines the granularity of the callback by defining the maximum number of times the callback will be called during the file transfer. :type policy: :class:`boto.gs.acl.CannedACLStrings` :param policy: A canned ACL policy that will be applied to the new key in GS. :type size: int :param size: (optional) The Maximum number of bytes to read from the file pointer (fp). This is useful when uploading a file in multiple parts where you are splitting the file up into different ranges to be uploaded. If not specified, the default behaviour is to read all bytes from the file pointer. Less bytes may be available. :type if_generation: int :param if_generation: (optional) If set to a generation number, the object will only be written to if its current generation number is this value. If set to the value 0, the object will only be written if it doesn't already exist.
Store an object using the name of the Key object as the key in cloud and the contents of the data stream pointed to by 'fp' as the contents.
[ "Store", "an", "object", "using", "the", "name", "of", "the", "Key", "object", "as", "the", "key", "in", "cloud", "and", "the", "contents", "of", "the", "data", "stream", "pointed", "to", "by", "fp", "as", "the", "contents", "." ]
def set_contents_from_stream(self, *args, **kwargs): """ Store an object using the name of the Key object as the key in cloud and the contents of the data stream pointed to by 'fp' as the contents. The stream object is not seekable and total size is not known. This has the implication that we can't specify the Content-Size and Content-MD5 in the header. So for huge uploads, the delay in calculating MD5 is avoided but with a penalty of inability to verify the integrity of the uploaded data. :type fp: file :param fp: the file whose contents are to be uploaded :type headers: dict :param headers: additional HTTP headers to be sent with the PUT request. :type replace: bool :param replace: If this parameter is False, the method will first check to see if an object exists in the bucket with the same key. If it does, it won't overwrite it. The default value is True which will overwrite the object. :type cb: function :param cb: a callback function that will be called to report progress on the upload. The callback should accept two integer parameters, the first representing the number of bytes that have been successfully transmitted to GS and the second representing the total number of bytes that need to be transmitted. :type num_cb: int :param num_cb: (optional) If a callback is specified with the cb parameter, this parameter determines the granularity of the callback by defining the maximum number of times the callback will be called during the file transfer. :type policy: :class:`boto.gs.acl.CannedACLStrings` :param policy: A canned ACL policy that will be applied to the new key in GS. :type size: int :param size: (optional) The Maximum number of bytes to read from the file pointer (fp). This is useful when uploading a file in multiple parts where you are splitting the file up into different ranges to be uploaded. If not specified, the default behaviour is to read all bytes from the file pointer. Less bytes may be available. :type if_generation: int :param if_generation: (optional) If set to a generation number, the object will only be written to if its current generation number is this value. If set to the value 0, the object will only be written if it doesn't already exist. """ if_generation = kwargs.pop('if_generation', None) if if_generation is not None: headers = kwargs.get('headers', {}) headers['x-goog-if-generation-match'] = str(if_generation) kwargs['headers'] = headers super(Key, self).set_contents_from_stream(*args, **kwargs)
[ "def", "set_contents_from_stream", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if_generation", "=", "kwargs", ".", "pop", "(", "'if_generation'", ",", "None", ")", "if", "if_generation", "is", "not", "None", ":", "headers", "=", "k...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/gs/key.py#L715-L777
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TNEANet.GetEdgeAttrValue
(self, *args)
return _snap.TNEANet_GetEdgeAttrValue(self, *args)
GetEdgeAttrValue(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> TStr Parameters: EId: int const & EdgeHI: TStrIntPrH::TIter const &
GetEdgeAttrValue(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> TStr
[ "GetEdgeAttrValue", "(", "TNEANet", "self", "int", "const", "&", "EId", "TStrIntPrH", "::", "TIter", "const", "&", "EdgeHI", ")", "-", ">", "TStr" ]
def GetEdgeAttrValue(self, *args): """ GetEdgeAttrValue(TNEANet self, int const & EId, TStrIntPrH::TIter const & EdgeHI) -> TStr Parameters: EId: int const & EdgeHI: TStrIntPrH::TIter const & """ return _snap.TNEANet_GetEdgeAttrValue(self, *args)
[ "def", "GetEdgeAttrValue", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TNEANet_GetEdgeAttrValue", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L22505-L22514
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/pylib/utils/reraiser_thread.py
python
ReraiserThreadGroup.Add
(self, thread)
Add a thread to the group. Args: thread: a ReraiserThread object.
Add a thread to the group.
[ "Add", "a", "thread", "to", "the", "group", "." ]
def Add(self, thread): """Add a thread to the group. Args: thread: a ReraiserThread object. """ self._threads.append(thread)
[ "def", "Add", "(", "self", ",", "thread", ")", ":", "self", ".", "_threads", ".", "append", "(", "thread", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/pylib/utils/reraiser_thread.py#L83-L89
zhaoweicai/cascade-rcnn
2252f46158ea6555868ca6fa5c221ea71d9b5e6c
scripts/cpp_lint.py
python
FileInfo.IsSource
(self)
return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
File has a source file extension.
File has a source file extension.
[ "File", "has", "a", "source", "file", "extension", "." ]
def IsSource(self): """File has a source file extension.""" return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
[ "def", "IsSource", "(", "self", ")", ":", "return", "self", ".", "Extension", "(", ")", "[", "1", ":", "]", "in", "(", "'c'", ",", "'cc'", ",", "'cpp'", ",", "'cxx'", ")" ]
https://github.com/zhaoweicai/cascade-rcnn/blob/2252f46158ea6555868ca6fa5c221ea71d9b5e6c/scripts/cpp_lint.py#L960-L962
p4lang/p4c
3272e79369f20813cc1a555a5eb26f44432f84a4
tools/stf/stf_parser.py
python
STFParser.p_priority
(self, p)
priority : INT_CONST_DEC
priority : INT_CONST_DEC
[ "priority", ":", "INT_CONST_DEC" ]
def p_priority(self, p): 'priority : INT_CONST_DEC' p[0] = p[1]
[ "def", "p_priority", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]" ]
https://github.com/p4lang/p4c/blob/3272e79369f20813cc1a555a5eb26f44432f84a4/tools/stf/stf_parser.py#L271-L273
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/wheel.py
python
Wheel.tags
(self)
return itertools.product( self.py_version.split('.'), self.abi.split('.'), self.platform.split('.'), )
List tags (py_version, abi, platform) supported by this wheel.
List tags (py_version, abi, platform) supported by this wheel.
[ "List", "tags", "(", "py_version", "abi", "platform", ")", "supported", "by", "this", "wheel", "." ]
def tags(self): '''List tags (py_version, abi, platform) supported by this wheel.''' return itertools.product( self.py_version.split('.'), self.abi.split('.'), self.platform.split('.'), )
[ "def", "tags", "(", "self", ")", ":", "return", "itertools", ".", "product", "(", "self", ".", "py_version", ".", "split", "(", "'.'", ")", ",", "self", ".", "abi", ".", "split", "(", "'.'", ")", ",", "self", ".", "platform", ".", "split", "(", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/setuptools/wheel.py#L66-L72
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/distributions/bernoulli.py
python
Bernoulli._mode
(self)
return math_ops.cast(self.probs > 0.5, self.dtype)
Returns `1` if `prob > 0.5` and `0` otherwise.
Returns `1` if `prob > 0.5` and `0` otherwise.
[ "Returns", "1", "if", "prob", ">", "0", ".", "5", "and", "0", "otherwise", "." ]
def _mode(self): """Returns `1` if `prob > 0.5` and `0` otherwise.""" return math_ops.cast(self.probs > 0.5, self.dtype)
[ "def", "_mode", "(", "self", ")", ":", "return", "math_ops", ".", "cast", "(", "self", ".", "probs", ">", "0.5", ",", "self", ".", "dtype", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/distributions/bernoulli.py#L163-L165
alexgkendall/caffe-posenet
62aafbd7c45df91acdba14f5d1406d8295c2bc6f
scripts/cpp_lint.py
python
PrintUsage
(message)
Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message.
Prints a brief usage string and exits, optionally with an error message.
[ "Prints", "a", "brief", "usage", "string", "and", "exits", "optionally", "with", "an", "error", "message", "." ]
def PrintUsage(message): """Prints a brief usage string and exits, optionally with an error message. Args: message: The optional error message. """ sys.stderr.write(_USAGE) if message: sys.exit('\nFATAL ERROR: ' + message) else: sys.exit(1)
[ "def", "PrintUsage", "(", "message", ")", ":", "sys", ".", "stderr", ".", "write", "(", "_USAGE", ")", "if", "message", ":", "sys", ".", "exit", "(", "'\\nFATAL ERROR: '", "+", "message", ")", "else", ":", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/alexgkendall/caffe-posenet/blob/62aafbd7c45df91acdba14f5d1406d8295c2bc6f/scripts/cpp_lint.py#L4757-L4767
zufuliu/notepad2
680bb88661147936c7ae062da1dae4231486d3c1
scintilla/scripts/FileGenerator.py
python
UpdateFileFromLines
(path, lines, lineEndToUse)
Join the lines with the lineEndToUse then update file if the result is different.
Join the lines with the lineEndToUse then update file if the result is different.
[ "Join", "the", "lines", "with", "the", "lineEndToUse", "then", "update", "file", "if", "the", "result", "is", "different", "." ]
def UpdateFileFromLines(path, lines, lineEndToUse): """Join the lines with the lineEndToUse then update file if the result is different. """ contents = lineEndToUse.join(lines) + lineEndToUse UpdateFile(path, contents)
[ "def", "UpdateFileFromLines", "(", "path", ",", "lines", ",", "lineEndToUse", ")", ":", "contents", "=", "lineEndToUse", ".", "join", "(", "lines", ")", "+", "lineEndToUse", "UpdateFile", "(", "path", ",", "contents", ")" ]
https://github.com/zufuliu/notepad2/blob/680bb88661147936c7ae062da1dae4231486d3c1/scintilla/scripts/FileGenerator.py#L199-L203
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/data_structures/sarray.py
python
SArray.__deepcopy__
(self, memo)
return SArray(_proxy=self.__proxy__)
Returns a deep copy of the sarray. As the data in an SArray is immutable, this is identical to __copy__.
Returns a deep copy of the sarray. As the data in an SArray is immutable, this is identical to __copy__.
[ "Returns", "a", "deep", "copy", "of", "the", "sarray", ".", "As", "the", "data", "in", "an", "SArray", "is", "immutable", "this", "is", "identical", "to", "__copy__", "." ]
def __deepcopy__(self, memo): """ Returns a deep copy of the sarray. As the data in an SArray is immutable, this is identical to __copy__. """ return SArray(_proxy=self.__proxy__)
[ "def", "__deepcopy__", "(", "self", ",", "memo", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sarray.py#L4655-L4660
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/timeseries/python/timeseries/model_utils.py
python
_check_predict_features
(features)
Raises errors if features are not suitable for prediction.
Raises errors if features are not suitable for prediction.
[ "Raises", "errors", "if", "features", "are", "not", "suitable", "for", "prediction", "." ]
def _check_predict_features(features): """Raises errors if features are not suitable for prediction.""" if feature_keys.PredictionFeatures.TIMES not in features: raise ValueError("Expected a '{}' feature for prediction.".format( feature_keys.PredictionFeatures.TIMES)) if feature_keys.PredictionFeatures.STATE_TUPLE not in features: raise ValueError("Expected a '{}' feature for prediction.".format( feature_keys.PredictionFeatures.STATE_TUPLE)) times_feature = features[feature_keys.PredictionFeatures.TIMES] if not times_feature.get_shape().is_compatible_with([None, None]): raise ValueError( ("Expected shape (batch dimension, window size) for feature '{}' " "(got shape {})").format(feature_keys.PredictionFeatures.TIMES, times_feature.get_shape())) _check_feature_shapes_compatible_with( features=features, compatible_with_name=feature_keys.PredictionFeatures.TIMES, compatible_with_value=times_feature, ignore=set([ feature_keys.PredictionFeatures.STATE_TUPLE # Model-dependent shapes ]))
[ "def", "_check_predict_features", "(", "features", ")", ":", "if", "feature_keys", ".", "PredictionFeatures", ".", "TIMES", "not", "in", "features", ":", "raise", "ValueError", "(", "\"Expected a '{}' feature for prediction.\"", ".", "format", "(", "feature_keys", "."...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/timeseries/python/timeseries/model_utils.py#L74-L94
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/engine/base_layer_utils.py
python
is_in_keras_graph
()
return call_context().in_keras_graph
Returns if currently executing inside of a Keras graph.
Returns if currently executing inside of a Keras graph.
[ "Returns", "if", "currently", "executing", "inside", "of", "a", "Keras", "graph", "." ]
def is_in_keras_graph(): """Returns if currently executing inside of a Keras graph.""" return call_context().in_keras_graph
[ "def", "is_in_keras_graph", "(", ")", ":", "return", "call_context", "(", ")", ".", "in_keras_graph" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/engine/base_layer_utils.py#L333-L335
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBUnixSignals.SetShouldNotify
(self, *args)
return _lldb.SBUnixSignals_SetShouldNotify(self, *args)
SetShouldNotify(self, int32_t signo, bool value) -> bool
SetShouldNotify(self, int32_t signo, bool value) -> bool
[ "SetShouldNotify", "(", "self", "int32_t", "signo", "bool", "value", ")", "-", ">", "bool" ]
def SetShouldNotify(self, *args): """SetShouldNotify(self, int32_t signo, bool value) -> bool""" return _lldb.SBUnixSignals_SetShouldNotify(self, *args)
[ "def", "SetShouldNotify", "(", "self", ",", "*", "args", ")", ":", "return", "_lldb", ".", "SBUnixSignals_SetShouldNotify", "(", "self", ",", "*", "args", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L12749-L12751
flexflow/FlexFlow
581fad8ba8d10a16a3102ee2b406b0319586df24
python/flexflow/core/flexflow_cffi.py
python
FFModel.sigmoid
(self, input, name=None)
return Tensor(handle, owner_op_type=OpType.SIGMOID)
Sigmoid activation function, :math:`sigmoid(x) = 1 / (1 + exp(-x))`. :param input: the input Tensor. :type input: Tensor :param name: the name of the layer. Default is None. :type name: string :returns: Tensor -- the output tensor.
Sigmoid activation function, :math:`sigmoid(x) = 1 / (1 + exp(-x))`. :param input: the input Tensor. :type input: Tensor :param name: the name of the layer. Default is None. :type name: string
[ "Sigmoid", "activation", "function", ":", "math", ":", "sigmoid", "(", "x", ")", "=", "1", "/", "(", "1", "+", "exp", "(", "-", "x", "))", ".", ":", "param", "input", ":", "the", "input", "Tensor", ".", ":", "type", "input", ":", "Tensor", ":", ...
def sigmoid(self, input, name=None): """Sigmoid activation function, :math:`sigmoid(x) = 1 / (1 + exp(-x))`. :param input: the input Tensor. :type input: Tensor :param name: the name of the layer. Default is None. :type name: string :returns: Tensor -- the output tensor. """ c_name = get_c_name(name) handle = ffc.flexflow_model_add_sigmoid(self.handle, input.handle, c_name) self.add_layer(OpType.SIGMOID, name) return Tensor(handle, owner_op_type=OpType.SIGMOID)
[ "def", "sigmoid", "(", "self", ",", "input", ",", "name", "=", "None", ")", ":", "c_name", "=", "get_c_name", "(", "name", ")", "handle", "=", "ffc", ".", "flexflow_model_add_sigmoid", "(", "self", ".", "handle", ",", "input", ".", "handle", ",", "c_na...
https://github.com/flexflow/FlexFlow/blob/581fad8ba8d10a16a3102ee2b406b0319586df24/python/flexflow/core/flexflow_cffi.py#L1557-L1571
christinaa/LLVM-VideoCore4
7773c3c9e5d22b785d4b96ed0acea37c8aa9c183
utils/llvm-build/llvmbuild/configutil.py
python
configure_file
(input_path, output_path, substitutions)
return True
configure_file(input_path, output_path, substitutions) -> bool Given an input and output path, "configure" the file at the given input path by replacing variables in the file with those given in the substitutions list. Returns true if the output file was written. The substitutions list should be given as a list of tuples (regex string, replacement), where the regex and replacement will be used as in 're.sub' to execute the variable replacement. The output path's parent directory need not exist (it will be created). If the output path does exist and the configured data is not different than it's current contents, the output file will not be modified. This is designed to limit the impact of configured files on build dependencies.
configure_file(input_path, output_path, substitutions) -> bool
[ "configure_file", "(", "input_path", "output_path", "substitutions", ")", "-", ">", "bool" ]
def configure_file(input_path, output_path, substitutions): """configure_file(input_path, output_path, substitutions) -> bool Given an input and output path, "configure" the file at the given input path by replacing variables in the file with those given in the substitutions list. Returns true if the output file was written. The substitutions list should be given as a list of tuples (regex string, replacement), where the regex and replacement will be used as in 're.sub' to execute the variable replacement. The output path's parent directory need not exist (it will be created). If the output path does exist and the configured data is not different than it's current contents, the output file will not be modified. This is designed to limit the impact of configured files on build dependencies. """ # Read in the input data. f = open(input_path, "rb") try: data = f.read() finally: f.close() # Perform the substitutions. for regex_string,replacement in substitutions: regex = re.compile(regex_string) data = regex.sub(replacement, data) # Ensure the output parent directory exists. output_parent_path = os.path.dirname(os.path.abspath(output_path)) if not os.path.exists(output_parent_path): os.makedirs(output_parent_path) # If the output path exists, load it and compare to the configured contents. if os.path.exists(output_path): current_data = None try: f = open(output_path, "rb") try: current_data = f.read() except: current_data = None f.close() except: current_data = None if current_data is not None and current_data == data: return False # Write the output contents. f = open(output_path, "wb") try: f.write(data) finally: f.close() return True
[ "def", "configure_file", "(", "input_path", ",", "output_path", ",", "substitutions", ")", ":", "# Read in the input data.", "f", "=", "open", "(", "input_path", ",", "\"rb\"", ")", "try", ":", "data", "=", "f", ".", "read", "(", ")", "finally", ":", "f", ...
https://github.com/christinaa/LLVM-VideoCore4/blob/7773c3c9e5d22b785d4b96ed0acea37c8aa9c183/utils/llvm-build/llvmbuild/configutil.py#L8-L66
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/ssl.py
python
SSLObject.shared_ciphers
(self)
return self._sslobj.shared_ciphers()
Return a list of ciphers shared by the client during the handshake or None if this is not a valid server connection.
Return a list of ciphers shared by the client during the handshake or None if this is not a valid server connection.
[ "Return", "a", "list", "of", "ciphers", "shared", "by", "the", "client", "during", "the", "handshake", "or", "None", "if", "this", "is", "not", "a", "valid", "server", "connection", "." ]
def shared_ciphers(self): """Return a list of ciphers shared by the client during the handshake or None if this is not a valid server connection. """ return self._sslobj.shared_ciphers()
[ "def", "shared_ciphers", "(", "self", ")", ":", "return", "self", ".", "_sslobj", ".", "shared_ciphers", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/ssl.py#L945-L949
mongodb/mongo
d8ff665343ad29cf286ee2cf4a1960d29371937b
buildscripts/linter/runner.py
python
LintRunner.run
(self, cmd)
return True
Check the specified cmd succeeds.
Check the specified cmd succeeds.
[ "Check", "the", "specified", "cmd", "succeeds", "." ]
def run(self, cmd): # type: (List[str]) -> bool """Check the specified cmd succeeds.""" logging.debug(str(cmd)) try: subprocess.check_output(cmd).decode('utf-8') except subprocess.CalledProcessError as cpe: self._safe_print("CMD [%s] failed:\n%s" % (' '.join(cmd), cpe.output)) return False return True
[ "def", "run", "(", "self", ",", "cmd", ")", ":", "# type: (List[str]) -> bool", "logging", ".", "debug", "(", "str", "(", "cmd", ")", ")", "try", ":", "subprocess", ".", "check_output", "(", "cmd", ")", ".", "decode", "(", "'utf-8'", ")", "except", "su...
https://github.com/mongodb/mongo/blob/d8ff665343ad29cf286ee2cf4a1960d29371937b/buildscripts/linter/runner.py#L227-L239
logcabin/logcabin
ee6c55ae9744b82b451becd9707d26c7c1b6bbfb
scripts/cpplint.py
python
RemoveMultiLineComments
(filename, lines, error)
Removes multiline (c-style) comments from lines.
Removes multiline (c-style) comments from lines.
[ "Removes", "multiline", "(", "c", "-", "style", ")", "comments", "from", "lines", "." ]
def RemoveMultiLineComments(filename, lines, error): """Removes multiline (c-style) comments from lines.""" count = 0 lineix = 0 while lineix < len(lines): lineix_begin = FindNextMultiLineCommentStart(lines, lineix) if lineix_begin >= len(lines): return lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) if lineix_end >= len(lines): error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, 'Could not find end of multi-line comment') return #if count == 1: # if r'\file' not in lines[lineix_begin + 1]: # error(filename, lineix_begin + 1, 'readability/multiline_comment', # 5, r'Second comment in file should be Doxygen \file comment.') RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) lineix = lineix_end + 1 count += 1
[ "def", "RemoveMultiLineComments", "(", "filename", ",", "lines", ",", "error", ")", ":", "count", "=", "0", "lineix", "=", "0", "while", "lineix", "<", "len", "(", "lines", ")", ":", "lineix_begin", "=", "FindNextMultiLineCommentStart", "(", "lines", ",", ...
https://github.com/logcabin/logcabin/blob/ee6c55ae9744b82b451becd9707d26c7c1b6bbfb/scripts/cpplint.py#L838-L857
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/fixer_util.py
python
_is_import_binding
(node, name, package=None)
return None
Will reuturn node if node will import name, or node will import * from package. None is returned otherwise. See test cases for examples.
Will reuturn node if node will import name, or node will import * from package. None is returned otherwise. See test cases for examples.
[ "Will", "reuturn", "node", "if", "node", "will", "import", "name", "or", "node", "will", "import", "*", "from", "package", ".", "None", "is", "returned", "otherwise", ".", "See", "test", "cases", "for", "examples", "." ]
def _is_import_binding(node, name, package=None): """ Will reuturn node if node will import name, or node will import * from package. None is returned otherwise. See test cases for examples. """ if node.type == syms.import_name and not package: imp = node.children[1] if imp.type == syms.dotted_as_names: for child in imp.children: if child.type == syms.dotted_as_name: if child.children[2].value == name: return node elif child.type == token.NAME and child.value == name: return node elif imp.type == syms.dotted_as_name: last = imp.children[-1] if last.type == token.NAME and last.value == name: return node elif imp.type == token.NAME and imp.value == name: return node elif node.type == syms.import_from: # unicode(...) is used to make life easier here, because # from a.b import parses to ['import', ['a', '.', 'b'], ...] if package and unicode(node.children[1]).strip() != package: return None n = node.children[3] if package and _find(u"as", n): # See test_from_import_as for explanation return None elif n.type == syms.import_as_names and _find(name, n): return node elif n.type == syms.import_as_name: child = n.children[2] if child.type == token.NAME and child.value == name: return node elif n.type == token.NAME and n.value == name: return node elif package and n.type == token.STAR: return node return None
[ "def", "_is_import_binding", "(", "node", ",", "name", ",", "package", "=", "None", ")", ":", "if", "node", ".", "type", "==", "syms", ".", "import_name", "and", "not", "package", ":", "imp", "=", "node", ".", "children", "[", "1", "]", "if", "imp", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/lib2to3/fixer_util.py#L393-L432
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/algorithms.py
python
diff
(arr, n, axis=0)
return out_arr
difference of n between self, analogous to s-s.shift(n) Parameters ---------- arr : ndarray n : int number of periods axis : int axis to shift on Returns ------- shifted
difference of n between self, analogous to s-s.shift(n)
[ "difference", "of", "n", "between", "self", "analogous", "to", "s", "-", "s", ".", "shift", "(", "n", ")" ]
def diff(arr, n, axis=0): """ difference of n between self, analogous to s-s.shift(n) Parameters ---------- arr : ndarray n : int number of periods axis : int axis to shift on Returns ------- shifted """ n = int(n) na = np.nan dtype = arr.dtype is_timedelta = False if needs_i8_conversion(arr): dtype = np.float64 arr = arr.view('i8') na = iNaT is_timedelta = True elif is_bool_dtype(dtype): dtype = np.object_ elif is_integer_dtype(dtype): dtype = np.float64 dtype = np.dtype(dtype) out_arr = np.empty(arr.shape, dtype=dtype) na_indexer = [slice(None)] * arr.ndim na_indexer[axis] = slice(None, n) if n >= 0 else slice(n, None) out_arr[tuple(na_indexer)] = na if arr.ndim == 2 and arr.dtype.name in _diff_special: f = _diff_special[arr.dtype.name] f(arr, out_arr, n, axis) else: res_indexer = [slice(None)] * arr.ndim res_indexer[axis] = slice(n, None) if n >= 0 else slice(None, n) res_indexer = tuple(res_indexer) lag_indexer = [slice(None)] * arr.ndim lag_indexer[axis] = slice(None, -n) if n > 0 else slice(-n, None) lag_indexer = tuple(lag_indexer) # need to make sure that we account for na for datelike/timedelta # we don't actually want to subtract these i8 numbers if is_timedelta: res = arr[res_indexer] lag = arr[lag_indexer] mask = (arr[res_indexer] == na) | (arr[lag_indexer] == na) if mask.any(): res = res.copy() res[mask] = 0 lag = lag.copy() lag[mask] = 0 result = res - lag result[mask] = na out_arr[res_indexer] = result else: out_arr[res_indexer] = arr[res_indexer] - arr[lag_indexer] if is_timedelta: from pandas import TimedeltaIndex out_arr = TimedeltaIndex(out_arr.ravel().astype('int64')).asi8.reshape( out_arr.shape).astype('timedelta64[ns]') return out_arr
[ "def", "diff", "(", "arr", ",", "n", ",", "axis", "=", "0", ")", ":", "n", "=", "int", "(", "n", ")", "na", "=", "np", ".", "nan", "dtype", "=", "arr", ".", "dtype", "is_timedelta", "=", "False", "if", "needs_i8_conversion", "(", "arr", ")", ":...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/algorithms.py#L1747-L1826
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/directnotify/Logger.py
python
Logger.__getTimeStamp
(self)
return "%02d:%02d:%02d:%02d: " % (days, hours, minutes, seconds)
Return the offset between current time and log file startTime
Return the offset between current time and log file startTime
[ "Return", "the", "offset", "between", "current", "time", "and", "log", "file", "startTime" ]
def __getTimeStamp(self): """ Return the offset between current time and log file startTime """ t = time.time() dt = t - self.__startTime days, dt = divmod(dt, 86400) hours, dt = divmod(dt, 3600) minutes, dt = divmod(dt, 60) seconds = int(math.ceil(dt)) return "%02d:%02d:%02d:%02d: " % (days, hours, minutes, seconds)
[ "def", "__getTimeStamp", "(", "self", ")", ":", "t", "=", "time", ".", "time", "(", ")", "dt", "=", "t", "-", "self", ".", "__startTime", "days", ",", "dt", "=", "divmod", "(", "dt", ",", "86400", ")", "hours", ",", "dt", "=", "divmod", "(", "d...
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/directnotify/Logger.py#L66-L76
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/isis_instrument.py
python
ISISInstrument.on_load_sample
(self, ws_name, beamcentre, isSample)
return centre_shift
It will be called just after loading the workspace for sample and can It configures the instrument for the specific run of the workspace for handle historical changes in the instrument. It centralizes the detector bank to the beamcentre (tuple of two values)
It will be called just after loading the workspace for sample and can
[ "It", "will", "be", "called", "just", "after", "loading", "the", "workspace", "for", "sample", "and", "can" ]
def on_load_sample(self, ws_name, beamcentre, isSample): """It will be called just after loading the workspace for sample and can It configures the instrument for the specific run of the workspace for handle historical changes in the instrument. It centralizes the detector bank to the beamcentre (tuple of two values) """ ws_ref = mtd[str(ws_name)] try: run_num = LARMOR.get_run_number_from_workspace_reference(ws_ref) except: run_num = int(re.findall(r'\d+', str(ws_name))[0]) if isSample: self.set_up_for_run(run_num) if self._newCalibrationWS: # We are about to transfer the Instrument Parameter File from the # calibration to the original workspace. We want to add new parameters # which the calibration file has not yet picked up. # IMPORTANT NOTE: This takes the parameter settings from the original workspace # if they are old too, then we don't pick up newly added parameters self._add_parmeters_absent_in_calibration(ws_name, self._newCalibrationWS) self.changeCalibration(ws_name) # centralize the bank to the centre dummy_centre, centre_shift = self.move_components(ws_name, beamcentre[0], beamcentre[1]) return centre_shift
[ "def", "on_load_sample", "(", "self", ",", "ws_name", ",", "beamcentre", ",", "isSample", ")", ":", "ws_ref", "=", "mtd", "[", "str", "(", "ws_name", ")", "]", "try", ":", "run_num", "=", "LARMOR", ".", "get_run_number_from_workspace_reference", "(", "ws_ref...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/isis_instrument.py#L767-L794
crosslife/OpenBird
9e0198a1a2295f03fa1e8676e216e22c9c7d380b
cocos2d/tools/bindings-generator/clang/cindex.py
python
CompilationDatabase.getCompileCommands
(self, filename)
return conf.lib.clang_CompilationDatabase_getCompileCommands(self, filename)
Get an iterable object providing all the CompileCommands available to build filename. Returns None if filename is not found in the database.
Get an iterable object providing all the CompileCommands available to build filename. Returns None if filename is not found in the database.
[ "Get", "an", "iterable", "object", "providing", "all", "the", "CompileCommands", "available", "to", "build", "filename", ".", "Returns", "None", "if", "filename", "is", "not", "found", "in", "the", "database", "." ]
def getCompileCommands(self, filename): """ Get an iterable object providing all the CompileCommands available to build filename. Returns None if filename is not found in the database. """ return conf.lib.clang_CompilationDatabase_getCompileCommands(self, filename)
[ "def", "getCompileCommands", "(", "self", ",", "filename", ")", ":", "return", "conf", ".", "lib", ".", "clang_CompilationDatabase_getCompileCommands", "(", "self", ",", "filename", ")" ]
https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/clang/cindex.py#L2641-L2647
jts/nanopolish
181549b682ffe99c1bbf1a410ee2806614a08445
scripts/reestimate_polya_emissions.py
python
make_segmentation_dict
(segmentations_tsv_path)
return segments
Load a segmentations TSV file. Rows of `segmentations_tsv_path` look like this: tag read_id: pos: L_0 A_0: P_0: P_1: RR: P(A)L: AL: polya-segmentation fc06... 161684804 47.0 1851.0 8354.0 11424.0 73.76 75.18 35.23 Note that this function only takes the first available segmentation for each read, i.e. if a read id appears more than once in the TSV, only the first segmentation is kept, and later occurrences of the read id in the TSV are ignored.
Load a segmentations TSV file. Rows of `segmentations_tsv_path` look like this:
[ "Load", "a", "segmentations", "TSV", "file", ".", "Rows", "of", "segmentations_tsv_path", "look", "like", "this", ":" ]
def make_segmentation_dict(segmentations_tsv_path): """ Load a segmentations TSV file. Rows of `segmentations_tsv_path` look like this: tag read_id: pos: L_0 A_0: P_0: P_1: RR: P(A)L: AL: polya-segmentation fc06... 161684804 47.0 1851.0 8354.0 11424.0 73.76 75.18 35.23 Note that this function only takes the first available segmentation for each read, i.e. if a read id appears more than once in the TSV, only the first segmentation is kept, and later occurrences of the read id in the TSV are ignored. """ segments = {} # loop thru TSV and update the list of segmentations: with open(segmentations_tsv_path, 'r') as f: headers = ['tag', 'read_id', 'pos', 'L_start', 'A_start', 'P_start', 'P_end', 'rate', 'plen', 'alen'] rdr = csv.DictReader(f, delimiter='\t', quoting=csv.QUOTE_NONE, fieldnames=headers) for row in rdr: if row['read_id'] not in list(segments.keys()): segments[row['read_id']] = { 'L_start': int(float(row['L_start'])), 'A_start': int(float(row['A_start'])), 'P_start': int(float(row['P_start'])), 'P_end': int(float(row['P_end'])) } return segments
[ "def", "make_segmentation_dict", "(", "segmentations_tsv_path", ")", ":", "segments", "=", "{", "}", "# loop thru TSV and update the list of segmentations:", "with", "open", "(", "segmentations_tsv_path", ",", "'r'", ")", "as", "f", ":", "headers", "=", "[", "'tag'", ...
https://github.com/jts/nanopolish/blob/181549b682ffe99c1bbf1a410ee2806614a08445/scripts/reestimate_polya_emissions.py#L104-L126
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/vision/ops.py
python
roi_pool
(x, boxes, boxes_num, output_size, spatial_scale=1.0, name=None)
This operator implements the roi_pooling layer. Region of interest pooling (also known as RoI pooling) is to perform max pooling on inputs of nonuniform sizes to obtain fixed-size feature maps (e.g. 7*7). The operator has three steps: 1. Dividing each region proposal into equal-sized sections with output_size(h, w) 2. Finding the largest value in each section 3. Copying these max values to the output buffer For more information, please refer to https://stackoverflow.com/questions/43430056/what-is-roi-layer-in-fast-rcnn. Args: x (Tensor): input feature, 4D-Tensor with the shape of [N,C,H,W], where N is the batch size, C is the input channel, H is Height, W is weight. The data type is float32 or float64. boxes (Tensor): boxes (Regions of Interest) to pool over. 2D-Tensor with the shape of [num_boxes,4]. Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates, and (x2, y2) is the bottom right coordinates. boxes_num (Tensor): the number of RoIs in each image, data type is int32. Default: None output_size (int or tuple[int, int]): the pooled output size(h, w), data type is int32. If int, h and w are both equal to output_size. spatial_scale (float, optional): multiplicative spatial scale factor to translate ROI coords from their input scale to the scale used when pooling. Default: 1.0 name(str, optional): for detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: pool_out (Tensor): the pooled feature, 4D-Tensor with the shape of [num_boxes, C, output_size[0], output_size[1]]. Examples: .. code-block:: python import paddle from paddle.vision.ops import roi_pool data = paddle.rand([1, 256, 32, 32]) boxes = paddle.rand([3, 4]) boxes[:, 2] += boxes[:, 0] + 3 boxes[:, 3] += boxes[:, 1] + 4 boxes_num = paddle.to_tensor([3]).astype('int32') pool_out = roi_pool(data, boxes, boxes_num=boxes_num, output_size=3) assert pool_out.shape == [3, 256, 3, 3], ''
This operator implements the roi_pooling layer. Region of interest pooling (also known as RoI pooling) is to perform max pooling on inputs of nonuniform sizes to obtain fixed-size feature maps (e.g. 7*7). The operator has three steps: 1. Dividing each region proposal into equal-sized sections with output_size(h, w) 2. Finding the largest value in each section 3. Copying these max values to the output buffer For more information, please refer to https://stackoverflow.com/questions/43430056/what-is-roi-layer-in-fast-rcnn.
[ "This", "operator", "implements", "the", "roi_pooling", "layer", ".", "Region", "of", "interest", "pooling", "(", "also", "known", "as", "RoI", "pooling", ")", "is", "to", "perform", "max", "pooling", "on", "inputs", "of", "nonuniform", "sizes", "to", "obtai...
def roi_pool(x, boxes, boxes_num, output_size, spatial_scale=1.0, name=None): """ This operator implements the roi_pooling layer. Region of interest pooling (also known as RoI pooling) is to perform max pooling on inputs of nonuniform sizes to obtain fixed-size feature maps (e.g. 7*7). The operator has three steps: 1. Dividing each region proposal into equal-sized sections with output_size(h, w) 2. Finding the largest value in each section 3. Copying these max values to the output buffer For more information, please refer to https://stackoverflow.com/questions/43430056/what-is-roi-layer-in-fast-rcnn. Args: x (Tensor): input feature, 4D-Tensor with the shape of [N,C,H,W], where N is the batch size, C is the input channel, H is Height, W is weight. The data type is float32 or float64. boxes (Tensor): boxes (Regions of Interest) to pool over. 2D-Tensor with the shape of [num_boxes,4]. Given as [[x1, y1, x2, y2], ...], (x1, y1) is the top left coordinates, and (x2, y2) is the bottom right coordinates. boxes_num (Tensor): the number of RoIs in each image, data type is int32. Default: None output_size (int or tuple[int, int]): the pooled output size(h, w), data type is int32. If int, h and w are both equal to output_size. spatial_scale (float, optional): multiplicative spatial scale factor to translate ROI coords from their input scale to the scale used when pooling. Default: 1.0 name(str, optional): for detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: pool_out (Tensor): the pooled feature, 4D-Tensor with the shape of [num_boxes, C, output_size[0], output_size[1]]. Examples: .. code-block:: python import paddle from paddle.vision.ops import roi_pool data = paddle.rand([1, 256, 32, 32]) boxes = paddle.rand([3, 4]) boxes[:, 2] += boxes[:, 0] + 3 boxes[:, 3] += boxes[:, 1] + 4 boxes_num = paddle.to_tensor([3]).astype('int32') pool_out = roi_pool(data, boxes, boxes_num=boxes_num, output_size=3) assert pool_out.shape == [3, 256, 3, 3], '' """ check_type(output_size, 'output_size', (int, tuple), 'roi_pool') if isinstance(output_size, int): output_size = (output_size, output_size) pooled_height, pooled_width = output_size if in_dygraph_mode(): assert boxes_num is not None, "boxes_num should not be None in dygraph mode." pool_out, argmaxes = _C_ops.roi_pool( x, boxes, boxes_num, "pooled_height", pooled_height, "pooled_width", pooled_width, "spatial_scale", spatial_scale) return pool_out else: check_variable_and_dtype(x, 'x', ['float32'], 'roi_pool') check_variable_and_dtype(boxes, 'boxes', ['float32'], 'roi_pool') helper = LayerHelper('roi_pool', **locals()) dtype = helper.input_dtype() pool_out = helper.create_variable_for_type_inference(dtype) argmaxes = helper.create_variable_for_type_inference(dtype='int32') inputs = { "X": x, "ROIs": boxes, } if boxes_num is not None: inputs['RoisNum'] = boxes_num helper.append_op( type="roi_pool", inputs=inputs, outputs={"Out": pool_out, "Argmax": argmaxes}, attrs={ "pooled_height": pooled_height, "pooled_width": pooled_width, "spatial_scale": spatial_scale }) return pool_out
[ "def", "roi_pool", "(", "x", ",", "boxes", ",", "boxes_num", ",", "output_size", ",", "spatial_scale", "=", "1.0", ",", "name", "=", "None", ")", ":", "check_type", "(", "output_size", ",", "'output_size'", ",", "(", "int", ",", "tuple", ")", ",", "'ro...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/vision/ops.py#L1022-L1096
v8mips/v8mips
f0c9cc0bbfd461c7f516799d9a58e9a7395f737e
PRESUBMIT.py
python
_CheckChangeLogFlag
(input_api, output_api)
return results
Checks usage of LOG= flag in the commit message.
Checks usage of LOG= flag in the commit message.
[ "Checks", "usage", "of", "LOG", "=", "flag", "in", "the", "commit", "message", "." ]
def _CheckChangeLogFlag(input_api, output_api): """Checks usage of LOG= flag in the commit message.""" results = [] if input_api.change.BUG and not 'LOG' in input_api.change.tags: results.append(output_api.PresubmitError( 'An issue reference (BUG=) requires a change log flag (LOG=). ' 'Use LOG=Y for including this commit message in the change log. ' 'Use LOG=N or leave blank otherwise.')) return results
[ "def", "_CheckChangeLogFlag", "(", "input_api", ",", "output_api", ")", ":", "results", "=", "[", "]", "if", "input_api", ".", "change", ".", "BUG", "and", "not", "'LOG'", "in", "input_api", ".", "change", ".", "tags", ":", "results", ".", "append", "(",...
https://github.com/v8mips/v8mips/blob/f0c9cc0bbfd461c7f516799d9a58e9a7395f737e/PRESUBMIT.py#L210-L218
sc0ty/subsync
be5390d00ff475b6543eb0140c7e65b34317d95b
subsync/synchro/controller.py
python
SyncController.validateTask
(self, task, *, interactive=False)
Check if task is properly defined. Parameters ---------- task: SyncTask Task to validate. interactive: bool, optional For interactive synchronization `out` will not be vaildated. Raises ------ Error Invalid task. KeyError or Exception Invalid `task`.out.path pattern.
Check if task is properly defined.
[ "Check", "if", "task", "is", "properly", "defined", "." ]
def validateTask(self, task, *, interactive=False): """Check if task is properly defined. Parameters ---------- task: SyncTask Task to validate. interactive: bool, optional For interactive synchronization `out` will not be vaildated. Raises ------ Error Invalid task. KeyError or Exception Invalid `task`.out.path pattern. """ sub, ref, out = task.sub, task.ref, task.out if sub is None or not sub.path or sub.no is None: raise Error('subtitles not set', task=task) if ref is None or not ref.path or ref.no is None: raise Error('reference file not set', task=task) if not interactive and (out is None or not out.path): raise Error('output path not set', task=task) if not interactive: out.validateOutputPattern()
[ "def", "validateTask", "(", "self", ",", "task", ",", "*", ",", "interactive", "=", "False", ")", ":", "sub", ",", "ref", ",", "out", "=", "task", ".", "sub", ",", "task", ".", "ref", ",", "task", ".", "out", "if", "sub", "is", "None", "or", "n...
https://github.com/sc0ty/subsync/blob/be5390d00ff475b6543eb0140c7e65b34317d95b/subsync/synchro/controller.py#L286-L311
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/Tkinter.py
python
Spinbox.scan
(self, *args)
return self._getints( self.tk.call((self._w, 'scan') + args)) or ()
Internal function.
Internal function.
[ "Internal", "function", "." ]
def scan(self, *args): """Internal function.""" return self._getints( self.tk.call((self._w, 'scan') + args)) or ()
[ "def", "scan", "(", "self", ",", "*", "args", ")", ":", "return", "self", ".", "_getints", "(", "self", ".", "tk", ".", "call", "(", "(", "self", ".", "_w", ",", "'scan'", ")", "+", "args", ")", ")", "or", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/Tkinter.py#L3544-L3547
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/v8/third_party/jinja2/nodes.py
python
Node.set_environment
(self, environment)
return self
Set the environment for all nodes.
Set the environment for all nodes.
[ "Set", "the", "environment", "for", "all", "nodes", "." ]
def set_environment(self, environment): """Set the environment for all nodes.""" todo = deque([self]) while todo: node = todo.popleft() node.environment = environment todo.extend(node.iter_child_nodes()) return self
[ "def", "set_environment", "(", "self", ",", "environment", ")", ":", "todo", "=", "deque", "(", "[", "self", "]", ")", "while", "todo", ":", "node", "=", "todo", ".", "popleft", "(", ")", "node", ".", "environment", "=", "environment", "todo", ".", "...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/v8/third_party/jinja2/nodes.py#L219-L226
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/logging/__init__.py
python
FileHandler.close
(self)
Closes the stream.
Closes the stream.
[ "Closes", "the", "stream", "." ]
def close(self): """ Closes the stream. """ self.acquire() try: try: if self.stream: try: self.flush() finally: stream = self.stream self.stream = None if hasattr(stream, "close"): stream.close() finally: # Issue #19523: call unconditionally to # prevent a handler leak when delay is set StreamHandler.close(self) finally: self.release()
[ "def", "close", "(", "self", ")", ":", "self", ".", "acquire", "(", ")", "try", ":", "try", ":", "if", "self", ".", "stream", ":", "try", ":", "self", ".", "flush", "(", ")", "finally", ":", "stream", "=", "self", ".", "stream", "self", ".", "s...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/logging/__init__.py#L922-L942
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/EditorWindow.py
python
HelpDialog.display
(self, parent, near=None)
Display the help dialog. parent - parent widget for the help window near - a Toplevel widget (e.g. EditorWindow or PyShell) to use as a reference for placing the help window
Display the help dialog.
[ "Display", "the", "help", "dialog", "." ]
def display(self, parent, near=None): """ Display the help dialog. parent - parent widget for the help window near - a Toplevel widget (e.g. EditorWindow or PyShell) to use as a reference for placing the help window """ if self.dlg is None: self.show_dialog(parent) if near: self.nearwindow(near)
[ "def", "display", "(", "self", ",", "parent", ",", "near", "=", "None", ")", ":", "if", "self", ".", "dlg", "is", "None", ":", "self", ".", "show_dialog", "(", "parent", ")", "if", "near", ":", "self", ".", "nearwindow", "(", "near", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/EditorWindow.py#L75-L86
niwinz/phantompy
ae25ddb6791e13cb7c35126971c410030ee5dfda
phantompy/webelements.py
python
WebElement.append_after
(self, element)
Same as :py:meth:`~.append` but appends outside the current dom element.
Same as :py:meth:`~.append` but appends outside the current dom element.
[ "Same", "as", ":", "py", ":", "meth", ":", "~", ".", "append", "but", "appends", "outside", "the", "current", "dom", "element", "." ]
def append_after(self, element): """ Same as :py:meth:`~.append` but appends outside the current dom element. """ if isinstance(element, util.string_type): lib.ph_webelement_append_html_after(self.ptr, util.force_bytes(element)) elif isinstance(element, WebElement): lib.ph_webelement_append_element_after(self.ptr, element.ptr) else: raise RuntimeError("Invalid argument")
[ "def", "append_after", "(", "self", ",", "element", ")", ":", "if", "isinstance", "(", "element", ",", "util", ".", "string_type", ")", ":", "lib", ".", "ph_webelement_append_html_after", "(", "self", ".", "ptr", ",", "util", ".", "force_bytes", "(", "elem...
https://github.com/niwinz/phantompy/blob/ae25ddb6791e13cb7c35126971c410030ee5dfda/phantompy/webelements.py#L202-L213
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
third_party/gpus/find_cuda_config.py
python
_get_header_version
(path, name)
return ""
Returns preprocessor defines in C header file.
Returns preprocessor defines in C header file.
[ "Returns", "preprocessor", "defines", "in", "C", "header", "file", "." ]
def _get_header_version(path, name): """Returns preprocessor defines in C header file.""" for line in io.open(path, "r", encoding="utf-8").readlines(): match = re.match("#define %s +(\d+)" % name, line) if match: return match.group(1) return ""
[ "def", "_get_header_version", "(", "path", ",", "name", ")", ":", "for", "line", "in", "io", ".", "open", "(", "path", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", ".", "readlines", "(", ")", ":", "match", "=", "re", ".", "match", "(", "\"...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/third_party/gpus/find_cuda_config.py#L121-L127
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/kernelized_utils.py
python
_to_matrix
(u)
return u
If input tensor is a vector (i.e., has rank 1), converts it to matrix.
If input tensor is a vector (i.e., has rank 1), converts it to matrix.
[ "If", "input", "tensor", "is", "a", "vector", "(", "i", ".", "e", ".", "has", "rank", "1", ")", "converts", "it", "to", "matrix", "." ]
def _to_matrix(u): """If input tensor is a vector (i.e., has rank 1), converts it to matrix.""" u_rank = len(u.shape) if u_rank not in [1, 2]: raise ValueError('The input tensor should have rank 1 or 2. Given rank: {}' .format(u_rank)) if u_rank == 1: return array_ops.expand_dims(u, 0) return u
[ "def", "_to_matrix", "(", "u", ")", ":", "u_rank", "=", "len", "(", "u", ".", "shape", ")", "if", "u_rank", "not", "in", "[", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "'The input tensor should have rank 1 or 2. Given rank: {}'", ".", "format", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/utils/kernelized_utils.py#L25-L33
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/extras/codelite.py
python
codelite_generator.execute
(self)
Entry point
Entry point
[ "Entry", "point" ]
def execute(self): """ Entry point """ self.restore() if not self.all_envs: self.load_envs() self.recurse([self.run_dir]) # user initialization self.init() # two phases for creating the solution self.collect_projects() # add project objects into "self.all_projects" self.write_files()
[ "def", "execute", "(", "self", ")", ":", "self", ".", "restore", "(", ")", "if", "not", "self", ".", "all_envs", ":", "self", ".", "load_envs", "(", ")", "self", ".", "recurse", "(", "[", "self", ".", "run_dir", "]", ")", "# user initialization", "se...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/extras/codelite.py#L710-L724
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py
python
TarInfo.__init__
(self, name="")
Construct a TarInfo object. name is the optional name of the member.
Construct a TarInfo object. name is the optional name of the member.
[ "Construct", "a", "TarInfo", "object", ".", "name", "is", "the", "optional", "name", "of", "the", "member", "." ]
def __init__(self, name=""): """Construct a TarInfo object. name is the optional name of the member. """ self.name = name # member name self.mode = 0o644 # file permissions self.uid = 0 # user id self.gid = 0 # group id self.size = 0 # file size self.mtime = 0 # modification time self.chksum = 0 # header checksum self.type = REGTYPE # member type self.linkname = "" # link name self.uname = "" # user name self.gname = "" # group name self.devmajor = 0 # device major number self.devminor = 0 # device minor number self.offset = 0 # the tar header starts here self.offset_data = 0 # the file's data starts here self.sparse = None # sparse member information self.pax_headers = {}
[ "def", "__init__", "(", "self", ",", "name", "=", "\"\"", ")", ":", "self", ".", "name", "=", "name", "# member name", "self", ".", "mode", "=", "0o644", "# file permissions", "self", ".", "uid", "=", "0", "# user id", "self", ".", "gid", "=", "0", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py#L739-L761
bundy-dns/bundy
3d41934996b82b0cd2fe22dd74d2abc1daba835d
src/lib/python/bundy/sysinfo/sysinfo.py
python
SysInfo.get_platform_machine
(self)
return self._platform_machine
Returns the platform machine architecture.
Returns the platform machine architecture.
[ "Returns", "the", "platform", "machine", "architecture", "." ]
def get_platform_machine(self): """Returns the platform machine architecture.""" return self._platform_machine
[ "def", "get_platform_machine", "(", "self", ")", ":", "return", "self", ".", "_platform_machine" ]
https://github.com/bundy-dns/bundy/blob/3d41934996b82b0cd2fe22dd74d2abc1daba835d/src/lib/python/bundy/sysinfo/sysinfo.py#L76-L78
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/xml/sax/_exceptions.py
python
SAXParseException.__str__
(self)
return "%s:%s:%s: %s" % (sysid, linenum, colnum, self._msg)
Create a string representation of the exception.
Create a string representation of the exception.
[ "Create", "a", "string", "representation", "of", "the", "exception", "." ]
def __str__(self): "Create a string representation of the exception." sysid = self.getSystemId() if sysid is None: sysid = "<unknown>" linenum = self.getLineNumber() if linenum is None: linenum = "?" colnum = self.getColumnNumber() if colnum is None: colnum = "?" return "%s:%s:%s: %s" % (sysid, linenum, colnum, self._msg)
[ "def", "__str__", "(", "self", ")", ":", "sysid", "=", "self", ".", "getSystemId", "(", ")", "if", "sysid", "is", "None", ":", "sysid", "=", "\"<unknown>\"", "linenum", "=", "self", ".", "getLineNumber", "(", ")", "if", "linenum", "is", "None", ":", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/xml/sax/_exceptions.py#L89-L100
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py
python
TarFile.getmember
(self, name)
return tarinfo
Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurrence is assumed to be the most up-to-date version.
Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurrence is assumed to be the most up-to-date version.
[ "Return", "a", "TarInfo", "object", "for", "member", "name", ".", "If", "name", "can", "not", "be", "found", "in", "the", "archive", "KeyError", "is", "raised", ".", "If", "a", "member", "occurs", "more", "than", "once", "in", "the", "archive", "its", ...
def getmember(self, name): """Return a TarInfo object for member `name'. If `name' can not be found in the archive, KeyError is raised. If a member occurs more than once in the archive, its last occurrence is assumed to be the most up-to-date version. """ tarinfo = self._getmember(name) if tarinfo is None: raise KeyError("filename %r not found" % name) return tarinfo
[ "def", "getmember", "(", "self", ",", "name", ")", ":", "tarinfo", "=", "self", ".", "_getmember", "(", "name", ")", "if", "tarinfo", "is", "None", ":", "raise", "KeyError", "(", "\"filename %r not found\"", "%", "name", ")", "return", "tarinfo" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tarfile.py#L1746-L1755
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/calendar.py
python
Calendar.monthdatescalendar
(self, year, month)
return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values.
Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values.
[ "Return", "a", "matrix", "(", "list", "of", "lists", ")", "representing", "a", "month", "s", "calendar", ".", "Each", "row", "represents", "a", "week", ";", "week", "entries", "are", "datetime", ".", "date", "values", "." ]
def monthdatescalendar(self, year, month): """ Return a matrix (list of lists) representing a month's calendar. Each row represents a week; week entries are datetime.date values. """ dates = list(self.itermonthdates(year, month)) return [ dates[i:i+7] for i in range(0, len(dates), 7) ]
[ "def", "monthdatescalendar", "(", "self", ",", "year", ",", "month", ")", ":", "dates", "=", "list", "(", "self", ".", "itermonthdates", "(", "year", ",", "month", ")", ")", "return", "[", "dates", "[", "i", ":", "i", "+", "7", "]", "for", "i", "...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/calendar.py#L194-L200
Salensoft/thu-cst-cracker
f7f6b4de460aaac6da3d776ab28d9175e8b32ae2
大三上/软件工程/hw/2015/Homework/作业2 - 代码风格/01_code_style/my_posixpath.py
python
normcase
(s)
return s
Normalize case of pathname. Has no effect under Posix
Normalize case of pathname. Has no effect under Posix
[ "Normalize", "case", "of", "pathname", ".", "Has", "no", "effect", "under", "Posix" ]
def normcase(s): """Normalize case of pathname. Has no effect under Posix""" return s
[ "def", "normcase", "(", "s", ")", ":", "return", "s" ]
https://github.com/Salensoft/thu-cst-cracker/blob/f7f6b4de460aaac6da3d776ab28d9175e8b32ae2/大三上/软件工程/hw/2015/Homework/作业2 - 代码风格/01_code_style/my_posixpath.py#L55-L57
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/i-pi/ipi/inputs/outputs.py
python
InputProperties.check
(self)
Checks for optional parameters.
Checks for optional parameters.
[ "Checks", "for", "optional", "parameters", "." ]
def check(self): """Checks for optional parameters.""" super(InputProperties,self).check() if self.stride.fetch() < 0: raise ValueError("The stride length for the properties file output must be positive.")
[ "def", "check", "(", "self", ")", ":", "super", "(", "InputProperties", ",", "self", ")", ".", "check", "(", ")", "if", "self", ".", "stride", ".", "fetch", "(", ")", "<", "0", ":", "raise", "ValueError", "(", "\"The stride length for the properties file o...
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/inputs/outputs.py#L82-L87
SpaceNetChallenge/BuildingDetectors
3def3c44b5847c744cd2f3356182892d92496579
qinhaifang/src/caffe-mnc/python/caffe/io.py
python
Transformer.preprocess
(self, in_, data)
return caffe_in
Format input for Caffe: - convert to single - resize to input dimensions (preserving number of channels) - transpose dimensions to K x H x W - reorder channels (for instance color to BGR) - scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models) - subtract mean - scale feature Parameters ---------- in_ : name of input blob to preprocess for data : (H' x W' x K) ndarray Returns ------- caffe_in : (K x H x W) ndarray for input to a Net
Format input for Caffe: - convert to single - resize to input dimensions (preserving number of channels) - transpose dimensions to K x H x W - reorder channels (for instance color to BGR) - scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models) - subtract mean - scale feature
[ "Format", "input", "for", "Caffe", ":", "-", "convert", "to", "single", "-", "resize", "to", "input", "dimensions", "(", "preserving", "number", "of", "channels", ")", "-", "transpose", "dimensions", "to", "K", "x", "H", "x", "W", "-", "reorder", "channe...
def preprocess(self, in_, data): """ Format input for Caffe: - convert to single - resize to input dimensions (preserving number of channels) - transpose dimensions to K x H x W - reorder channels (for instance color to BGR) - scale raw input (e.g. from [0, 1] to [0, 255] for ImageNet models) - subtract mean - scale feature Parameters ---------- in_ : name of input blob to preprocess for data : (H' x W' x K) ndarray Returns ------- caffe_in : (K x H x W) ndarray for input to a Net """ self.__check_input(in_) caffe_in = data.astype(np.float32, copy=False) transpose = self.transpose.get(in_) channel_swap = self.channel_swap.get(in_) raw_scale = self.raw_scale.get(in_) mean = self.mean.get(in_) input_scale = self.input_scale.get(in_) in_dims = self.inputs[in_][2:] if caffe_in.shape[:2] != in_dims: caffe_in = resize_image(caffe_in, in_dims) if transpose is not None: caffe_in = caffe_in.transpose(transpose) if channel_swap is not None: caffe_in = caffe_in[channel_swap, :, :] if raw_scale is not None: caffe_in *= raw_scale if mean is not None: caffe_in -= mean if input_scale is not None: caffe_in *= input_scale return caffe_in
[ "def", "preprocess", "(", "self", ",", "in_", ",", "data", ")", ":", "self", ".", "__check_input", "(", "in_", ")", "caffe_in", "=", "data", ".", "astype", "(", "np", ".", "float32", ",", "copy", "=", "False", ")", "transpose", "=", "self", ".", "t...
https://github.com/SpaceNetChallenge/BuildingDetectors/blob/3def3c44b5847c744cd2f3356182892d92496579/qinhaifang/src/caffe-mnc/python/caffe/io.py#L121-L161
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/tornado/tornado-6/tornado/websocket.py
python
WebSocketHandler.ping_interval
(self)
return self.settings.get("websocket_ping_interval", None)
The interval for websocket keep-alive pings. Set websocket_ping_interval = 0 to disable pings.
The interval for websocket keep-alive pings.
[ "The", "interval", "for", "websocket", "keep", "-", "alive", "pings", "." ]
def ping_interval(self) -> Optional[float]: """The interval for websocket keep-alive pings. Set websocket_ping_interval = 0 to disable pings. """ return self.settings.get("websocket_ping_interval", None)
[ "def", "ping_interval", "(", "self", ")", "->", "Optional", "[", "float", "]", ":", "return", "self", ".", "settings", ".", "get", "(", "\"websocket_ping_interval\"", ",", "None", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/tornado/tornado-6/tornado/websocket.py#L284-L289
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/ceph_deploy.py
python
cli_test
(ctx, config)
ceph-deploy cli to exercise most commonly use cli's and ensure all commands works and also startup the init system.
ceph-deploy cli to exercise most commonly use cli's and ensure all commands works and also startup the init system.
[ "ceph", "-", "deploy", "cli", "to", "exercise", "most", "commonly", "use", "cli", "s", "and", "ensure", "all", "commands", "works", "and", "also", "startup", "the", "init", "system", "." ]
def cli_test(ctx, config): """ ceph-deploy cli to exercise most commonly use cli's and ensure all commands works and also startup the init system. """ log.info('Ceph-deploy Test') if config is None: config = {} test_branch = '' conf_dir = teuthology.get_testdir(ctx) + "/cdtest" def execute_cdeploy(admin, cmd, path): """Execute ceph-deploy commands """ """Either use git path or repo path """ args = ['cd', conf_dir, run.Raw(';')] if path: args.append('{path}/ceph-deploy/ceph-deploy'.format(path=path)) else: args.append('ceph-deploy') args.append(run.Raw(cmd)) ec = admin.run(args=args, check_status=False).exitstatus if ec != 0: raise RuntimeError( "failed during ceph-deploy cmd: {cmd} , ec={ec}".format(cmd=cmd, ec=ec)) if config.get('rhbuild'): path = None else: path = teuthology.get_testdir(ctx) # test on branch from config eg: wip-* , master or next etc # packages for all distro's should exist for wip* if ctx.config.get('branch'): branch = ctx.config.get('branch') test_branch = ' --dev={branch} '.format(branch=branch) mons = ctx.cluster.only(teuthology.is_type('mon')) for node, role in mons.remotes.items(): admin = node admin.run(args=['mkdir', conf_dir], check_status=False) nodename = admin.shortname system_type = teuthology.get_system_type(admin) if config.get('rhbuild'): admin.run(args=['sudo', 'yum', 'install', 'ceph-deploy', '-y']) log.info('system type is %s', system_type) osds = ctx.cluster.only(teuthology.is_type('osd')) for remote, roles in osds.remotes.items(): devs = teuthology.get_scratch_devices(remote) log.info("roles %s", roles) if (len(devs) < 3): log.error( 'Test needs minimum of 3 devices, only found %s', str(devs)) raise RuntimeError("Needs minimum of 3 devices ") conf_path = '{conf_dir}/ceph.conf'.format(conf_dir=conf_dir) new_cmd = 'new ' + nodename execute_cdeploy(admin, new_cmd, path) if config.get('conf') is not None: confp = config.get('conf') for section, keys in confp.items(): lines = '[{section}]\n'.format(section=section) admin.sudo_write_file(conf_path, lines, append=True) for key, value in keys.items(): log.info("[%s] %s = %s" % (section, key, value)) lines = '{key} = {value}\n'.format(key=key, value=value) admin.sudo_write_file(conf_path, lines, append=True) new_mon_install = 'install {branch} --mon '.format( branch=test_branch) + nodename new_mgr_install = 'install {branch} --mgr '.format( branch=test_branch) + nodename new_osd_install = 'install {branch} --osd '.format( branch=test_branch) + nodename new_admin = 'install {branch} --cli '.format(branch=test_branch) + nodename create_initial = 'mon create-initial ' mgr_create = 'mgr create ' + nodename # either use create-keys or push command push_keys = 'admin ' + nodename execute_cdeploy(admin, new_mon_install, path) execute_cdeploy(admin, new_mgr_install, path) execute_cdeploy(admin, new_osd_install, path) execute_cdeploy(admin, new_admin, path) execute_cdeploy(admin, create_initial, path) execute_cdeploy(admin, mgr_create, path) execute_cdeploy(admin, push_keys, path) for i in range(3): zap_disk = 'disk zap ' + "{n}:{d}".format(n=nodename, d=devs[i]) prepare = 'osd prepare ' + "{n}:{d}".format(n=nodename, d=devs[i]) execute_cdeploy(admin, zap_disk, path) execute_cdeploy(admin, prepare, path) log.info("list files for debugging purpose to check file permissions") admin.run(args=['ls', run.Raw('-lt'), conf_dir]) remote.run(args=['sudo', 'ceph', '-s'], check_status=False) out = remote.sh('sudo ceph health') log.info('Ceph health: %s', out.rstrip('\n')) log.info("Waiting for cluster to become healthy") with contextutil.safe_while(sleep=10, tries=6, action='check health') as proceed: while proceed(): out = remote.sh('sudo ceph health') if (out.split(None, 1)[0] == 'HEALTH_OK'): break rgw_install = 'install {branch} --rgw {node}'.format( branch=test_branch, node=nodename, ) rgw_create = 'rgw create ' + nodename execute_cdeploy(admin, rgw_install, path) execute_cdeploy(admin, rgw_create, path) log.info('All ceph-deploy cli tests passed') try: yield finally: log.info("cleaning up") ctx.cluster.run(args=['sudo', 'systemctl', 'stop', 'ceph.target'], check_status=False) time.sleep(4) for i in range(3): umount_dev = "{d}1".format(d=devs[i]) remote.run(args=['sudo', 'umount', run.Raw(umount_dev)]) cmd = 'purge ' + nodename execute_cdeploy(admin, cmd, path) cmd = 'purgedata ' + nodename execute_cdeploy(admin, cmd, path) log.info("Removing temporary dir") admin.run( args=[ 'rm', run.Raw('-rf'), run.Raw(conf_dir)], check_status=False) if config.get('rhbuild'): admin.run(args=['sudo', 'yum', 'remove', 'ceph-deploy', '-y'])
[ "def", "cli_test", "(", "ctx", ",", "config", ")", ":", "log", ".", "info", "(", "'Ceph-deploy Test'", ")", "if", "config", "is", "None", ":", "config", "=", "{", "}", "test_branch", "=", "''", "conf_dir", "=", "teuthology", ".", "get_testdir", "(", "c...
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/ceph_deploy.py#L567-L701
widelands/widelands
e9f047d46a23d81312237d52eabf7d74e8de52d6
utils/make_spritemap.py
python
build_frame_group_regions
(frames)
return (float(cost) / len(frames), newframes)
Given a list of frame, identify variable subregions and split frames into blits accordingly. Return (avgcost, list of list of ((x, y), pic, pc_pic))
Given a list of frame, identify variable subregions and split frames into blits accordingly.
[ "Given", "a", "list", "of", "frame", "identify", "variable", "subregions", "and", "split", "frames", "into", "blits", "accordingly", "." ]
def build_frame_group_regions(frames): """Given a list of frame, identify variable subregions and split frames into blits accordingly. Return (avgcost, list of list of ((x, y), pic, pc_pic)) """ pc = frames[0].pc_pic is not None regions = [] if len(frames) > 1: # Find the regions that are not equal over all frames followers = np.asarray([frame.pic for frame in frames[1:]]) diff = np.any(np.any(frames[0].pic != followers, 3), 0) if pc: followers_pc = np.asarray([frame.pc_pic for frame in frames[1:]]) diff = diff | np.any(np.any(frames[0].pc_pic != followers_pc, 3) & followers[ :, :, :, 3] != 0, 0) # TODO: use rectangle covering instead, once it becomes more efficient label_img, nlabels = ndimage.label(diff) for i in range(1, nlabels + 1): ys, xs = np.where(label_img == i) regions.append((ys.min(), xs.min(), ys.max() + 1, xs.max() + 1)) else: diff = np.zeros(frames[0].pic.shape[:2], np.bool) base_pic_mask = frames[0].pic[:, :, 3] != 0 & ~diff for region in regions: base_pic_mask[region[0]:region[2], region[1]:region[3]] = False ys, xs = np.where(base_pic_mask) cost = 0 base_pic_rect = None if len(ys) and len(xs): base_pic_rect = (ys.min(), xs.min(), ys.max() + 1, xs.max() + 1) base_pic_base = frames[0].pic.copy() base_pic_base[:, :, 3] = np.choose( base_pic_mask, [0, base_pic_base[:, :, 3]]) base_pic = base_pic_base[base_pic_rect[0]:base_pic_rect[ 2], base_pic_rect[1]:base_pic_rect[3]] if pc: base_pic_pc = frames[0].pc_pic[base_pic_rect[ 0]:base_pic_rect[2], base_pic_rect[1]:base_pic_rect[3]] else: base_pic_pc = None cost = rectangle_cost(base_pic_rect) newframes = [] for frame in frames: newframe = [((base_pic_rect[0], base_pic_rect[1]), base_pic, base_pic_pc)] if base_pic_rect else [] for region in regions: pic = frame.pic[region[0]:region[2], region[1]:region[3]] if pc: pc_pic = frame.pc_pic[region[0]:region[2], region[1]:region[3]] else: pc_pic = None newframe.append(((region[0], region[1]), pic, pc_pic)) cost += rectangle_cost(region) newframes.append(newframe) return (float(cost) / len(frames), newframes)
[ "def", "build_frame_group_regions", "(", "frames", ")", ":", "pc", "=", "frames", "[", "0", "]", ".", "pc_pic", "is", "not", "None", "regions", "=", "[", "]", "if", "len", "(", "frames", ")", ">", "1", ":", "# Find the regions that are not equal over all fra...
https://github.com/widelands/widelands/blob/e9f047d46a23d81312237d52eabf7d74e8de52d6/utils/make_spritemap.py#L306-L367
Project-OSRM/osrm-backend
f2e284623e25b5570dd2a5e6985abcb3790fd348
third_party/flatbuffers/python/flatbuffers/table.py
python
Table.Vector
(self, off)
return x
Vector retrieves the start of data of the vector whose offset is stored at "off" in this object.
Vector retrieves the start of data of the vector whose offset is stored at "off" in this object.
[ "Vector", "retrieves", "the", "start", "of", "data", "of", "the", "vector", "whose", "offset", "is", "stored", "at", "off", "in", "this", "object", "." ]
def Vector(self, off): """Vector retrieves the start of data of the vector whose offset is stored at "off" in this object.""" N.enforce_number(off, N.UOffsetTFlags) off += self.Pos x = off + self.Get(N.UOffsetTFlags, off) # data starts after metadata containing the vector length x += N.UOffsetTFlags.bytewidth return x
[ "def", "Vector", "(", "self", ",", "off", ")", ":", "N", ".", "enforce_number", "(", "off", ",", "N", ".", "UOffsetTFlags", ")", "off", "+=", "self", ".", "Pos", "x", "=", "off", "+", "self", ".", "Get", "(", "N", ".", "UOffsetTFlags", ",", "off"...
https://github.com/Project-OSRM/osrm-backend/blob/f2e284623e25b5570dd2a5e6985abcb3790fd348/third_party/flatbuffers/python/flatbuffers/table.py#L66-L75
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
clang/tools/scan-build-py/lib/libscanbuild/intercept.py
python
is_preload_disabled
(platform)
Library-based interposition will fail silently if SIP is enabled, so this should be detected. You can detect whether SIP is enabled on Darwin by checking whether (1) there is a binary called 'csrutil' in the path and, if so, (2) whether the output of executing 'csrutil status' contains 'System Integrity Protection status: enabled'. :param platform: name of the platform (returned by sys.platform), :return: True if library preload will fail by the dynamic linker.
Library-based interposition will fail silently if SIP is enabled, so this should be detected. You can detect whether SIP is enabled on Darwin by checking whether (1) there is a binary called 'csrutil' in the path and, if so, (2) whether the output of executing 'csrutil status' contains 'System Integrity Protection status: enabled'.
[ "Library", "-", "based", "interposition", "will", "fail", "silently", "if", "SIP", "is", "enabled", "so", "this", "should", "be", "detected", ".", "You", "can", "detect", "whether", "SIP", "is", "enabled", "on", "Darwin", "by", "checking", "whether", "(", ...
def is_preload_disabled(platform): """ Library-based interposition will fail silently if SIP is enabled, so this should be detected. You can detect whether SIP is enabled on Darwin by checking whether (1) there is a binary called 'csrutil' in the path and, if so, (2) whether the output of executing 'csrutil status' contains 'System Integrity Protection status: enabled'. :param platform: name of the platform (returned by sys.platform), :return: True if library preload will fail by the dynamic linker. """ if platform in WRAPPER_ONLY_PLATFORMS: return True elif platform == 'darwin': command = ['csrutil', 'status'] pattern = re.compile(r'System Integrity Protection status:\s+enabled') try: return any(pattern.match(line) for line in run_command(command)) except: return False else: return False
[ "def", "is_preload_disabled", "(", "platform", ")", ":", "if", "platform", "in", "WRAPPER_ONLY_PLATFORMS", ":", "return", "True", "elif", "platform", "==", "'darwin'", ":", "command", "=", "[", "'csrutil'", ",", "'status'", "]", "pattern", "=", "re", ".", "c...
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang/tools/scan-build-py/lib/libscanbuild/intercept.py#L226-L246
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/richtext.py
python
RichTextFileHandler.SaveStream
(*args, **kwargs)
return _richtext.RichTextFileHandler_SaveStream(*args, **kwargs)
SaveStream(self, RichTextBuffer buffer, wxOutputStream stream) -> bool
SaveStream(self, RichTextBuffer buffer, wxOutputStream stream) -> bool
[ "SaveStream", "(", "self", "RichTextBuffer", "buffer", "wxOutputStream", "stream", ")", "-", ">", "bool" ]
def SaveStream(*args, **kwargs): """SaveStream(self, RichTextBuffer buffer, wxOutputStream stream) -> bool""" return _richtext.RichTextFileHandler_SaveStream(*args, **kwargs)
[ "def", "SaveStream", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextFileHandler_SaveStream", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/richtext.py#L2756-L2758
facebookincubator/katran
192eb988c398afc673620254097defb7035d669e
build/fbcode_builder/getdeps/manifest.py
python
ManifestParser.is_first_party_project
(self)
return self.shipit_project is not None
returns true if this is an FB first-party project
returns true if this is an FB first-party project
[ "returns", "true", "if", "this", "is", "an", "FB", "first", "-", "party", "project" ]
def is_first_party_project(self): """returns true if this is an FB first-party project""" return self.shipit_project is not None
[ "def", "is_first_party_project", "(", "self", ")", ":", "return", "self", ".", "shipit_project", "is", "not", "None" ]
https://github.com/facebookincubator/katran/blob/192eb988c398afc673620254097defb7035d669e/build/fbcode_builder/getdeps/manifest.py#L355-L357
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/mem/qos/QoSMemSinkInterface.py
python
QoSMemSinkInterface.controller
(self)
return controller
Instantiate the memory controller and bind it to the current interface.
Instantiate the memory controller and bind it to the current interface.
[ "Instantiate", "the", "memory", "controller", "and", "bind", "it", "to", "the", "current", "interface", "." ]
def controller(self): """ Instantiate the memory controller and bind it to the current interface. """ controller = QoSMemSinkCtrl() controller.interface = self return controller
[ "def", "controller", "(", "self", ")", ":", "controller", "=", "QoSMemSinkCtrl", "(", ")", "controller", ".", "interface", "=", "self", "return", "controller" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/mem/qos/QoSMemSinkInterface.py#L43-L50
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/distutils/ccompiler_opt.py
python
_Parse._parse_policy_autovec
(self, has_baseline, final_targets, extra_flags)
return has_baseline, final_targets, extra_flags
skip features that has no auto-vectorized support by compiler
skip features that has no auto-vectorized support by compiler
[ "skip", "features", "that", "has", "no", "auto", "-", "vectorized", "support", "by", "compiler" ]
def _parse_policy_autovec(self, has_baseline, final_targets, extra_flags): """skip features that has no auto-vectorized support by compiler""" skipped = [] for tar in final_targets[:]: if isinstance(tar, str): can = self.feature_can_autovec(tar) else: # multiple target can = all([ self.feature_can_autovec(t) for t in tar ]) if not can: final_targets.remove(tar) skipped.append(tar) if skipped: self.dist_log("skip non auto-vectorized features", skipped) return has_baseline, final_targets, extra_flags
[ "def", "_parse_policy_autovec", "(", "self", ",", "has_baseline", ",", "final_targets", ",", "extra_flags", ")", ":", "skipped", "=", "[", "]", "for", "tar", "in", "final_targets", "[", ":", "]", ":", "if", "isinstance", "(", "tar", ",", "str", ")", ":",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/distutils/ccompiler_opt.py#L2099-L2117
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/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/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/models.py#L901-L916
giuspen/cherrytree
84712f206478fcf9acf30174009ad28c648c6344
pygtk2/modules/tablez.py
python
TablesHandler.on_table_cell_key_press
(self, widget, event, path, model, col_num)
return False
Catches Table Cell key presses
Catches Table Cell key presses
[ "Catches", "Table", "Cell", "key", "presses" ]
def on_table_cell_key_press(self, widget, event, path, model, col_num): """Catches Table Cell key presses""" keyname = gtk.gdk.keyval_name(event.keyval) if event.state & gtk.gdk.SHIFT_MASK: pass elif event.state & gtk.gdk.MOD1_MASK: pass elif event.state & gtk.gdk.CONTROL_MASK: # on Win32, emtpy Ctrl deselects selected text, so to fix it if cons.IS_WIN_OS: if keyname in cons.STR_KEYS_CONTROL: return True if keyname == "period": self.curr_table_cell = widget self.curr_table_cell_insert_newline() return True elif keyname == "comma": return True else: if keyname in [cons.STR_KEY_RETURN, cons.STR_KEY_TAB, cons.STR_KEY_UP, cons.STR_KEY_DOWN]: if model[path][col_num] != widget.get_text(): if self.dad.is_curr_node_not_read_only_or_error(): model[path][col_num] = widget.get_text() self.dad.update_window_save_needed("nbuf", True) if keyname == cons.STR_KEY_UP: if col_num > 0: next_col_num = col_num - 1 next_path = path else: next_iter = None next_path = model.get_path(model.get_iter(path)) while not next_iter and next_path[0] > 0: node_path_list = list(next_path) node_path_list[0] -= 1 next_path = tuple(node_path_list) next_iter = model.get_iter(next_path) #next_iter = model.iter_next(model.get_iter(path)) if not next_iter: return False next_path = model.get_path(next_iter) next_col_num = self.dad.table_columns-1 else: if col_num < self.dad.table_columns-1: next_col_num = col_num + 1 next_path = path else: next_iter = model.iter_next(model.get_iter(path)) if not next_iter: return False next_path = model.get_path(next_iter) next_col_num = 0 #print "(path, col_num) = (%s, %s)" % (path, col_num) #print "(next_path, next_col_num) = (%s, %s)" % (next_path, next_col_num) next_column = self.curr_table_anchor.treeview.get_columns()[next_col_num] self.curr_table_anchor.treeview.set_cursor_on_cell(next_path, focus_column=next_column, focus_cell=next_column.get_cell_renderers()[0], start_editing=True) return True return False
[ "def", "on_table_cell_key_press", "(", "self", ",", "widget", ",", "event", ",", "path", ",", "model", ",", "col_num", ")", ":", "keyname", "=", "gtk", ".", "gdk", ".", "keyval_name", "(", "event", ".", "keyval", ")", "if", "event", ".", "state", "&", ...
https://github.com/giuspen/cherrytree/blob/84712f206478fcf9acf30174009ad28c648c6344/pygtk2/modules/tablez.py#L403-L460
cyberbotics/webots
af7fa7d68dcf7b4550f1f2e132092b41e83698fc
resources/osm_importer/utils/vector.py
python
Vector2D.__truediv__
(self, other)
Divide the vector to another.
Divide the vector to another.
[ "Divide", "the", "vector", "to", "another", "." ]
def __truediv__(self, other): """Divide the vector to another.""" if isinstance(other, Vector2D): # Dot product return self.x / other.x + self.y / other.y elif isinstance(other, float): # Scalar product return Vector2D(self.x / other, self.y / other) else: raise TypeError()
[ "def", "__truediv__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Vector2D", ")", ":", "# Dot product", "return", "self", ".", "x", "/", "other", ".", "x", "+", "self", ".", "y", "/", "other", ".", "y", "elif", "is...
https://github.com/cyberbotics/webots/blob/af7fa7d68dcf7b4550f1f2e132092b41e83698fc/resources/osm_importer/utils/vector.py#L63-L72
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftmake/make_line.py
python
make_line
(first_param, last_param=None)
return obj
makeLine(first_param, p2) Creates a line from 2 points or from a given object. Parameters ---------- first_param : Base.Vector -> First point of the line (if p2 is None) Part.LineSegment -> Line is created from the given Linesegment Shape -> Line is created from the give Shape last_param : Base.Vector Second point of the line, if not set the function evaluates the first_param to look for a Part.LineSegment or a Shape
makeLine(first_param, p2) Creates a line from 2 points or from a given object.
[ "makeLine", "(", "first_param", "p2", ")", "Creates", "a", "line", "from", "2", "points", "or", "from", "a", "given", "object", "." ]
def make_line(first_param, last_param=None): """makeLine(first_param, p2) Creates a line from 2 points or from a given object. Parameters ---------- first_param : Base.Vector -> First point of the line (if p2 is None) Part.LineSegment -> Line is created from the given Linesegment Shape -> Line is created from the give Shape last_param : Base.Vector Second point of the line, if not set the function evaluates the first_param to look for a Part.LineSegment or a Shape """ if last_param: p1 = first_param p2 = last_param else: if hasattr(first_param, "StartPoint") and hasattr(first_param, "EndPoint"): p2 = first_param.EndPoint p1 = first_param.StartPoint elif hasattr(p1,"Vertexes"): p2 = first_param.Vertexes[-1].Point p1 = first_param.Vertexes[0].Point else: _err = "Unable to create a line from the given parameters" App.Console.PrintError(_err + "\n") return obj = make_wire.make_wire([p1,p2]) return obj
[ "def", "make_line", "(", "first_param", ",", "last_param", "=", "None", ")", ":", "if", "last_param", ":", "p1", "=", "first_param", "p2", "=", "last_param", "else", ":", "if", "hasattr", "(", "first_param", ",", "\"StartPoint\"", ")", "and", "hasattr", "(...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftmake/make_line.py#L34-L67
QMCPACK/qmcpack
d0948ab455e38364458740cc8e2239600a14c5cd
nexus/lib/grid_functions.py
python
ParallelotopeGrid.initialize_local
(self, axes = None, shape = None, cells = None, dr = None, corner = None, center = None, centered = False, **kwargs )
(`Internal API`) Initialize the parallelotope grid points and set the origin if not provided.
(`Internal API`) Initialize the parallelotope grid points and set the origin if not provided.
[ "(", "Internal", "API", ")", "Initialize", "the", "parallelotope", "grid", "points", "and", "set", "the", "origin", "if", "not", "provided", "." ]
def initialize_local(self, axes = None, shape = None, cells = None, dr = None, corner = None, center = None, centered = False, **kwargs ): """ (`Internal API`) Initialize the parallelotope grid points and set the origin if not provided. """ if shape is None and cells is None and dr is None: self.error('cannot initialize grid, either "shape", "cells", or "dr" is required') elif shape is not None: grid_dim = len(shape) elif cells is not None: grid_dim = len(cells) elif dr is not None: grid_dim = len(dr) #end if bconds = kwargs.get('bconds',None) endpoint = self.has_endpoints(bconds=bconds,grid_dim=grid_dim) points,shape,axes = parallelotope_grid_points( axes = axes, shape = shape, cells = cells, dr = dr, centered = centered, endpoint = endpoint, return_shape = True, return_axes = True ) if center is not None: center = np.array(center) corner = center - axes.sum(axis=0)/2 #end if kwargs['axes'] = axes if corner is not None: kwargs['origin'] = corner #end if kwargs['shape'] = shape kwargs['centered'] = centered kwargs['points'] = points StructuredGridWithAxes.initialize_local(self,**kwargs)
[ "def", "initialize_local", "(", "self", ",", "axes", "=", "None", ",", "shape", "=", "None", ",", "cells", "=", "None", ",", "dr", "=", "None", ",", "corner", "=", "None", ",", "center", "=", "None", ",", "centered", "=", "False", ",", "*", "*", ...
https://github.com/QMCPACK/qmcpack/blob/d0948ab455e38364458740cc8e2239600a14c5cd/nexus/lib/grid_functions.py#L2221-L2271