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
qt/qtwebkit
ab1bd15209abaf7effc51dbc2f272c5681af7223
Source/WebInspectorUI/Scripts/jsmin.py
python
jsmin
(js)
return outs.getvalue()
returns a minified version of the javascript string
returns a minified version of the javascript string
[ "returns", "a", "minified", "version", "of", "the", "javascript", "string" ]
def jsmin(js): """ returns a minified version of the javascript string """ if not is_3: if cStringIO and not isinstance(js, unicode): # strings can use cStringIO for a 3x performance # improvement, but unicode (in python2) cannot klass = cStringIO.StringIO else: klass = StringIO.StringIO else: klass = io.StringIO ins = klass(js) outs = klass() JavascriptMinify(ins, outs).minify() return outs.getvalue()
[ "def", "jsmin", "(", "js", ")", ":", "if", "not", "is_3", ":", "if", "cStringIO", "and", "not", "isinstance", "(", "js", ",", "unicode", ")", ":", "# strings can use cStringIO for a 3x performance", "# improvement, but unicode (in python2) cannot", "klass", "=", "cS...
https://github.com/qt/qtwebkit/blob/ab1bd15209abaf7effc51dbc2f272c5681af7223/Source/WebInspectorUI/Scripts/jsmin.py#L43-L59
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
configure.py
python
get_var
(environ_cp, var_name, query_item, enabled_by_default, question=None, yes_reply=None, no_reply=None)
return var
Get boolean input from user. If var_name is not set in env, ask user to enable query_item or not. If the response is empty, use the default. Args: environ_cp: copy of the os.environ. var_name: string for name of environment variable, e.g. "TF_NEED_HDFS". query_item: string for feature related to the variable, e.g. "Hadoop File System". enabled_by_default: boolean for default behavior. question: optional string for how to ask for user input. yes_reply: optionanl string for reply when feature is enabled. no_reply: optional string for reply when feature is disabled. Returns: boolean value of the variable.
Get boolean input from user.
[ "Get", "boolean", "input", "from", "user", "." ]
def get_var(environ_cp, var_name, query_item, enabled_by_default, question=None, yes_reply=None, no_reply=None): """Get boolean input from user. If var_name is not set in env, ask user to enable query_item or not. If the response is empty, use the default. Args: environ_cp: copy of the os.environ. var_name: string for name of environment variable, e.g. "TF_NEED_HDFS". query_item: string for feature related to the variable, e.g. "Hadoop File System". enabled_by_default: boolean for default behavior. question: optional string for how to ask for user input. yes_reply: optionanl string for reply when feature is enabled. no_reply: optional string for reply when feature is disabled. Returns: boolean value of the variable. """ if not question: question = 'Do you wish to build TensorFlow with %s support?' % query_item if not yes_reply: yes_reply = '%s support will be enabled for TensorFlow.' % query_item if not no_reply: no_reply = 'No %s' % yes_reply yes_reply += '\n' no_reply += '\n' if enabled_by_default: question += ' [Y/n]: ' else: question += ' [y/N]: ' var = environ_cp.get(var_name) while var is None: user_input_origin = get_input(question) user_input = user_input_origin.strip().lower() if user_input == 'y': print(yes_reply) var = True elif user_input == 'n': print(no_reply) var = False elif not user_input: if enabled_by_default: print(yes_reply) var = True else: print(no_reply) var = False else: print('Invalid selection: %s' % user_input_origin) return var
[ "def", "get_var", "(", "environ_cp", ",", "var_name", ",", "query_item", ",", "enabled_by_default", ",", "question", "=", "None", ",", "yes_reply", "=", "None", ",", "no_reply", "=", "None", ")", ":", "if", "not", "question", ":", "question", "=", "'Do you...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/configure.py#L290-L349
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/html.py
python
HtmlParser.InitParser
(*args, **kwargs)
return _html.HtmlParser_InitParser(*args, **kwargs)
InitParser(self, String source)
InitParser(self, String source)
[ "InitParser", "(", "self", "String", "source", ")" ]
def InitParser(*args, **kwargs): """InitParser(self, String source)""" return _html.HtmlParser_InitParser(*args, **kwargs)
[ "def", "InitParser", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlParser_InitParser", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/html.py#L197-L199
doxygen/doxygen
c5d4b67565a5fadea5d84d28cfe86db605b4593f
doc/translator.py
python
TrManager.__emails
(self, classId)
return lst
Returns the list of maintainer emails. The method returns the list of e-mail addresses for the translator class, but only the addresses that were not marked as [xxx].
Returns the list of maintainer emails.
[ "Returns", "the", "list", "of", "maintainer", "emails", "." ]
def __emails(self, classId): """Returns the list of maintainer emails. The method returns the list of e-mail addresses for the translator class, but only the addresses that were not marked as [xxx].""" lst = [] for m in self.__maintainersDic[classId]: if not m[1].startswith('['): email = m[1] email = email.replace(' at ', '@') # Unmangle the mangled e-mail email = email.replace(' dot ', '.') lst.append(email) return lst
[ "def", "__emails", "(", "self", ",", "classId", ")", ":", "lst", "=", "[", "]", "for", "m", "in", "self", ".", "__maintainersDic", "[", "classId", "]", ":", "if", "not", "m", "[", "1", "]", ".", "startswith", "(", "'['", ")", ":", "email", "=", ...
https://github.com/doxygen/doxygen/blob/c5d4b67565a5fadea5d84d28cfe86db605b4593f/doc/translator.py#L1502-L1514
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
TreeCtrl.HitTest
(*args, **kwargs)
return _controls_.TreeCtrl_HitTest(*args, **kwargs)
HitTest(Point point) -> (item, where) Determine which item (if any) belongs the given point. The coordinates specified are relative to the client area of tree ctrl and the where return value is set to a bitmask of wxTREE_HITTEST_xxx constants.
HitTest(Point point) -> (item, where)
[ "HitTest", "(", "Point", "point", ")", "-", ">", "(", "item", "where", ")" ]
def HitTest(*args, **kwargs): """ HitTest(Point point) -> (item, where) Determine which item (if any) belongs the given point. The coordinates specified are relative to the client area of tree ctrl and the where return value is set to a bitmask of wxTREE_HITTEST_xxx constants. """ return _controls_.TreeCtrl_HitTest(*args, **kwargs)
[ "def", "HitTest", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TreeCtrl_HitTest", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L5539-L5548
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/grid.py
python
Grid.GetColSize
(*args, **kwargs)
return _grid.Grid_GetColSize(*args, **kwargs)
GetColSize(self, int col) -> int
GetColSize(self, int col) -> int
[ "GetColSize", "(", "self", "int", "col", ")", "-", ">", "int" ]
def GetColSize(*args, **kwargs): """GetColSize(self, int col) -> int""" return _grid.Grid_GetColSize(*args, **kwargs)
[ "def", "GetColSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_GetColSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/grid.py#L1762-L1764
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/cond_v2.py
python
_get_intermediates
(func_graph)
return intermediates
Returns intermediate tensors of `func_graph` for gradient computation.
Returns intermediate tensors of `func_graph` for gradient computation.
[ "Returns", "intermediate", "tensors", "of", "func_graph", "for", "gradient", "computation", "." ]
def _get_intermediates(func_graph): """Returns intermediate tensors of `func_graph` for gradient computation.""" intermediates = [] for op in func_graph.get_operations(): for t in op.outputs: if t in func_graph.inputs: continue if t in func_graph.outputs: continue if t.dtype is dtypes.resource: continue # Accumulating mutexes can cause deadlock. if op.type == "MutexLock": continue intermediates.append(t) return intermediates
[ "def", "_get_intermediates", "(", "func_graph", ")", ":", "intermediates", "=", "[", "]", "for", "op", "in", "func_graph", ".", "get_operations", "(", ")", ":", "for", "t", "in", "op", ".", "outputs", ":", "if", "t", "in", "func_graph", ".", "inputs", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/cond_v2.py#L450-L463
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/stats/_multivariate.py
python
multinomial_gen.cov
(self, n, p)
return self._checkresult(result, npcond, np.nan)
Covariance matrix of the multinomial distribution. Parameters ---------- %(_doc_default_callparams)s Returns ------- cov : ndarray The covariance matrix of the distribution
Covariance matrix of the multinomial distribution.
[ "Covariance", "matrix", "of", "the", "multinomial", "distribution", "." ]
def cov(self, n, p): """ Covariance matrix of the multinomial distribution. Parameters ---------- %(_doc_default_callparams)s Returns ------- cov : ndarray The covariance matrix of the distribution """ n, p, npcond = self._process_parameters(n, p) nn = n[..., np.newaxis, np.newaxis] result = nn * np.einsum('...j,...k->...jk', -p, p) # change the diagonal for i in range(p.shape[-1]): result[..., i, i] += n*p[..., i] return self._checkresult(result, npcond, np.nan)
[ "def", "cov", "(", "self", ",", "n", ",", "p", ")", ":", "n", ",", "p", ",", "npcond", "=", "self", ".", "_process_parameters", "(", "n", ",", "p", ")", "nn", "=", "n", "[", "...", ",", "np", ".", "newaxis", ",", "np", ".", "newaxis", "]", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/stats/_multivariate.py#L3134-L3156
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/sysconfig.py
python
get_platform
()
return "%s-%s-%s" % (osname, release, machine)
Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; on Linux, the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'.
Return a string that identifies the current platform.
[ "Return", "a", "string", "that", "identifies", "the", "current", "platform", "." ]
def get_platform(): """Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; on Linux, the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'. """ if os.name == 'nt': if 'amd64' in sys.version.lower(): return 'win-amd64' return sys.platform if os.name != "posix" or not hasattr(os, 'uname'): # XXX what about the architecture? NT is Intel or Alpha return sys.platform # Set for cross builds explicitly if "_PYTHON_HOST_PLATFORM" in os.environ: return os.environ["_PYTHON_HOST_PLATFORM"] # Try to distinguish various flavours of Unix osname, host, release, version, machine = os.uname() # Convert the OS name to lowercase, remove '/' characters, and translate # spaces (for "Power Macintosh") osname = osname.lower().replace('/', '') machine = machine.replace(' ', '_') machine = machine.replace('/', '-') if osname[:5] == "linux": # At least on Linux/Intel, 'machine' is the processor -- # i386, etc. # XXX what about Alpha, SPARC, etc? return "%s-%s" % (osname, machine) elif osname[:5] == "sunos": if release[0] >= "5": # SunOS 5 == Solaris 2 osname = "solaris" release = "%d.%s" % (int(release[0]) - 3, release[2:]) # We can't use "platform.architecture()[0]" because a # bootstrap problem. We use a dict to get an error # if some suspicious happens. bitness = {2147483647:"32bit", 9223372036854775807:"64bit"} machine += ".%s" % bitness[sys.maxsize] # fall through to standard osname-release-machine representation elif osname[:3] == "aix": return "%s-%s.%s" % (osname, version, release) elif osname[:6] == "cygwin": osname = "cygwin" import re rel_re = re.compile(r'[\d.]+') m = rel_re.match(release) if m: release = m.group() elif osname[:6] == "darwin": import _osx_support osname, release, machine = _osx_support.get_platform_osx( get_config_vars(), osname, release, machine) return "%s-%s-%s" % (osname, release, machine)
[ "def", "get_platform", "(", ")", ":", "if", "os", ".", "name", "==", "'nt'", ":", "if", "'amd64'", "in", "sys", ".", "version", ".", "lower", "(", ")", ":", "return", "'win-amd64'", "return", "sys", ".", "platform", "if", "os", ".", "name", "!=", "...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/sysconfig.py#L605-L678
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/md/compute.py
python
ThermodynamicQuantities.potential_energy
(self)
return self._cpp_obj.potential_energy
r""":math:`U`. Potential energy that the group contributes to the entire system :math:`[\mathrm{energy}]`. The potential energy is calculated as a sum of per-particle energy contributions: .. math:: U = \sum_{i \in \mathrm{filter}} U_i, where :math:`U_i` is defined as: .. math:: U_i = U_{\mathrm{pair}, i} + U_{\mathrm{bond}, i} + U_{\mathrm{angle}, i} + U_{\mathrm{dihedral}, i} + U_{\mathrm{improper}, i} + U_{\mathrm{external}, i} + U_{\mathrm{other}, i} and each term on the RHS is calculated as: .. math:: U_{\mathrm{pair}, i} &= \frac{1}{2} \sum_j V_{\mathrm{pair}, ij} U_{\mathrm{bond}, i} &= \frac{1}{2} \sum_{(j, k) \in \mathrm{bonds}} V_{\mathrm{bond}, jk} U_{\mathrm{angle}, i} &= \frac{1}{3} \sum_{(j, k, l) \in \mathrm{angles}} V_{\mathrm{angle}, jkl} U_{\mathrm{dihedral}, i} &= \frac{1}{4} \sum_{(j, k, l, m) \in \mathrm{dihedrals}} V_{\mathrm{dihedral}, jklm} U_{\mathrm{improper}, i} &= \frac{1}{4} \sum_{(j, k, l, m) \in \mathrm{impropers}} V_{\mathrm{improper}, jklm} In each summation above, the indices go over all particles and we only use terms where one of the summation indices (:math:`j`, :math:`k`, :math:`l`, or :math:`m`) is equal to :math:`i`. External and other potentials are summed similar to the other terms using per-particle contributions.
r""":math:`U`.
[ "r", ":", "math", ":", "U", "." ]
def potential_energy(self): r""":math:`U`. Potential energy that the group contributes to the entire system :math:`[\mathrm{energy}]`. The potential energy is calculated as a sum of per-particle energy contributions: .. math:: U = \sum_{i \in \mathrm{filter}} U_i, where :math:`U_i` is defined as: .. math:: U_i = U_{\mathrm{pair}, i} + U_{\mathrm{bond}, i} + U_{\mathrm{angle}, i} + U_{\mathrm{dihedral}, i} + U_{\mathrm{improper}, i} + U_{\mathrm{external}, i} + U_{\mathrm{other}, i} and each term on the RHS is calculated as: .. math:: U_{\mathrm{pair}, i} &= \frac{1}{2} \sum_j V_{\mathrm{pair}, ij} U_{\mathrm{bond}, i} &= \frac{1}{2} \sum_{(j, k) \in \mathrm{bonds}} V_{\mathrm{bond}, jk} U_{\mathrm{angle}, i} &= \frac{1}{3} \sum_{(j, k, l) \in \mathrm{angles}} V_{\mathrm{angle}, jkl} U_{\mathrm{dihedral}, i} &= \frac{1}{4} \sum_{(j, k, l, m) \in \mathrm{dihedrals}} V_{\mathrm{dihedral}, jklm} U_{\mathrm{improper}, i} &= \frac{1}{4} \sum_{(j, k, l, m) \in \mathrm{impropers}} V_{\mathrm{improper}, jklm} In each summation above, the indices go over all particles and we only use terms where one of the summation indices (:math:`j`, :math:`k`, :math:`l`, or :math:`m`) is equal to :math:`i`. External and other potentials are summed similar to the other terms using per-particle contributions. """ self._cpp_obj.compute(self._simulation.timestep) return self._cpp_obj.potential_energy
[ "def", "potential_energy", "(", "self", ")", ":", "self", ".", "_cpp_obj", ".", "compute", "(", "self", ".", "_simulation", ".", "timestep", ")", "return", "self", ".", "_cpp_obj", ".", "potential_energy" ]
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/md/compute.py#L167-L214
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py
python
_ProxyFile.read
(self, size=None)
return self._read(size, self._file.read)
Read bytes.
Read bytes.
[ "Read", "bytes", "." ]
def read(self, size=None): """Read bytes.""" return self._read(size, self._file.read)
[ "def", "read", "(", "self", ",", "size", "=", "None", ")", ":", "return", "self", ".", "_read", "(", "size", ",", "self", ".", "_file", ".", "read", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mailbox.py#L1871-L1873
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/html.py
python
PreHtmlHelpFrame
(*args, **kwargs)
return val
PreHtmlHelpFrame(HtmlHelpData data=None) -> HtmlHelpFrame
PreHtmlHelpFrame(HtmlHelpData data=None) -> HtmlHelpFrame
[ "PreHtmlHelpFrame", "(", "HtmlHelpData", "data", "=", "None", ")", "-", ">", "HtmlHelpFrame" ]
def PreHtmlHelpFrame(*args, **kwargs): """PreHtmlHelpFrame(HtmlHelpData data=None) -> HtmlHelpFrame""" val = _html.new_PreHtmlHelpFrame(*args, **kwargs) self._setOORInfo(self) return val
[ "def", "PreHtmlHelpFrame", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", "=", "_html", ".", "new_PreHtmlHelpFrame", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_setOORInfo", "(", "self", ")", "return", "val" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html.py#L1803-L1807
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py3/numpy/ma/core.py
python
masked_greater_equal
(x, value, copy=True)
return masked_where(greater_equal(x, value), x, copy=copy)
Mask an array where greater than or equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x >= value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_greater_equal(a, 2) masked_array(data=[0, 1, --, --], mask=[False, False, True, True], fill_value=999999)
Mask an array where greater than or equal to a given value.
[ "Mask", "an", "array", "where", "greater", "than", "or", "equal", "to", "a", "given", "value", "." ]
def masked_greater_equal(x, value, copy=True): """ Mask an array where greater than or equal to a given value. This function is a shortcut to ``masked_where``, with `condition` = (x >= value). See Also -------- masked_where : Mask where a condition is met. Examples -------- >>> import numpy.ma as ma >>> a = np.arange(4) >>> a array([0, 1, 2, 3]) >>> ma.masked_greater_equal(a, 2) masked_array(data=[0, 1, --, --], mask=[False, False, True, True], fill_value=999999) """ return masked_where(greater_equal(x, value), x, copy=copy)
[ "def", "masked_greater_equal", "(", "x", ",", "value", ",", "copy", "=", "True", ")", ":", "return", "masked_where", "(", "greater_equal", "(", "x", ",", "value", ")", ",", "x", ",", "copy", "=", "copy", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py3/numpy/ma/core.py#L1972-L1995
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/convert/processor/conversion/ror/pregen_subprocessor.py
python
RoRPregenSubprocessor.generate
(cls, gamedata)
Create nyan objects for hardcoded properties.
Create nyan objects for hardcoded properties.
[ "Create", "nyan", "objects", "for", "hardcoded", "properties", "." ]
def generate(cls, gamedata): """ Create nyan objects for hardcoded properties. """ # Stores pregenerated raw API objects as a container pregen_converter_group = ConverterObjectGroup("pregen") AoCPregenSubprocessor.generate_attributes(gamedata, pregen_converter_group) AoCPregenSubprocessor.generate_diplomatic_stances(gamedata, pregen_converter_group) AoCPregenSubprocessor.generate_entity_types(gamedata, pregen_converter_group) AoCPregenSubprocessor.generate_effect_types(gamedata, pregen_converter_group) AoCPregenSubprocessor.generate_language_objects(gamedata, pregen_converter_group) AoCPregenSubprocessor.generate_misc_effect_objects(gamedata, pregen_converter_group) # TODO: # cls._generate_modifiers(gamedata, pregen_converter_group) AoCPregenSubprocessor.generate_terrain_types(gamedata, pregen_converter_group) AoCPregenSubprocessor.generate_resources(gamedata, pregen_converter_group) cls.generate_death_condition(gamedata, pregen_converter_group) pregen_nyan_objects = gamedata.pregen_nyan_objects # Create nyan objects from the raw API objects for pregen_object in pregen_nyan_objects.values(): pregen_object.create_nyan_object() # This has to be a separate for-loop because of possible object interdependencies for pregen_object in pregen_nyan_objects.values(): pregen_object.create_nyan_members() if not pregen_object.is_ready(): raise Exception("%s: Pregenerated object is not ready for export: " "Member or object not initialized." % (pregen_object))
[ "def", "generate", "(", "cls", ",", "gamedata", ")", ":", "# Stores pregenerated raw API objects as a container", "pregen_converter_group", "=", "ConverterObjectGroup", "(", "\"pregen\"", ")", "AoCPregenSubprocessor", ".", "generate_attributes", "(", "gamedata", ",", "prege...
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/convert/processor/conversion/ror/pregen_subprocessor.py#L21-L51
kristjankorjus/Replicating-DeepMind
68539394e792b34a4d6b430a2eb73b8b8f91d8db
libraries/cuda-convnet2/python_util/options.py
python
OptionsParser.parse
(self, eval_expr_defaults=False)
return self.options
Parses the options in sys.argv based on the options added to this parser. The default behavior is to leave any expression default options as OptionExpression objects. Set eval_expr_defaults=True to circumvent this.
Parses the options in sys.argv based on the options added to this parser. The default behavior is to leave any expression default options as OptionExpression objects. Set eval_expr_defaults=True to circumvent this.
[ "Parses", "the", "options", "in", "sys", ".", "argv", "based", "on", "the", "options", "added", "to", "this", "parser", ".", "The", "default", "behavior", "is", "to", "leave", "any", "expression", "default", "options", "as", "OptionExpression", "objects", "....
def parse(self, eval_expr_defaults=False): """Parses the options in sys.argv based on the options added to this parser. The default behavior is to leave any expression default options as OptionExpression objects. Set eval_expr_defaults=True to circumvent this.""" short_opt_str = ''.join(["%s:" % self.options[name].letter for name in self.options if len(self.options[name].letter) == 1]) long_opts = ["%s=" % self.options[name].letter for name in self.options if len(self.options[name].letter) > 1] (go, ga) = getopt(sys.argv[1:], short_opt_str, longopts=long_opts) dic = dict(go) for o in self.get_options_list(sort_order=self.SORT_EXPR_LAST): if o.prefixed_letter in dic: o.set_value(dic[o.prefixed_letter]) else: # check if excused or has default excused = max([o2.prefixed_letter in dic for o2 in self.options.values() if o2.excuses == self.EXCUSE_ALL or o.name in o2.excuses]) if not excused and o.default is None: raise OptionMissingException("Option %s (%s) not supplied" % (o.prefixed_letter, o.desc)) o.set_default() # check requirements if o.prefixed_letter in dic: for o2 in self.get_options_list(sort_order=self.SORT_LETTER): if o2.name in o.requires and o2.prefixed_letter not in dic: raise OptionMissingException("Option %s (%s) requires option %s (%s)" % (o.prefixed_letter, o.desc, o2.prefixed_letter, o2.desc)) if eval_expr_defaults: self.eval_expr_defaults() return self.options
[ "def", "parse", "(", "self", ",", "eval_expr_defaults", "=", "False", ")", ":", "short_opt_str", "=", "''", ".", "join", "(", "[", "\"%s:\"", "%", "self", ".", "options", "[", "name", "]", ".", "letter", "for", "name", "in", "self", ".", "options", "...
https://github.com/kristjankorjus/Replicating-DeepMind/blob/68539394e792b34a4d6b430a2eb73b8b8f91d8db/libraries/cuda-convnet2/python_util/options.py#L123-L149
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/util.py
python
dict_fold
(dict_, func, init_value, use_keys=False)
return final_value
r"""Perform a recursive fold on a nested mapping's values or keys. A fold is for a unnested mapping looks as follows. .. code-block:: python mapping = {'a': 0, 'b': 1, 'c': 2} accumulated_value = 0 func = lambda x, y: x + y for value in mapping.values(): accumulated_value = func(accumulated_value, value) Args: dict\_ (dict): The nested mapping to perform the map on. func (callable): A callable taking in one value use to fold over dictionary values or keys if ``use_keys`` is set. init_value: An initial value to use for the fold. use_keys (bool, optional): If true use keys instead of values for the fold. Defaults to ``False``. Returns: The final value of the fold.
r"""Perform a recursive fold on a nested mapping's values or keys.
[ "r", "Perform", "a", "recursive", "fold", "on", "a", "nested", "mapping", "s", "values", "or", "keys", "." ]
def dict_fold(dict_, func, init_value, use_keys=False): r"""Perform a recursive fold on a nested mapping's values or keys. A fold is for a unnested mapping looks as follows. .. code-block:: python mapping = {'a': 0, 'b': 1, 'c': 2} accumulated_value = 0 func = lambda x, y: x + y for value in mapping.values(): accumulated_value = func(accumulated_value, value) Args: dict\_ (dict): The nested mapping to perform the map on. func (callable): A callable taking in one value use to fold over dictionary values or keys if ``use_keys`` is set. init_value: An initial value to use for the fold. use_keys (bool, optional): If true use keys instead of values for the fold. Defaults to ``False``. Returns: The final value of the fold. """ final_value = init_value for key, value in dict_.items(): if isinstance(value, dict): final_value = dict_fold(value, func, final_value) else: if use_keys: final_value = func(key, final_value) else: final_value = func(value, final_value) return final_value
[ "def", "dict_fold", "(", "dict_", ",", "func", ",", "init_value", ",", "use_keys", "=", "False", ")", ":", "final_value", "=", "init_value", "for", "key", ",", "value", "in", "dict_", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", ...
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/util.py#L56-L89
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
CondCore/Utilities/python/CondDBFW/querying.py
python
connection._cms_oracle_string
(user, pwd, db_name)
return 'oracle://%s:%s@%s' % (user, pwd, db_name)
Get database string for oracle.
Get database string for oracle.
[ "Get", "database", "string", "for", "oracle", "." ]
def _cms_oracle_string(user, pwd, db_name): """ Get database string for oracle. """ return 'oracle://%s:%s@%s' % (user, pwd, db_name)
[ "def", "_cms_oracle_string", "(", "user", ",", "pwd", ",", "db_name", ")", ":", "return", "'oracle://%s:%s@%s'", "%", "(", "user", ",", "pwd", ",", "db_name", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/CondCore/Utilities/python/CondDBFW/querying.py#L134-L138
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
third_party/closure_linter/closure_linter/statetracker.py
python
DocComment.AddFlag
(self, flag)
Add a new document flag. Args: flag: DocFlag object.
Add a new document flag.
[ "Add", "a", "new", "document", "flag", "." ]
def AddFlag(self, flag): """Add a new document flag. Args: flag: DocFlag object. """ self.__flags[flag.flag_type] = flag
[ "def", "AddFlag", "(", "self", ",", "flag", ")", ":", "self", ".", "__flags", "[", "flag", ".", "flag_type", "]", "=", "flag" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/third_party/closure_linter/closure_linter/statetracker.py#L283-L289
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/genericmessagedialog.py
python
GenericMessageDialog.SetMessage
(self, message)
Sets the message shown by the dialog. :param `message`: a string representing the main :class:`GenericMessageDialog` message. .. versionadded:: 0.9.3
Sets the message shown by the dialog.
[ "Sets", "the", "message", "shown", "by", "the", "dialog", "." ]
def SetMessage(self, message): """ Sets the message shown by the dialog. :param `message`: a string representing the main :class:`GenericMessageDialog` message. .. versionadded:: 0.9.3 """ self._message = message
[ "def", "SetMessage", "(", "self", ",", "message", ")", ":", "self", ".", "_message", "=", "message" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/genericmessagedialog.py#L1514-L1523
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/sets.py
python
BaseSet.__init__
(self)
This is an abstract class.
This is an abstract class.
[ "This", "is", "an", "abstract", "class", "." ]
def __init__(self): """This is an abstract class.""" # Don't call this from a concrete subclass! if self.__class__ is BaseSet: raise TypeError, ("BaseSet is an abstract class. " "Use Set or ImmutableSet.")
[ "def", "__init__", "(", "self", ")", ":", "# Don't call this from a concrete subclass!", "if", "self", ".", "__class__", "is", "BaseSet", ":", "raise", "TypeError", ",", "(", "\"BaseSet is an abstract class. \"", "\"Use Set or ImmutableSet.\"", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/sets.py#L72-L77
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
PhysicsTools/Heppy/python/physicsobjects/Lepton.py
python
Lepton.ip3D
(self)
return abs(self.dB(self.PV3D))
3D impact parameter value.
3D impact parameter value.
[ "3D", "impact", "parameter", "value", "." ]
def ip3D(self): '''3D impact parameter value.''' return abs(self.dB(self.PV3D))
[ "def", "ip3D", "(", "self", ")", ":", "return", "abs", "(", "self", ".", "dB", "(", "self", ".", "PV3D", ")", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/PhysicsTools/Heppy/python/physicsobjects/Lepton.py#L5-L7
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/__init__.py
python
extract_extension_options
(field_list, options_spec)
return option_dict
Return a dictionary mapping extension option names to converted values. :Parameters: - `field_list`: A flat field list without field arguments, where each field body consists of a single paragraph only. - `options_spec`: Dictionary mapping known option names to a conversion function such as `int` or `float`. :Exceptions: - `KeyError` for unknown option names. - `ValueError` for invalid option values (raised by the conversion function). - `TypeError` for invalid option value types (raised by conversion function). - `DuplicateOptionError` for duplicate options. - `BadOptionError` for invalid fields. - `BadOptionDataError` for invalid option data (missing name, missing data, bad quotes, etc.).
Return a dictionary mapping extension option names to converted values.
[ "Return", "a", "dictionary", "mapping", "extension", "option", "names", "to", "converted", "values", "." ]
def extract_extension_options(field_list, options_spec): """ Return a dictionary mapping extension option names to converted values. :Parameters: - `field_list`: A flat field list without field arguments, where each field body consists of a single paragraph only. - `options_spec`: Dictionary mapping known option names to a conversion function such as `int` or `float`. :Exceptions: - `KeyError` for unknown option names. - `ValueError` for invalid option values (raised by the conversion function). - `TypeError` for invalid option value types (raised by conversion function). - `DuplicateOptionError` for duplicate options. - `BadOptionError` for invalid fields. - `BadOptionDataError` for invalid option data (missing name, missing data, bad quotes, etc.). """ option_list = extract_options(field_list) option_dict = assemble_option_dict(option_list, options_spec) return option_dict
[ "def", "extract_extension_options", "(", "field_list", ",", "options_spec", ")", ":", "option_list", "=", "extract_options", "(", "field_list", ")", "option_dict", "=", "assemble_option_dict", "(", "option_list", ",", "options_spec", ")", "return", "option_dict" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/__init__.py#L245-L268
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/tools/grit/grit/gather/skeleton_gatherer.py
python
SkeletonGatherer.UnEscape
(self, text)
return text
Subclasses can override. Base impl is identity.
Subclasses can override. Base impl is identity.
[ "Subclasses", "can", "override", ".", "Base", "impl", "is", "identity", "." ]
def UnEscape(self, text): '''Subclasses can override. Base impl is identity. ''' return text
[ "def", "UnEscape", "(", "self", ",", "text", ")", ":", "return", "text" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/tools/grit/grit/gather/skeleton_gatherer.py#L54-L57
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/backend.py
python
softmax
(x, axis=-1)
return nn.softmax(x, axis=axis)
Softmax of a tensor. Args: x: A tensor or variable. axis: The dimension softmax would be performed on. The default is -1 which indicates the last dimension. Returns: A tensor.
Softmax of a tensor.
[ "Softmax", "of", "a", "tensor", "." ]
def softmax(x, axis=-1): """Softmax of a tensor. Args: x: A tensor or variable. axis: The dimension softmax would be performed on. The default is -1 which indicates the last dimension. Returns: A tensor. """ return nn.softmax(x, axis=axis)
[ "def", "softmax", "(", "x", ",", "axis", "=", "-", "1", ")", ":", "return", "nn", ".", "softmax", "(", "x", ",", "axis", "=", "axis", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L4783-L4794
facebook/wangle
2e7e3fbb3a15c4986d6fe0e36c31daeeba614ce3
build/fbcode_builder/getdeps/subcmd.py
python
cmd
(name, help=None, cmd_table=CmdTable)
return wrapper
@cmd() is a decorator that can be used to help define Subcmd instances Example usage: @subcmd('list', 'Show the result list') class ListCmd(Subcmd): def run(self, args): # Perform the command actions here... pass
@cmd() is a decorator that can be used to help define Subcmd instances
[ "@cmd", "()", "is", "a", "decorator", "that", "can", "be", "used", "to", "help", "define", "Subcmd", "instances" ]
def cmd(name, help=None, cmd_table=CmdTable): """ @cmd() is a decorator that can be used to help define Subcmd instances Example usage: @subcmd('list', 'Show the result list') class ListCmd(Subcmd): def run(self, args): # Perform the command actions here... pass """ def wrapper(cls): class SubclassedCmd(cls): NAME = name HELP = help cmd_table.append(SubclassedCmd) return SubclassedCmd return wrapper
[ "def", "cmd", "(", "name", ",", "help", "=", "None", ",", "cmd_table", "=", "CmdTable", ")", ":", "def", "wrapper", "(", "cls", ")", ":", "class", "SubclassedCmd", "(", "cls", ")", ":", "NAME", "=", "name", "HELP", "=", "help", "cmd_table", ".", "a...
https://github.com/facebook/wangle/blob/2e7e3fbb3a15c4986d6fe0e36c31daeeba614ce3/build/fbcode_builder/getdeps/subcmd.py#L35-L56
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/optimize/optimize.py
python
show_options
(solver=None, method=None, disp=True)
Show documentation for additional options of optimization solvers. These are method-specific options that can be supplied through the ``options`` dict. Parameters ---------- solver : str Type of optimization solver. One of 'minimize', 'minimize_scalar', 'root', or 'linprog'. method : str, optional If not given, shows all methods of the specified solver. Otherwise, show only the options for the specified method. Valid values corresponds to methods' names of respective solver (e.g. 'BFGS' for 'minimize'). disp : bool, optional Whether to print the result rather than returning it. Returns ------- text Either None (for disp=False) or the text string (disp=True) Notes ----- The solver-specific methods are: `scipy.optimize.minimize` - :ref:`Nelder-Mead <optimize.minimize-neldermead>` - :ref:`Powell <optimize.minimize-powell>` - :ref:`CG <optimize.minimize-cg>` - :ref:`BFGS <optimize.minimize-bfgs>` - :ref:`Newton-CG <optimize.minimize-newtoncg>` - :ref:`L-BFGS-B <optimize.minimize-lbfgsb>` - :ref:`TNC <optimize.minimize-tnc>` - :ref:`COBYLA <optimize.minimize-cobyla>` - :ref:`SLSQP <optimize.minimize-slsqp>` - :ref:`dogleg <optimize.minimize-dogleg>` - :ref:`trust-ncg <optimize.minimize-trustncg>` `scipy.optimize.root` - :ref:`hybr <optimize.root-hybr>` - :ref:`lm <optimize.root-lm>` - :ref:`broyden1 <optimize.root-broyden1>` - :ref:`broyden2 <optimize.root-broyden2>` - :ref:`anderson <optimize.root-anderson>` - :ref:`linearmixing <optimize.root-linearmixing>` - :ref:`diagbroyden <optimize.root-diagbroyden>` - :ref:`excitingmixing <optimize.root-excitingmixing>` - :ref:`krylov <optimize.root-krylov>` - :ref:`df-sane <optimize.root-dfsane>` `scipy.optimize.minimize_scalar` - :ref:`brent <optimize.minimize_scalar-brent>` - :ref:`golden <optimize.minimize_scalar-golden>` - :ref:`bounded <optimize.minimize_scalar-bounded>` `scipy.optimize.linprog` - :ref:`simplex <optimize.linprog-simplex>` - :ref:`interior-point <optimize.linprog-interior-point>`
Show documentation for additional options of optimization solvers.
[ "Show", "documentation", "for", "additional", "options", "of", "optimization", "solvers", "." ]
def show_options(solver=None, method=None, disp=True): """ Show documentation for additional options of optimization solvers. These are method-specific options that can be supplied through the ``options`` dict. Parameters ---------- solver : str Type of optimization solver. One of 'minimize', 'minimize_scalar', 'root', or 'linprog'. method : str, optional If not given, shows all methods of the specified solver. Otherwise, show only the options for the specified method. Valid values corresponds to methods' names of respective solver (e.g. 'BFGS' for 'minimize'). disp : bool, optional Whether to print the result rather than returning it. Returns ------- text Either None (for disp=False) or the text string (disp=True) Notes ----- The solver-specific methods are: `scipy.optimize.minimize` - :ref:`Nelder-Mead <optimize.minimize-neldermead>` - :ref:`Powell <optimize.minimize-powell>` - :ref:`CG <optimize.minimize-cg>` - :ref:`BFGS <optimize.minimize-bfgs>` - :ref:`Newton-CG <optimize.minimize-newtoncg>` - :ref:`L-BFGS-B <optimize.minimize-lbfgsb>` - :ref:`TNC <optimize.minimize-tnc>` - :ref:`COBYLA <optimize.minimize-cobyla>` - :ref:`SLSQP <optimize.minimize-slsqp>` - :ref:`dogleg <optimize.minimize-dogleg>` - :ref:`trust-ncg <optimize.minimize-trustncg>` `scipy.optimize.root` - :ref:`hybr <optimize.root-hybr>` - :ref:`lm <optimize.root-lm>` - :ref:`broyden1 <optimize.root-broyden1>` - :ref:`broyden2 <optimize.root-broyden2>` - :ref:`anderson <optimize.root-anderson>` - :ref:`linearmixing <optimize.root-linearmixing>` - :ref:`diagbroyden <optimize.root-diagbroyden>` - :ref:`excitingmixing <optimize.root-excitingmixing>` - :ref:`krylov <optimize.root-krylov>` - :ref:`df-sane <optimize.root-dfsane>` `scipy.optimize.minimize_scalar` - :ref:`brent <optimize.minimize_scalar-brent>` - :ref:`golden <optimize.minimize_scalar-golden>` - :ref:`bounded <optimize.minimize_scalar-bounded>` `scipy.optimize.linprog` - :ref:`simplex <optimize.linprog-simplex>` - :ref:`interior-point <optimize.linprog-interior-point>` """ import textwrap doc_routines = { 'minimize': ( ('bfgs', 'scipy.optimize.optimize._minimize_bfgs'), ('cg', 'scipy.optimize.optimize._minimize_cg'), ('cobyla', 'scipy.optimize.cobyla._minimize_cobyla'), ('dogleg', 'scipy.optimize._trustregion_dogleg._minimize_dogleg'), ('l-bfgs-b', 'scipy.optimize.lbfgsb._minimize_lbfgsb'), ('nelder-mead', 'scipy.optimize.optimize._minimize_neldermead'), ('newton-cg', 'scipy.optimize.optimize._minimize_newtoncg'), ('powell', 'scipy.optimize.optimize._minimize_powell'), ('slsqp', 'scipy.optimize.slsqp._minimize_slsqp'), ('tnc', 'scipy.optimize.tnc._minimize_tnc'), ('trust-ncg', 'scipy.optimize._trustregion_ncg._minimize_trust_ncg'), ), 'root': ( ('hybr', 'scipy.optimize.minpack._root_hybr'), ('lm', 'scipy.optimize._root._root_leastsq'), ('broyden1', 'scipy.optimize._root._root_broyden1_doc'), ('broyden2', 'scipy.optimize._root._root_broyden2_doc'), ('anderson', 'scipy.optimize._root._root_anderson_doc'), ('diagbroyden', 'scipy.optimize._root._root_diagbroyden_doc'), ('excitingmixing', 'scipy.optimize._root._root_excitingmixing_doc'), ('linearmixing', 'scipy.optimize._root._root_linearmixing_doc'), ('krylov', 'scipy.optimize._root._root_krylov_doc'), ('df-sane', 'scipy.optimize._spectral._root_df_sane'), ), 'root_scalar': ( ('bisect', 'scipy.optimize._root_scalar._root_scalar_bisect_doc'), ('brentq', 'scipy.optimize._root_scalar._root_scalar_brentq_doc'), ('brenth', 'scipy.optimize._root_scalar._root_scalar_brenth_doc'), ('ridder', 'scipy.optimize._root_scalar._root_scalar_ridder_doc'), ('toms748', 'scipy.optimize._root_scalar._root_scalar_toms748_doc'), ('secant', 'scipy.optimize._root_scalar._root_scalar_secant_doc'), ('newton', 'scipy.optimize._root_scalar._root_scalar_newton_doc'), ('halley', 'scipy.optimize._root_scalar._root_scalar_halley_doc'), ), 'linprog': ( ('simplex', 'scipy.optimize._linprog._linprog_simplex'), ('interior-point', 'scipy.optimize._linprog._linprog_ip'), ), 'minimize_scalar': ( ('brent', 'scipy.optimize.optimize._minimize_scalar_brent'), ('bounded', 'scipy.optimize.optimize._minimize_scalar_bounded'), ('golden', 'scipy.optimize.optimize._minimize_scalar_golden'), ), } if solver is None: text = ["\n\n\n========\n", "minimize\n", "========\n"] text.append(show_options('minimize', disp=False)) text.extend(["\n\n===============\n", "minimize_scalar\n", "===============\n"]) text.append(show_options('minimize_scalar', disp=False)) text.extend(["\n\n\n====\n", "root\n", "====\n"]) text.append(show_options('root', disp=False)) text.extend(['\n\n\n=======\n', 'linprog\n', '=======\n']) text.append(show_options('linprog', disp=False)) text = "".join(text) else: solver = solver.lower() if solver not in doc_routines: raise ValueError('Unknown solver %r' % (solver,)) if method is None: text = [] for name, _ in doc_routines[solver]: text.extend(["\n\n" + name, "\n" + "="*len(name) + "\n\n"]) text.append(show_options(solver, name, disp=False)) text = "".join(text) else: method = method.lower() methods = dict(doc_routines[solver]) if method not in methods: raise ValueError("Unknown method %r" % (method,)) name = methods[method] # Import function object parts = name.split('.') mod_name = ".".join(parts[:-1]) __import__(mod_name) obj = getattr(sys.modules[mod_name], parts[-1]) # Get doc doc = obj.__doc__ if doc is not None: text = textwrap.dedent(doc).strip() else: text = "" if disp: print(text) return else: return text
[ "def", "show_options", "(", "solver", "=", "None", ",", "method", "=", "None", ",", "disp", "=", "True", ")", ":", "import", "textwrap", "doc_routines", "=", "{", "'minimize'", ":", "(", "(", "'bfgs'", ",", "'scipy.optimize.optimize._minimize_bfgs'", ")", ",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/optimize/optimize.py#L2890-L3055
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Misc.__winfo_getint
(self, x)
return int(x, 0)
Internal function.
Internal function.
[ "Internal", "function", "." ]
def __winfo_getint(self, x): """Internal function.""" return int(x, 0)
[ "def", "__winfo_getint", "(", "self", ",", "x", ")", ":", "return", "int", "(", "x", ",", "0", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L921-L923
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py
python
load_entry_point
(dist, group, name)
return get_distribution(dist).load_entry_point(group, name)
Return `name` entry point of `group` for `dist` or raise ImportError
Return `name` entry point of `group` for `dist` or raise ImportError
[ "Return", "name", "entry", "point", "of", "group", "for", "dist", "or", "raise", "ImportError" ]
def load_entry_point(dist, group, name): """Return `name` entry point of `group` for `dist` or raise ImportError""" return get_distribution(dist).load_entry_point(group, name)
[ "def", "load_entry_point", "(", "dist", ",", "group", ",", "name", ")", ":", "return", "get_distribution", "(", "dist", ")", ".", "load_entry_point", "(", "group", ",", "name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L488-L490
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
SpinDoubleEvent.__init__
(self, *args, **kwargs)
__init__(self, EventType commandType=wxEVT_NULL, int winid=0, double value=0) -> SpinDoubleEvent
__init__(self, EventType commandType=wxEVT_NULL, int winid=0, double value=0) -> SpinDoubleEvent
[ "__init__", "(", "self", "EventType", "commandType", "=", "wxEVT_NULL", "int", "winid", "=", "0", "double", "value", "=", "0", ")", "-", ">", "SpinDoubleEvent" ]
def __init__(self, *args, **kwargs): """__init__(self, EventType commandType=wxEVT_NULL, int winid=0, double value=0) -> SpinDoubleEvent""" _controls_.SpinDoubleEvent_swiginit(self,_controls_.new_SpinDoubleEvent(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_controls_", ".", "SpinDoubleEvent_swiginit", "(", "self", ",", "_controls_", ".", "new_SpinDoubleEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L2549-L2551
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
cpp/build-support/cpplint.py
python
FilesBelongToSameModule
(filename_cc, filename_h)
return files_belong_to_same_module, common_path
Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the source (e.g. .cc) file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file.
Check if these two filenames belong to the same module.
[ "Check", "if", "these", "two", "filenames", "belong", "to", "the", "same", "module", "." ]
def FilesBelongToSameModule(filename_cc, filename_h): """Check if these two filenames belong to the same module. The concept of a 'module' here is a as follows: foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the same 'module' if they are in the same directory. some/path/public/xyzzy and some/path/internal/xyzzy are also considered to belong to the same module here. If the filename_cc contains a longer path than the filename_h, for example, '/absolute/path/to/base/sysinfo.cc', and this file would include 'base/sysinfo.h', this function also produces the prefix needed to open the header. This is used by the caller of this function to more robustly open the header file. We don't have access to the real include paths in this context, so we need this guesswork here. Known bugs: tools/base/bar.cc and base/bar.h belong to the same module according to this implementation. Because of this, this function gives some false positives. This should be sufficiently rare in practice. Args: filename_cc: is the path for the source (e.g. .cc) file filename_h: is the path for the header path Returns: Tuple with a bool and a string: bool: True if filename_cc and filename_h belong to the same module. string: the additional prefix needed to open the header file. """ fileinfo_cc = FileInfo(filename_cc) if not fileinfo_cc.Extension().lstrip('.') in GetNonHeaderExtensions(): return (False, '') fileinfo_h = FileInfo(filename_h) if not fileinfo_h.Extension().lstrip('.') in GetHeaderExtensions(): return (False, '') filename_cc = filename_cc[:-(len(fileinfo_cc.Extension()))] matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo_cc.BaseName()) if matched_test_suffix: filename_cc = filename_cc[:-len(matched_test_suffix.group(1))] filename_cc = filename_cc.replace('/public/', '/') filename_cc = filename_cc.replace('/internal/', '/') filename_h = filename_h[:-(len(fileinfo_h.Extension()))] if filename_h.endswith('-inl'): filename_h = filename_h[:-len('-inl')] filename_h = filename_h.replace('/public/', '/') filename_h = filename_h.replace('/internal/', '/') files_belong_to_same_module = filename_cc.endswith(filename_h) common_path = '' if files_belong_to_same_module: common_path = filename_cc[:-len(filename_h)] return files_belong_to_same_module, common_path
[ "def", "FilesBelongToSameModule", "(", "filename_cc", ",", "filename_h", ")", ":", "fileinfo_cc", "=", "FileInfo", "(", "filename_cc", ")", "if", "not", "fileinfo_cc", ".", "Extension", "(", ")", ".", "lstrip", "(", "'.'", ")", "in", "GetNonHeaderExtensions", ...
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/cpp/build-support/cpplint.py#L5573-L5628
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py
python
replaceWith
(replStr)
return lambda s,l,t: [replStr]
Helper method for common parse actions that simply return a literal value. Especially useful when used with C{L{transformString<ParserElement.transformString>}()}. Example:: num = Word(nums).setParseAction(lambda toks: int(toks[0])) na = oneOf("N/A NA").setParseAction(replaceWith(math.nan)) term = na | num OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234]
Helper method for common parse actions that simply return a literal value. Especially useful when used with C{L{transformString<ParserElement.transformString>}()}.
[ "Helper", "method", "for", "common", "parse", "actions", "that", "simply", "return", "a", "literal", "value", ".", "Especially", "useful", "when", "used", "with", "C", "{", "L", "{", "transformString<ParserElement", ".", "transformString", ">", "}", "()", "}",...
def replaceWith(replStr): """ Helper method for common parse actions that simply return a literal value. Especially useful when used with C{L{transformString<ParserElement.transformString>}()}. Example:: num = Word(nums).setParseAction(lambda toks: int(toks[0])) na = oneOf("N/A NA").setParseAction(replaceWith(math.nan)) term = na | num OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234] """ return lambda s,l,t: [replStr]
[ "def", "replaceWith", "(", "replStr", ")", ":", "return", "lambda", "s", ",", "l", ",", "t", ":", "[", "replStr", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py#L4797-L4809
ycm-core/ycmd
fc0fb7e5e15176cc5a2a30c80956335988c6b59a
ycmd/extra_conf_store.py
python
Disable
( module_file )
Disables the loading of a module for the current session.
Disables the loading of a module for the current session.
[ "Disables", "the", "loading", "of", "a", "module", "for", "the", "current", "session", "." ]
def Disable( module_file ): """Disables the loading of a module for the current session.""" with _module_for_module_file_lock: _module_for_module_file[ module_file ] = None
[ "def", "Disable", "(", "module_file", ")", ":", "with", "_module_for_module_file_lock", ":", "_module_for_module_file", "[", "module_file", "]", "=", "None" ]
https://github.com/ycm-core/ycmd/blob/fc0fb7e5e15176cc5a2a30c80956335988c6b59a/ycmd/extra_conf_store.py#L114-L117
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/io.py
python
BufferedIOBase.write
(self, b)
Write the given buffer to the IO stream. Return the number of bytes written, which is never less than len(b). Raises BlockingIOError if the buffer is full and the underlying raw stream cannot accept more data at the moment.
Write the given buffer to the IO stream.
[ "Write", "the", "given", "buffer", "to", "the", "IO", "stream", "." ]
def write(self, b): """Write the given buffer to the IO stream. Return the number of bytes written, which is never less than len(b). Raises BlockingIOError if the buffer is full and the underlying raw stream cannot accept more data at the moment. """ self._unsupported("write")
[ "def", "write", "(", "self", ",", "b", ")", ":", "self", ".", "_unsupported", "(", "\"write\"", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/io.py#L703-L712
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/MiniAEFrame.py
python
code
(x)
return s
Convert a long int to the 4-character code it really is
Convert a long int to the 4-character code it really is
[ "Convert", "a", "long", "int", "to", "the", "4", "-", "character", "code", "it", "really", "is" ]
def code(x): "Convert a long int to the 4-character code it really is" s = '' for i in range(4): x, c = divmod(x, 256) s = chr(c) + s return s
[ "def", "code", "(", "x", ")", ":", "s", "=", "''", "for", "i", "in", "range", "(", "4", ")", ":", "x", ",", "c", "=", "divmod", "(", "x", ",", "256", ")", "s", "=", "chr", "(", "c", ")", "+", "s", "return", "s" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/plat-mac/MiniAEFrame.py#L170-L176
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_model.py
python
BasicFittingModel._reset_start_xs
(self)
Resets the start Xs stored by the context.
Resets the start Xs stored by the context.
[ "Resets", "the", "start", "Xs", "stored", "by", "the", "context", "." ]
def _reset_start_xs(self) -> None: """Resets the start Xs stored by the context.""" if self.fitting_context.number_of_datasets > 0: self.fitting_context.start_xs = [self.retrieve_first_good_data_from(name) for name in self.fitting_context.dataset_names] else: self.fitting_context.start_xs = []
[ "def", "_reset_start_xs", "(", "self", ")", "->", "None", ":", "if", "self", ".", "fitting_context", ".", "number_of_datasets", ">", "0", ":", "self", ".", "fitting_context", ".", "start_xs", "=", "[", "self", ".", "retrieve_first_good_data_from", "(", "name",...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/Muon/GUI/Common/fitting_widgets/basic_fitting/basic_fitting_model.py#L535-L541
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/Devices/EFI/Firmware/AppPkg/Applications/Python/PyMod-2.7.2/Lib/ntpath.py
python
normpath
(path)
return prefix + backslash.join(comps)
Normalize path, eliminating double slashes, etc.
Normalize path, eliminating double slashes, etc.
[ "Normalize", "path", "eliminating", "double", "slashes", "etc", "." ]
def normpath(path): """Normalize path, eliminating double slashes, etc.""" # Preserve unicode (if path is unicode) backslash, dot = (u'\\', u'.') if isinstance(path, unicode) else ('\\', '.') if path.startswith(('\\\\.\\', '\\\\?\\')): # in the case of paths with these prefixes: # \\.\ -> device names # \\?\ -> literal paths # do not do any normalization, but return the path unchanged return path path = path.replace("/", "\\") prefix, path = splitdrive(path) # We need to be careful here. If the prefix is empty, and the path starts # with a backslash, it could either be an absolute path on the current # drive (\dir1\dir2\file) or a UNC filename (\\server\mount\dir1\file). It # is therefore imperative NOT to collapse multiple backslashes blindly in # that case. # The code below preserves multiple backslashes when there is no drive # letter. This means that the invalid filename \\\a\b is preserved # unchanged, where a\\\b is normalised to a\b. It's not clear that there # is any better behaviour for such edge cases. if prefix == '': # No drive letter - preserve initial backslashes while path[:1] == "\\": prefix = prefix + backslash path = path[1:] else: # We have a drive letter - collapse initial backslashes if path.startswith("\\"): prefix = prefix + backslash path = path.lstrip("\\") comps = path.split("\\") i = 0 while i < len(comps): if comps[i] in ('.', ''): del comps[i] elif comps[i] == '..': if i > 0 and comps[i-1] != '..': del comps[i-1:i+1] i -= 1 elif i == 0 and prefix.endswith("\\"): del comps[i] else: i += 1 else: i += 1 # If the path is now empty, substitute '.' if not prefix and not comps: comps.append(dot) return prefix + backslash.join(comps)
[ "def", "normpath", "(", "path", ")", ":", "# Preserve unicode (if path is unicode)", "backslash", ",", "dot", "=", "(", "u'\\\\'", ",", "u'.'", ")", "if", "isinstance", "(", "path", ",", "unicode", ")", "else", "(", "'\\\\'", ",", "'.'", ")", "if", "path",...
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/Devices/EFI/Firmware/AppPkg/Applications/Python/PyMod-2.7.2/Lib/ntpath.py#L403-L452
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py
python
_parse_format_specifier
(format_spec, _localeconv=None)
return format_dict
Parse and validate a format specifier. Turns a standard numeric format specifier into a dict, with the following entries: fill: fill character to pad field to minimum width align: alignment type, either '<', '>', '=' or '^' sign: either '+', '-' or ' ' minimumwidth: nonnegative integer giving minimum width zeropad: boolean, indicating whether to pad with zeros thousands_sep: string to use as thousands separator, or '' grouping: grouping for thousands separators, in format used by localeconv decimal_point: string to use for decimal point precision: nonnegative integer giving precision, or None type: one of the characters 'eEfFgG%', or None unicode: boolean (always True for Python 3.x)
Parse and validate a format specifier.
[ "Parse", "and", "validate", "a", "format", "specifier", "." ]
def _parse_format_specifier(format_spec, _localeconv=None): """Parse and validate a format specifier. Turns a standard numeric format specifier into a dict, with the following entries: fill: fill character to pad field to minimum width align: alignment type, either '<', '>', '=' or '^' sign: either '+', '-' or ' ' minimumwidth: nonnegative integer giving minimum width zeropad: boolean, indicating whether to pad with zeros thousands_sep: string to use as thousands separator, or '' grouping: grouping for thousands separators, in format used by localeconv decimal_point: string to use for decimal point precision: nonnegative integer giving precision, or None type: one of the characters 'eEfFgG%', or None unicode: boolean (always True for Python 3.x) """ m = _parse_format_specifier_regex.match(format_spec) if m is None: raise ValueError("Invalid format specifier: " + format_spec) # get the dictionary format_dict = m.groupdict() # zeropad; defaults for fill and alignment. If zero padding # is requested, the fill and align fields should be absent. fill = format_dict['fill'] align = format_dict['align'] format_dict['zeropad'] = (format_dict['zeropad'] is not None) if format_dict['zeropad']: if fill is not None: raise ValueError("Fill character conflicts with '0'" " in format specifier: " + format_spec) if align is not None: raise ValueError("Alignment conflicts with '0' in " "format specifier: " + format_spec) format_dict['fill'] = fill or ' ' # PEP 3101 originally specified that the default alignment should # be left; it was later agreed that right-aligned makes more sense # for numeric types. See http://bugs.python.org/issue6857. format_dict['align'] = align or '>' # default sign handling: '-' for negative, '' for positive if format_dict['sign'] is None: format_dict['sign'] = '-' # minimumwidth defaults to 0; precision remains None if not given format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0') if format_dict['precision'] is not None: format_dict['precision'] = int(format_dict['precision']) # if format type is 'g' or 'G' then a precision of 0 makes little # sense; convert it to 1. Same if format type is unspecified. if format_dict['precision'] == 0: if format_dict['type'] is None or format_dict['type'] in 'gG': format_dict['precision'] = 1 # determine thousands separator, grouping, and decimal separator, and # add appropriate entries to format_dict if format_dict['type'] == 'n': # apart from separators, 'n' behaves just like 'g' format_dict['type'] = 'g' if _localeconv is None: _localeconv = _locale.localeconv() if format_dict['thousands_sep'] is not None: raise ValueError("Explicit thousands separator conflicts with " "'n' type in format specifier: " + format_spec) format_dict['thousands_sep'] = _localeconv['thousands_sep'] format_dict['grouping'] = _localeconv['grouping'] format_dict['decimal_point'] = _localeconv['decimal_point'] else: if format_dict['thousands_sep'] is None: format_dict['thousands_sep'] = '' format_dict['grouping'] = [3, 0] format_dict['decimal_point'] = '.' # record whether return type should be str or unicode format_dict['unicode'] = isinstance(format_spec, unicode) return format_dict
[ "def", "_parse_format_specifier", "(", "format_spec", ",", "_localeconv", "=", "None", ")", ":", "m", "=", "_parse_format_specifier_regex", ".", "match", "(", "format_spec", ")", "if", "m", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid format specifier...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/decimal.py#L5956-L6038
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/image_grad.py
python
_ResizeBicubicGrad
(op, grad)
return [grad0, None]
The derivatives for bicubic resizing. Args: op: The ResizeBicubic op. grad: The tensor representing the gradient w.r.t. the output. Returns: The gradients w.r.t. the input.
The derivatives for bicubic resizing.
[ "The", "derivatives", "for", "bicubic", "resizing", "." ]
def _ResizeBicubicGrad(op, grad): """The derivatives for bicubic resizing. Args: op: The ResizeBicubic op. grad: The tensor representing the gradient w.r.t. the output. Returns: The gradients w.r.t. the input. """ allowed_types = [dtypes.float32, dtypes.float64] grad0 = None if op.inputs[0].dtype in allowed_types: grad0 = gen_image_ops.resize_bicubic_grad( grad, op.inputs[0], align_corners=op.get_attr("align_corners"), half_pixel_centers=op.get_attr("half_pixel_centers")) return [grad0, None]
[ "def", "_ResizeBicubicGrad", "(", "op", ",", "grad", ")", ":", "allowed_types", "=", "[", "dtypes", ".", "float32", ",", "dtypes", ".", "float64", "]", "grad0", "=", "None", "if", "op", ".", "inputs", "[", "0", "]", ".", "dtype", "in", "allowed_types",...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/image_grad.py#L91-L109
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/learn/python/learn/datasets/base.py
python
load_boston
(data_path=None)
return load_csv_with_header( data_path, target_dtype=np.float, features_dtype=np.float)
Load Boston housing dataset. Args: data_path: string, path to boston dataset (optional) Returns: Dataset object containing data in-memory.
Load Boston housing dataset.
[ "Load", "Boston", "housing", "dataset", "." ]
def load_boston(data_path=None): """Load Boston housing dataset. Args: data_path: string, path to boston dataset (optional) Returns: Dataset object containing data in-memory. """ if data_path is None: module_path = path.dirname(__file__) data_path = path.join(module_path, 'data', 'boston_house_prices.csv') return load_csv_with_header( data_path, target_dtype=np.float, features_dtype=np.float)
[ "def", "load_boston", "(", "data_path", "=", "None", ")", ":", "if", "data_path", "is", "None", ":", "module_path", "=", "path", ".", "dirname", "(", "__file__", ")", "data_path", "=", "path", ".", "join", "(", "module_path", ",", "'data'", ",", "'boston...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/datasets/base.py#L108-L123
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/ply/example/classcalc/calc.py
python
Calc.p_expression_binop
(self, p)
expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression | expression EXP expression
expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression | expression EXP expression
[ "expression", ":", "expression", "PLUS", "expression", "|", "expression", "MINUS", "expression", "|", "expression", "TIMES", "expression", "|", "expression", "DIVIDE", "expression", "|", "expression", "EXP", "expression" ]
def p_expression_binop(self, p): """ expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression | expression EXP expression """ #print [repr(p[i]) for i in range(0,4)] if p[2] == '+' : p[0] = p[1] + p[3] elif p[2] == '-': p[0] = p[1] - p[3] elif p[2] == '*': p[0] = p[1] * p[3] elif p[2] == '/': p[0] = p[1] / p[3] elif p[2] == '**': p[0] = p[1] ** p[3]
[ "def", "p_expression_binop", "(", "self", ",", "p", ")", ":", "#print [repr(p[i]) for i in range(0,4)]", "if", "p", "[", "2", "]", "==", "'+'", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "p", "[", "3", "]", "elif", "p", "[", "2", "]",...
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/classcalc/calc.py#L114-L127
freebayes/freebayes
be3ae1fa38886aa26ae419aa64d0b6565f8f4f42
python/dirichlet.py
python
beta
(alphas)
return math.exp(sum(map(gammaln, alphas)) - gammaln(sum(alphas)))
Multivariate beta function
Multivariate beta function
[ "Multivariate", "beta", "function" ]
def beta(alphas): """Multivariate beta function""" return math.exp(sum(map(gammaln, alphas)) - gammaln(sum(alphas)))
[ "def", "beta", "(", "alphas", ")", ":", "return", "math", ".", "exp", "(", "sum", "(", "map", "(", "gammaln", ",", "alphas", ")", ")", "-", "gammaln", "(", "sum", "(", "alphas", ")", ")", ")" ]
https://github.com/freebayes/freebayes/blob/be3ae1fa38886aa26ae419aa64d0b6565f8f4f42/python/dirichlet.py#L20-L22
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/generator/msvs.py
python
_GetGuidOfProject
(proj_path, spec)
return guid
Get the guid for the project. Arguments: proj_path: Path of the vcproj or vcxproj file to generate. spec: The target dictionary containing the properties of the target. Returns: the guid. Raises: ValueError: if the specified GUID is invalid.
Get the guid for the project.
[ "Get", "the", "guid", "for", "the", "project", "." ]
def _GetGuidOfProject(proj_path, spec): """Get the guid for the project. Arguments: proj_path: Path of the vcproj or vcxproj file to generate. spec: The target dictionary containing the properties of the target. Returns: the guid. Raises: ValueError: if the specified GUID is invalid. """ # Pluck out the default configuration. default_config = _GetDefaultConfiguration(spec) # Decide the guid of the project. guid = default_config.get('msvs_guid') if guid: if VALID_MSVS_GUID_CHARS.match(guid) is None: raise ValueError('Invalid MSVS guid: "%s". Must match regex: "%s".' % (guid, VALID_MSVS_GUID_CHARS.pattern)) guid = '{%s}' % guid guid = guid or MSVSNew.MakeGuid(proj_path) return guid
[ "def", "_GetGuidOfProject", "(", "proj_path", ",", "spec", ")", ":", "# Pluck out the default configuration.", "default_config", "=", "_GetDefaultConfiguration", "(", "spec", ")", "# Decide the guid of the project.", "guid", "=", "default_config", ".", "get", "(", "'msvs_...
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/msvs.py#L862-L883
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/fusion/portableglobe/servers/portable_globe.py
python
Globe.IsGee
(self)
return self.is_gee_
Returns whether file appears to be a legal glx.
Returns whether file appears to be a legal glx.
[ "Returns", "whether", "file", "appears", "to", "be", "a", "legal", "glx", "." ]
def IsGee(self): """Returns whether file appears to be a legal glx.""" return self.is_gee_
[ "def", "IsGee", "(", "self", ")", ":", "return", "self", ".", "is_gee_" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/fusion/portableglobe/servers/portable_globe.py#L89-L91
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py
python
IsCppString
(line)
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant.
Does line terminate so, that the next symbol is in string constant.
[ "Does", "line", "terminate", "so", "that", "the", "next", "symbol", "is", "in", "string", "constant", "." ]
def IsCppString(line): """Does line terminate so, that the next symbol is in string constant. This function does not consider single-line nor multi-line comments. Args: line: is a partial line of code starting from the 0..n. Returns: True, if next character appended to 'line' is inside a string constant. """ line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
[ "def", "IsCppString", "(", "line", ")", ":", "line", "=", "line", ".", "replace", "(", "r'\\\\'", ",", "'XX'", ")", "# after this, \\\\\" does not match to \\\"", "return", "(", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/models/AI-Model-Zoo/caffe-xilinx/scripts/cpp_lint.py#L1045-L1059
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/Paste/paste/evalexception/middleware.py
python
wsgiapp
()
return decorator
Turns a function or method into a WSGI application.
Turns a function or method into a WSGI application.
[ "Turns", "a", "function", "or", "method", "into", "a", "WSGI", "application", "." ]
def wsgiapp(): """ Turns a function or method into a WSGI application. """ def decorator(func): def wsgiapp_wrapper(*args): # we get 3 args when this is a method, two when it is # a function :( if len(args) == 3: environ = args[1] start_response = args[2] args = [args[0]] else: environ, start_response = args args = [] def application(environ, start_response): form = wsgilib.parse_formvars(environ, include_get_vars=True) headers = response.HeaderDict( {'content-type': 'text/html', 'status': '200 OK'}) form['environ'] = environ form['headers'] = headers res = func(*args, **form.mixed()) status = headers.pop('status') start_response(status, headers.headeritems()) return [res] app = httpexceptions.make_middleware(application) app = simplecatcher(app) return app(environ, start_response) wsgiapp_wrapper.exposed = True return wsgiapp_wrapper return decorator
[ "def", "wsgiapp", "(", ")", ":", "def", "decorator", "(", "func", ")", ":", "def", "wsgiapp_wrapper", "(", "*", "args", ")", ":", "# we get 3 args when this is a method, two when it is", "# a function :(", "if", "len", "(", "args", ")", "==", "3", ":", "enviro...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/Paste/paste/evalexception/middleware.py#L98-L130
blchinezu/pocketbook-coolreader
d032f332ea2e392b04276d3c13ff07e98d4462f3
thirdparty/freetype/src/tools/docmaker/content.py
python
ContentProcessor.__init__
( self )
Initialize a block content processor.
Initialize a block content processor.
[ "Initialize", "a", "block", "content", "processor", "." ]
def __init__( self ): """Initialize a block content processor.""" self.reset() self.sections = {} # dictionary of documentation sections self.section = None # current documentation section self.chapters = [] # list of chapters self.headers = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "reset", "(", ")", "self", ".", "sections", "=", "{", "}", "# dictionary of documentation sections", "self", ".", "section", "=", "None", "# current documentation section", "self", ".", "chapters", "=", "[...
https://github.com/blchinezu/pocketbook-coolreader/blob/d032f332ea2e392b04276d3c13ff07e98d4462f3/thirdparty/freetype/src/tools/docmaker/content.py#L403-L412
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
third_party/ply/example/ansic/cparse.py
python
p_parameter_type_list_opt_2
(t)
parameter_type_list_opt : parameter_type_list
parameter_type_list_opt : parameter_type_list
[ "parameter_type_list_opt", ":", "parameter_type_list" ]
def p_parameter_type_list_opt_2(t): 'parameter_type_list_opt : parameter_type_list' pass
[ "def", "p_parameter_type_list_opt_2", "(", "t", ")", ":", "pass" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/third_party/ply/example/ansic/cparse.py#L447-L449
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/tools/inspector_protocol/jinja2/filters.py
python
do_reverse
(value)
Reverse the object or return an iterator that iterates over it the other way round.
Reverse the object or return an iterator that iterates over it the other way round.
[ "Reverse", "the", "object", "or", "return", "an", "iterator", "that", "iterates", "over", "it", "the", "other", "way", "round", "." ]
def do_reverse(value): """Reverse the object or return an iterator that iterates over it the other way round. """ if isinstance(value, string_types): return value[::-1] try: return reversed(value) except TypeError: try: rv = list(value) rv.reverse() return rv except TypeError: raise FilterArgumentError('argument must be iterable')
[ "def", "do_reverse", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "string_types", ")", ":", "return", "value", "[", ":", ":", "-", "1", "]", "try", ":", "return", "reversed", "(", "value", ")", "except", "TypeError", ":", "try", ":"...
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/tools/inspector_protocol/jinja2/filters.py#L895-L909
funnyzhou/Adaptive_Feeding
9c78182331d8c0ea28de47226e805776c638d46f
lib/datasets/voc_eval.py
python
voc_ap
(rec, prec, use_07_metric=False)
return ap
ap = voc_ap(rec, prec, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11 point method (default:False).
ap = voc_ap(rec, prec, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11 point method (default:False).
[ "ap", "=", "voc_ap", "(", "rec", "prec", "[", "use_07_metric", "]", ")", "Compute", "VOC", "AP", "given", "precision", "and", "recall", ".", "If", "use_07_metric", "is", "true", "uses", "the", "VOC", "07", "11", "point", "method", "(", "default", ":", ...
def voc_ap(rec, prec, use_07_metric=False): """ ap = voc_ap(rec, prec, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11 point method (default:False). """ if use_07_metric: # 11 point metric ap = 0. for t in np.arange(0., 1.1, 0.1): if np.sum(rec >= t) == 0: p = 0 else: p = np.max(prec[rec >= t]) ap = ap + p / 11. else: # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap
[ "def", "voc_ap", "(", "rec", ",", "prec", ",", "use_07_metric", "=", "False", ")", ":", "if", "use_07_metric", ":", "# 11 point metric", "ap", "=", "0.", "for", "t", "in", "np", ".", "arange", "(", "0.", ",", "1.1", ",", "0.1", ")", ":", "if", "np"...
https://github.com/funnyzhou/Adaptive_Feeding/blob/9c78182331d8c0ea28de47226e805776c638d46f/lib/datasets/voc_eval.py#L31-L62
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
DirItemData.SetNewDirName
(*args, **kwargs)
return _controls_.DirItemData_SetNewDirName(*args, **kwargs)
SetNewDirName(self, String path)
SetNewDirName(self, String path)
[ "SetNewDirName", "(", "self", "String", "path", ")" ]
def SetNewDirName(*args, **kwargs): """SetNewDirName(self, String path)""" return _controls_.DirItemData_SetNewDirName(*args, **kwargs)
[ "def", "SetNewDirName", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "DirItemData_SetNewDirName", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L5628-L5630
junhyukoh/caffe-lstm
598d45456fa2a1b127a644f4aa38daa8fb9fc722
python/caffe/net_spec.py
python
param_name_dict
()
return dict(zip(param_type_names, param_names))
Find out the correspondence between layer names and parameter names.
Find out the correspondence between layer names and parameter names.
[ "Find", "out", "the", "correspondence", "between", "layer", "names", "and", "parameter", "names", "." ]
def param_name_dict(): """Find out the correspondence between layer names and parameter names.""" layer = caffe_pb2.LayerParameter() # get all parameter names (typically underscore case) and corresponding # type names (typically camel case), which contain the layer names # (note that not all parameters correspond to layers, but we'll ignore that) param_names = [s for s in dir(layer) if s.endswith('_param')] param_type_names = [type(getattr(layer, s)).__name__ for s in param_names] # strip the final '_param' or 'Parameter' param_names = [s[:-len('_param')] for s in param_names] param_type_names = [s[:-len('Parameter')] for s in param_type_names] return dict(zip(param_type_names, param_names))
[ "def", "param_name_dict", "(", ")", ":", "layer", "=", "caffe_pb2", ".", "LayerParameter", "(", ")", "# get all parameter names (typically underscore case) and corresponding", "# type names (typically camel case), which contain the layer names", "# (note that not all parameters correspon...
https://github.com/junhyukoh/caffe-lstm/blob/598d45456fa2a1b127a644f4aa38daa8fb9fc722/python/caffe/net_spec.py#L28-L40
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
MouseEvent.GetLinesPerAction
(*args, **kwargs)
return _core_.MouseEvent_GetLinesPerAction(*args, **kwargs)
GetLinesPerAction(self) -> int Returns the configured number of lines (or whatever) to be scrolled per wheel action. Defaults to three.
GetLinesPerAction(self) -> int
[ "GetLinesPerAction", "(", "self", ")", "-", ">", "int" ]
def GetLinesPerAction(*args, **kwargs): """ GetLinesPerAction(self) -> int Returns the configured number of lines (or whatever) to be scrolled per wheel action. Defaults to three. """ return _core_.MouseEvent_GetLinesPerAction(*args, **kwargs)
[ "def", "GetLinesPerAction", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "MouseEvent_GetLinesPerAction", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L5832-L5839
sailing-pmls/bosen
06cb58902d011fbea5f9428f10ce30e621492204
style_script/cpplint.py
python
CheckSectionSpacing
(filename, clean_lines, class_info, linenum, error)
Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found.
Checks for additional blank line issues related to sections.
[ "Checks", "for", "additional", "blank", "line", "issues", "related", "to", "sections", "." ]
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): """Checks for additional blank line issues related to sections. Currently the only thing checked here is blank line before protected/private. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. class_info: A _ClassInfo objects. linenum: The number of the line to check. error: The function to call with any errors found. """ # Skip checks if the class is small, where small means 25 lines or less. # 25 lines seems like a good cutoff since that's the usual height of # terminals, and any class that can't fit in one screen can't really # be considered "small". # # Also skip checks if we are on the first line. This accounts for # classes that look like # class Foo { public: ... }; # # If we didn't find the end of the class, last_line would be zero, # and the check will be skipped by the first condition. if (class_info.last_line - class_info.starting_linenum <= 24 or linenum <= class_info.starting_linenum): return matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) if matched: # Issue warning if the line before public/protected/private was # not a blank line, but don't do this if the previous line contains # "class" or "struct". This can happen two ways: # - We are at the beginning of the class. # - We are forward-declaring an inner class that is semantically # private, but needed to be public for implementation reasons. # Also ignores cases where the previous line ends with a backslash as can be # common when defining classes in C macros. prev_line = clean_lines.lines[linenum - 1] if (not IsBlankLine(prev_line) and not Search(r'\b(class|struct)\b', prev_line) and not Search(r'\\$', prev_line)): # Try a bit harder to find the beginning of the class. This is to # account for multi-line base-specifier lists, e.g.: # class Derived # : public Base { end_class_head = class_info.starting_linenum for i in range(class_info.starting_linenum, linenum): if Search(r'\{\s*$', clean_lines.lines[i]): end_class_head = i break if end_class_head < linenum - 1: error(filename, linenum, 'whitespace/blank_line', 3, '"%s:" should be preceded by a blank line' % matched.group(1))
[ "def", "CheckSectionSpacing", "(", "filename", ",", "clean_lines", ",", "class_info", ",", "linenum", ",", "error", ")", ":", "# Skip checks if the class is small, where small means 25 lines or less.", "# 25 lines seems like a good cutoff since that's the usual height of", "# termina...
https://github.com/sailing-pmls/bosen/blob/06cb58902d011fbea5f9428f10ce30e621492204/style_script/cpplint.py#L3812-L3864
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/geodesy/utm.py
python
gridZone
(lat, lon)
return (zone, band)
Find UTM zone and MGRS band for latitude and longitude. :param lat: latitude in degrees, negative is South. :param lon: longitude in degrees, negative is West. :returns: (zone, band) tuple. :raises: :exc:`ValueError` if lon not in [-180..180] or if lat has no corresponding band letter. :todo: handle polar (UPS_) zones: A, B, Y, Z.
Find UTM zone and MGRS band for latitude and longitude.
[ "Find", "UTM", "zone", "and", "MGRS", "band", "for", "latitude", "and", "longitude", "." ]
def gridZone(lat, lon): """Find UTM zone and MGRS band for latitude and longitude. :param lat: latitude in degrees, negative is South. :param lon: longitude in degrees, negative is West. :returns: (zone, band) tuple. :raises: :exc:`ValueError` if lon not in [-180..180] or if lat has no corresponding band letter. :todo: handle polar (UPS_) zones: A, B, Y, Z. """ if -180.0 > lon or lon > 180.0: raise ValueError('invalid longitude: ' + str(lon)) zone = int((lon + 180.0)//6.0) + 1 band = ' ' if 84 >= lat and lat >= 72: band = 'X' elif 72 > lat and lat >= 64: band = 'W' elif 64 > lat and lat >= 56: band = 'V' elif 56 > lat and lat >= 48: band = 'U' elif 48 > lat and lat >= 40: band = 'T' elif 40 > lat and lat >= 32: band = 'S' elif 32 > lat and lat >= 24: band = 'R' elif 24 > lat and lat >= 16: band = 'Q' elif 16 > lat and lat >= 8: band = 'P' elif 8 > lat and lat >= 0: band = 'N' elif 0 > lat and lat >= -8: band = 'M' elif -8 > lat and lat >= -16: band = 'L' elif -16 > lat and lat >= -24: band = 'K' elif -24 > lat and lat >= -32: band = 'J' elif -32 > lat and lat >= -40: band = 'H' elif -40 > lat and lat >= -48: band = 'G' elif -48 > lat and lat >= -56: band = 'F' elif -56 > lat and lat >= -64: band = 'E' elif -64 > lat and lat >= -72: band = 'D' elif -72 > lat and lat >= -80: band = 'C' else: raise ValueError('latitude out of UTM range: ' + str(lat)) return (zone, band)
[ "def", "gridZone", "(", "lat", ",", "lon", ")", ":", "if", "-", "180.0", ">", "lon", "or", "lon", ">", "180.0", ":", "raise", "ValueError", "(", "'invalid longitude: '", "+", "str", "(", "lon", ")", ")", "zone", "=", "int", "(", "(", "lon", "+", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/geodesy/utm.py#L155-L191
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/generator/analyzer.py
python
_LookupTargets
(names, mapping)
return [mapping[name] for name in names if name in mapping]
Returns a list of the mapping[name] for each value in |names| that is in |mapping|.
Returns a list of the mapping[name] for each value in |names| that is in |mapping|.
[ "Returns", "a", "list", "of", "the", "mapping", "[", "name", "]", "for", "each", "value", "in", "|names|", "that", "is", "in", "|mapping|", "." ]
def _LookupTargets(names, mapping): """Returns a list of the mapping[name] for each value in |names| that is in |mapping|.""" return [mapping[name] for name in names if name in mapping]
[ "def", "_LookupTargets", "(", "names", ",", "mapping", ")", ":", "return", "[", "mapping", "[", "name", "]", "for", "name", "in", "names", "if", "name", "in", "mapping", "]" ]
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/generator/analyzer.py#L569-L572
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
gpu/command_buffer/build_gles2_cmd_buffer.py
python
GENnHandler.WriteGLES2ImplementationUnitTest
(self, func, file)
Overrriden from TypeHandler.
Overrriden from TypeHandler.
[ "Overrriden", "from", "TypeHandler", "." ]
def WriteGLES2ImplementationUnitTest(self, func, file): """Overrriden from TypeHandler.""" code = """ TEST_F(GLES2ImplementationTest, %(name)s) { GLuint ids[2] = { 0, }; struct Cmds { cmds::%(name)sImmediate gen; GLuint data[2]; }; Cmds expected; expected.gen.Init(arraysize(ids), &ids[0]); expected.data[0] = k%(types)sStartId; expected.data[1] = k%(types)sStartId + 1; gl_->%(name)s(arraysize(ids), &ids[0]); EXPECT_EQ(0, memcmp(&expected, commands_, sizeof(expected))); EXPECT_EQ(k%(types)sStartId, ids[0]); EXPECT_EQ(k%(types)sStartId + 1, ids[1]); } """ file.Write(code % { 'name': func.name, 'types': func.GetInfo('resource_types'), })
[ "def", "WriteGLES2ImplementationUnitTest", "(", "self", ",", "func", ",", "file", ")", ":", "code", "=", "\"\"\"\nTEST_F(GLES2ImplementationTest, %(name)s) {\n GLuint ids[2] = { 0, };\n struct Cmds {\n cmds::%(name)sImmediate gen;\n GLuint data[2];\n };\n Cmds expected;\n expected...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/gpu/command_buffer/build_gles2_cmd_buffer.py#L3966-L3988
alexozer/jankdrone
c4b403eb254b41b832ab2bdfade12ba59c99e5dc
shm/lib/nanopb/generator/nanopb_generator.py
python
ProtoFile.generate_header
(self, includes, headername, options)
Generate content for a header file. Generates strings, which should be concatenated and stored to file.
Generate content for a header file. Generates strings, which should be concatenated and stored to file.
[ "Generate", "content", "for", "a", "header", "file", ".", "Generates", "strings", "which", "should", "be", "concatenated", "and", "stored", "to", "file", "." ]
def generate_header(self, includes, headername, options): '''Generate content for a header file. Generates strings, which should be concatenated and stored to file. ''' yield '/* Automatically generated nanopb header */\n' if options.notimestamp: yield '/* Generated by %s */\n\n' % (nanopb_version) else: yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime()) if self.fdesc.package: symbol = make_identifier(self.fdesc.package + '_' + headername) else: symbol = make_identifier(headername) yield '#ifndef PB_%s_INCLUDED\n' % symbol yield '#define PB_%s_INCLUDED\n' % symbol try: yield options.libformat % ('pb.h') except TypeError: # no %s specified - use whatever was passed in as options.libformat yield options.libformat yield '\n' for incfile in includes: noext = os.path.splitext(incfile)[0] yield options.genformat % (noext + options.extension + '.h') yield '\n' yield '/* @@protoc_insertion_point(includes) */\n' yield '#if PB_PROTO_HEADER_VERSION != 30\n' yield '#error Regenerate this file with the current version of nanopb generator.\n' yield '#endif\n' yield '\n' yield '#ifdef __cplusplus\n' yield 'extern "C" {\n' yield '#endif\n\n' if self.enums: yield '/* Enum definitions */\n' for enum in self.enums: yield str(enum) + '\n\n' if self.messages: yield '/* Struct definitions */\n' for msg in sort_dependencies(self.messages): yield msg.types() yield str(msg) + '\n\n' if self.extensions: yield '/* Extensions */\n' for extension in self.extensions: yield extension.extension_decl() yield '\n' if self.messages: yield '/* Default values for struct fields */\n' for msg in self.messages: yield msg.default_decl(True) yield '\n' yield '/* Initializer values for message structs */\n' for msg in self.messages: identifier = '%s_init_default' % msg.name yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False)) for msg in self.messages: identifier = '%s_init_zero' % msg.name yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True)) yield '\n' yield '/* Field tags (for use in manual encoding/decoding) */\n' for msg in sort_dependencies(self.messages): for field in msg.fields: yield field.tags() for extension in self.extensions: yield extension.tags() yield '\n' yield '/* Struct field encoding specification for nanopb */\n' for msg in self.messages: yield msg.fields_declaration() + '\n' yield '\n' yield '/* Maximum encoded size of messages (where known) */\n' for msg in self.messages: msize = msg.encoded_size(self.dependencies) identifier = '%s_size' % msg.name if msize is not None: yield '#define %-40s %s\n' % (identifier, msize) else: yield '/* %s depends on runtime parameters */\n' % identifier yield '\n' yield '/* Message IDs (where set with "msgid" option) */\n' yield '#ifdef PB_MSGID\n' for msg in self.messages: if hasattr(msg,'msgid'): yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name) yield '\n' symbol = make_identifier(headername.split('.')[0]) yield '#define %s_MESSAGES \\\n' % symbol for msg in self.messages: m = "-1" msize = msg.encoded_size(self.dependencies) if msize is not None: m = msize if hasattr(msg,'msgid'): yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name) yield '\n' for msg in self.messages: if hasattr(msg,'msgid'): yield '#define %s_msgid %d\n' % (msg.name, msg.msgid) yield '\n' yield '#endif\n\n' yield '#ifdef __cplusplus\n' yield '} /* extern "C" */\n' yield '#endif\n' # End of header yield '/* @@protoc_insertion_point(eof) */\n' yield '\n#endif\n'
[ "def", "generate_header", "(", "self", ",", "includes", ",", "headername", ",", "options", ")", ":", "yield", "'/* Automatically generated nanopb header */\\n'", "if", "options", ".", "notimestamp", ":", "yield", "'/* Generated by %s */\\n\\n'", "%", "(", "nanopb_versio...
https://github.com/alexozer/jankdrone/blob/c4b403eb254b41b832ab2bdfade12ba59c99e5dc/shm/lib/nanopb/generator/nanopb_generator.py#L1065-L1193
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mhlib.py
python
MH.deletefolder
(self, name)
Delete a folder. This removes files in the folder but not subdirectories. Raise os.error if deleting the folder itself fails.
Delete a folder. This removes files in the folder but not subdirectories. Raise os.error if deleting the folder itself fails.
[ "Delete", "a", "folder", ".", "This", "removes", "files", "in", "the", "folder", "but", "not", "subdirectories", ".", "Raise", "os", ".", "error", "if", "deleting", "the", "folder", "itself", "fails", "." ]
def deletefolder(self, name): """Delete a folder. This removes files in the folder but not subdirectories. Raise os.error if deleting the folder itself fails.""" fullname = os.path.join(self.getpath(), name) for subname in os.listdir(fullname): fullsubname = os.path.join(fullname, subname) try: os.unlink(fullsubname) except os.error: self.error('%s not deleted, continuing...' % fullsubname) os.rmdir(fullname)
[ "def", "deletefolder", "(", "self", ",", "name", ")", ":", "fullname", "=", "os", ".", "path", ".", "join", "(", "self", ".", "getpath", "(", ")", ",", "name", ")", "for", "subname", "in", "os", ".", "listdir", "(", "fullname", ")", ":", "fullsubna...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/mhlib.py#L224-L235
microsoft/EdgeML
ef9f8a77f096acbdeb941014791f8eda1c1bc35b
tf/edgeml_tf/utils.py
python
getConfusionMatrix
(predicted, target, numClasses)
return arr
Returns a confusion matrix for a multiclass classification problem. `predicted` is a 1-D array of integers representing the predicted classes and `target` is the target classes. confusion[i][j]: Number of elements of class j predicted as class i Labels are assumed to be in range(0, numClasses) Use`printFormattedConfusionMatrix` to echo the confusion matrix in a user friendly form.
Returns a confusion matrix for a multiclass classification problem. `predicted` is a 1-D array of integers representing the predicted classes and `target` is the target classes.
[ "Returns", "a", "confusion", "matrix", "for", "a", "multiclass", "classification", "problem", ".", "predicted", "is", "a", "1", "-", "D", "array", "of", "integers", "representing", "the", "predicted", "classes", "and", "target", "is", "the", "target", "classes...
def getConfusionMatrix(predicted, target, numClasses): ''' Returns a confusion matrix for a multiclass classification problem. `predicted` is a 1-D array of integers representing the predicted classes and `target` is the target classes. confusion[i][j]: Number of elements of class j predicted as class i Labels are assumed to be in range(0, numClasses) Use`printFormattedConfusionMatrix` to echo the confusion matrix in a user friendly form. ''' assert(predicted.ndim == 1) assert(target.ndim == 1) arr = np.zeros([numClasses, numClasses]) for i in range(len(predicted)): arr[predicted[i]][target[i]] += 1 return arr
[ "def", "getConfusionMatrix", "(", "predicted", ",", "target", ",", "numClasses", ")", ":", "assert", "(", "predicted", ".", "ndim", "==", "1", ")", "assert", "(", "target", ".", "ndim", "==", "1", ")", "arr", "=", "np", ".", "zeros", "(", "[", "numCl...
https://github.com/microsoft/EdgeML/blob/ef9f8a77f096acbdeb941014791f8eda1c1bc35b/tf/edgeml_tf/utils.py#L143-L161
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PropertyGridManager.IsPropertySelected
(*args, **kwargs)
return _propgrid.PropertyGridManager_IsPropertySelected(*args, **kwargs)
IsPropertySelected(self, PGPropArg id) -> bool
IsPropertySelected(self, PGPropArg id) -> bool
[ "IsPropertySelected", "(", "self", "PGPropArg", "id", ")", "-", ">", "bool" ]
def IsPropertySelected(*args, **kwargs): """IsPropertySelected(self, PGPropArg id) -> bool""" return _propgrid.PropertyGridManager_IsPropertySelected(*args, **kwargs)
[ "def", "IsPropertySelected", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGridManager_IsPropertySelected", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L3547-L3549
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/build/waf-1.7.13/waflib/Tools/c_preproc.py
python
trimquotes
(s)
return s
Remove the single quotes around an expression:: trimquotes("'test'") == "test" :param s: expression to transform :type s: string :rtype: string
Remove the single quotes around an expression::
[ "Remove", "the", "single", "quotes", "around", "an", "expression", "::" ]
def trimquotes(s): """ Remove the single quotes around an expression:: trimquotes("'test'") == "test" :param s: expression to transform :type s: string :rtype: string """ if not s: return '' s = s.rstrip() if s[0] == "'" and s[-1] == "'": return s[1:-1] return s
[ "def", "trimquotes", "(", "s", ")", ":", "if", "not", "s", ":", "return", "''", "s", "=", "s", ".", "rstrip", "(", ")", "if", "s", "[", "0", "]", "==", "\"'\"", "and", "s", "[", "-", "1", "]", "==", "\"'\"", ":", "return", "s", "[", "1", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/build/waf-1.7.13/waflib/Tools/c_preproc.py#L172-L185
nvdla/sw
79538ba1b52b040a4a4645f630e457fa01839e90
umd/external/protobuf-2.6/python/mox.py
python
Regex.__init__
(self, pattern, flags=0)
Initialize. Args: # pattern is the regular expression to search for pattern: str # flags passed to re.compile function as the second argument flags: int
Initialize.
[ "Initialize", "." ]
def __init__(self, pattern, flags=0): """Initialize. Args: # pattern is the regular expression to search for pattern: str # flags passed to re.compile function as the second argument flags: int """ self.regex = re.compile(pattern, flags=flags)
[ "def", "__init__", "(", "self", ",", "pattern", ",", "flags", "=", "0", ")", ":", "self", ".", "regex", "=", "re", ".", "compile", "(", "pattern", ",", "flags", "=", "flags", ")" ]
https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/mox.py#L910-L920
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/multiprocessing/managers.py
python
debug_info
(self, c)
Return some info --- useful to spot problems with refcounting
Return some info --- useful to spot problems with refcounting
[ "Return", "some", "info", "---", "useful", "to", "spot", "problems", "with", "refcounting" ]
def debug_info(self, c): ''' Return some info --- useful to spot problems with refcounting ''' # Perhaps include debug info about 'c'? with self.mutex: result = [] keys = list(self.id_to_refcount.keys()) keys.sort() for ident in keys: if ident != '0': result.append(' %s: refcount=%s\n %s' % (ident, self.id_to_refcount[ident], str(self.id_to_obj[ident][0])[:75])) return '\n'.join(result)
[ "def", "debug_info", "(", "self", ",", "c", ")", ":", "# Perhaps include debug info about 'c'?", "with", "self", ".", "mutex", ":", "result", "=", "[", "]", "keys", "=", "list", "(", "self", ".", "id_to_refcount", ".", "keys", "(", ")", ")", "keys", ".",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/multiprocessing/managers.py#L329-L343
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/json_schema_compiler/cc_generator.py
python
_Generator._GeneratePopulateVariableFromValue
(self, type_, src_var, dst_var, failure_value, is_ptr=False)
return Code().Sblock('{').Concat(c.Substitute({ 'cpp_type': self._type_helper.GetCppType(type_), 'src_var': src_var, 'dst_var': dst_var, 'failure_value': failure_value, 'key': type_.name, 'parent_key': type_.parent.name, })).Eblock('}')
Generates code to populate a variable |dst_var| of type |type_| from a Value* at |src_var|. The Value* is assumed to be non-NULL. In the generated code, if |dst_var| fails to be populated then Populate will return |failure_value|.
Generates code to populate a variable |dst_var| of type |type_| from a Value* at |src_var|. The Value* is assumed to be non-NULL. In the generated code, if |dst_var| fails to be populated then Populate will return |failure_value|.
[ "Generates", "code", "to", "populate", "a", "variable", "|dst_var|", "of", "type", "|type_|", "from", "a", "Value", "*", "at", "|src_var|", ".", "The", "Value", "*", "is", "assumed", "to", "be", "non", "-", "NULL", ".", "In", "the", "generated", "code", ...
def _GeneratePopulateVariableFromValue(self, type_, src_var, dst_var, failure_value, is_ptr=False): """Generates code to populate a variable |dst_var| of type |type_| from a Value* at |src_var|. The Value* is assumed to be non-NULL. In the generated code, if |dst_var| fails to be populated then Populate will return |failure_value|. """ c = Code() underlying_type = self._type_helper.FollowRef(type_) if underlying_type.property_type.is_fundamental: if is_ptr: (c.Append('%(cpp_type)s temp;') .Sblock('if (!%s) {' % cpp_util.GetAsFundamentalValue( self._type_helper.FollowRef(type_), src_var, '&temp')) .Concat(self._GenerateError( '"\'%%(key)s\': expected ' + '%s, got " + %s' % ( type_.name, self._util_cc_helper.GetValueTypeString( '%%(src_var)s', True))))) c.Append('%(dst_var)s.reset();') if not self._generate_error_messages: c.Append('return %(failure_value)s;') (c.Eblock('}') .Append('else') .Append(' %(dst_var)s.reset(new %(cpp_type)s(temp));') ) else: (c.Sblock('if (!%s) {' % cpp_util.GetAsFundamentalValue( self._type_helper.FollowRef(type_), src_var, '&%s' % dst_var)) .Concat(self._GenerateError( '"\'%%(key)s\': expected ' + '%s, got " + %s' % ( type_.name, self._util_cc_helper.GetValueTypeString( '%%(src_var)s', True)))) .Append('return %(failure_value)s;') .Eblock('}') ) elif underlying_type.property_type == PropertyType.OBJECT: if is_ptr: (c.Append('const base::DictionaryValue* dictionary = NULL;') .Sblock('if (!%(src_var)s->GetAsDictionary(&dictionary)) {') .Concat(self._GenerateError( '"\'%%(key)s\': expected dictionary, got " + ' + self._util_cc_helper.GetValueTypeString('%%(src_var)s', True)))) # If an optional property fails to populate, the population can still # succeed with a warning. If no error messages are generated, this # warning is not set and we fail out instead. if not self._generate_error_messages: c.Append('return %(failure_value)s;') (c.Eblock('}') .Sblock('else {') .Append('std::unique_ptr<%(cpp_type)s> temp(new %(cpp_type)s());') .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs( ('*dictionary', 'temp.get()'))) .Append(' return %(failure_value)s;') ) (c.Append('}') .Append('else') .Append(' %(dst_var)s = std::move(temp);') .Eblock('}') ) else: (c.Append('const base::DictionaryValue* dictionary = NULL;') .Sblock('if (!%(src_var)s->GetAsDictionary(&dictionary)) {') .Concat(self._GenerateError( '"\'%%(key)s\': expected dictionary, got " + ' + self._util_cc_helper.GetValueTypeString('%%(src_var)s', True))) .Append('return %(failure_value)s;') .Eblock('}') .Append('if (!%%(cpp_type)s::Populate(%s)) {' % self._GenerateArgs( ('*dictionary', '&%(dst_var)s'))) .Append(' return %(failure_value)s;') .Append('}') ) elif underlying_type.property_type == PropertyType.FUNCTION: if is_ptr: c.Append('%(dst_var)s.reset(new base::DictionaryValue());') elif underlying_type.property_type == PropertyType.ANY: c.Append('%(dst_var)s = %(src_var)s->CreateDeepCopy();') elif underlying_type.property_type == PropertyType.ARRAY: # util_cc_helper deals with optional and required arrays (c.Append('const base::ListValue* list = NULL;') .Sblock('if (!%(src_var)s->GetAsList(&list)) {') .Concat(self._GenerateError( '"\'%%(key)s\': expected list, got " + ' + self._util_cc_helper.GetValueTypeString('%%(src_var)s', True))) ) if is_ptr and self._generate_error_messages: c.Append('%(dst_var)s.reset();') else: c.Append('return %(failure_value)s;') c.Eblock('}') c.Sblock('else {') item_type = self._type_helper.FollowRef(underlying_type.item_type) if item_type.property_type == PropertyType.ENUM: c.Concat(self._GenerateListValueToEnumArrayConversion( item_type, 'list', dst_var, failure_value, is_ptr=is_ptr)) else: c.Sblock('if (!%s(%s)) {' % ( self._util_cc_helper.PopulateArrayFromListFunction(is_ptr), self._GenerateArgs(('*list', '&%(dst_var)s')))) c.Concat(self._GenerateError( '"unable to populate array \'%%(parent_key)s\'"')) if is_ptr and self._generate_error_messages: c.Append('%(dst_var)s.reset();') else: c.Append('return %(failure_value)s;') c.Eblock('}') c.Eblock('}') elif underlying_type.property_type == PropertyType.CHOICES: if is_ptr: (c.Append('std::unique_ptr<%(cpp_type)s> temp(new %(cpp_type)s());') .Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs( ('*%(src_var)s', 'temp.get()'))) .Append(' return %(failure_value)s;') .Append('%(dst_var)s = std::move(temp);') ) else: (c.Append('if (!%%(cpp_type)s::Populate(%s))' % self._GenerateArgs( ('*%(src_var)s', '&%(dst_var)s'))) .Append(' return %(failure_value)s;')) elif underlying_type.property_type == PropertyType.ENUM: c.Concat(self._GenerateStringToEnumConversion(underlying_type, src_var, dst_var, failure_value)) elif underlying_type.property_type == PropertyType.BINARY: (c.Append('const base::BinaryValue* binary_value = NULL;') .Sblock('if (!%(src_var)s->IsType(base::Value::TYPE_BINARY)) {') .Concat(self._GenerateError( '"\'%%(key)s\': expected binary, got " + ' + self._util_cc_helper.GetValueTypeString('%%(src_var)s', True))) ) if not self._generate_error_messages: c.Append('return %(failure_value)s;') (c.Eblock('}') .Sblock('else {') .Append(' binary_value =') .Append(' static_cast<const base::BinaryValue*>(%(src_var)s);') ) if is_ptr: (c.Append('%(dst_var)s.reset(new std::vector<char>(') .Append(' binary_value->GetBuffer(),') .Append(' binary_value->GetBuffer() + binary_value->GetSize()));') ) else: (c.Append('%(dst_var)s.assign(') .Append(' binary_value->GetBuffer(),') .Append(' binary_value->GetBuffer() + binary_value->GetSize());') ) c.Eblock('}') else: raise NotImplementedError(type_) if c.IsEmpty(): return c return Code().Sblock('{').Concat(c.Substitute({ 'cpp_type': self._type_helper.GetCppType(type_), 'src_var': src_var, 'dst_var': dst_var, 'failure_value': failure_value, 'key': type_.name, 'parent_key': type_.parent.name, })).Eblock('}')
[ "def", "_GeneratePopulateVariableFromValue", "(", "self", ",", "type_", ",", "src_var", ",", "dst_var", ",", "failure_value", ",", "is_ptr", "=", "False", ")", ":", "c", "=", "Code", "(", ")", "underlying_type", "=", "self", ".", "_type_helper", ".", "Follow...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/json_schema_compiler/cc_generator.py#L751-L925
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/utils/sparsefuncs.py
python
inplace_swap_column
(X, m, n)
Swaps two columns of a CSC/CSR matrix in-place. Parameters ---------- X : CSR or CSC sparse matrix, shape=(n_samples, n_features) Matrix whose two columns are to be swapped. m: int Index of the column of X to be swapped. n : int Index of the column of X to be swapped.
Swaps two columns of a CSC/CSR matrix in-place.
[ "Swaps", "two", "columns", "of", "a", "CSC", "/", "CSR", "matrix", "in", "-", "place", "." ]
def inplace_swap_column(X, m, n): """ Swaps two columns of a CSC/CSR matrix in-place. Parameters ---------- X : CSR or CSC sparse matrix, shape=(n_samples, n_features) Matrix whose two columns are to be swapped. m: int Index of the column of X to be swapped. n : int Index of the column of X to be swapped. """ if m < 0: m += X.shape[1] if n < 0: n += X.shape[1] if isinstance(X, sp.csc_matrix): return inplace_swap_row_csr(X, m, n) elif isinstance(X, sp.csr_matrix): return inplace_swap_row_csc(X, m, n) else: _raise_typeerror(X)
[ "def", "inplace_swap_column", "(", "X", ",", "m", ",", "n", ")", ":", "if", "m", "<", "0", ":", "m", "+=", "X", ".", "shape", "[", "1", "]", "if", "n", "<", "0", ":", "n", "+=", "X", ".", "shape", "[", "1", "]", "if", "isinstance", "(", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/utils/sparsefuncs.py#L312-L336
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/distutils/misc_util.py
python
generate_config_py
(target)
return target
Generate config.py file containing system_info information used during building the package. Usage: config['py_modules'].append((packagename, '__config__',generate_config_py))
Generate config.py file containing system_info information used during building the package.
[ "Generate", "config", ".", "py", "file", "containing", "system_info", "information", "used", "during", "building", "the", "package", "." ]
def generate_config_py(target): """Generate config.py file containing system_info information used during building the package. Usage: config['py_modules'].append((packagename, '__config__',generate_config_py)) """ from numpy.distutils.system_info import system_info from distutils.dir_util import mkpath mkpath(os.path.dirname(target)) f = open(target, 'w') f.write('# This file is generated by numpy\'s %s\n' % (os.path.basename(sys.argv[0]))) f.write('# It contains system_info results at the time of building this package.\n') f.write('__all__ = ["get_info","show"]\n\n') # For gfortran+msvc combination, extra shared libraries may exist f.write(""" import os import sys extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs') if sys.platform == 'win32' and os.path.isdir(extra_dll_dir): os.environ.setdefault('PATH', '') os.environ['PATH'] += os.pathsep + extra_dll_dir """) for k, i in system_info.saved_results.items(): f.write('%s=%r\n' % (k, i)) f.write(r''' def get_info(name): g = globals() return g.get(name, g.get(name + "_info", {})) def show(): for name,info_dict in globals().items(): if name[0] == "_" or type(info_dict) is not type({}): continue print(name + ":") if not info_dict: print(" NOT AVAILABLE") for k,v in info_dict.items(): v = str(v) if k == "sources" and len(v) > 200: v = v[:60] + " ...\n... " + v[-60:] print(" %s = %s" % (k,v)) ''') f.close() return target
[ "def", "generate_config_py", "(", "target", ")", ":", "from", "numpy", ".", "distutils", ".", "system_info", "import", "system_info", "from", "distutils", ".", "dir_util", "import", "mkpath", "mkpath", "(", "os", ".", "path", ".", "dirname", "(", "target", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/distutils/misc_util.py#L2266-L2316
kushview/Element
1cc16380caa2ab79461246ba758b9de1f46db2a5
waflib/Tools/d.py
python
process_header
(self)
Process the attribute 'header_lst' to create the d header compilation tasks:: def build(bld): bld.program(source='foo.d', target='app', header_lst='blah.d')
Process the attribute 'header_lst' to create the d header compilation tasks::
[ "Process", "the", "attribute", "header_lst", "to", "create", "the", "d", "header", "compilation", "tasks", "::" ]
def process_header(self): """ Process the attribute 'header_lst' to create the d header compilation tasks:: def build(bld): bld.program(source='foo.d', target='app', header_lst='blah.d') """ for i in getattr(self, 'header_lst', []): node = self.path.find_resource(i[0]) if not node: raise Errors.WafError('file %r not found on d obj' % i[0]) self.create_task('d_header', node, node.change_ext('.di'))
[ "def", "process_header", "(", "self", ")", ":", "for", "i", "in", "getattr", "(", "self", ",", "'header_lst'", ",", "[", "]", ")", ":", "node", "=", "self", ".", "path", ".", "find_resource", "(", "i", "[", "0", "]", ")", "if", "not", "node", ":"...
https://github.com/kushview/Element/blob/1cc16380caa2ab79461246ba758b9de1f46db2a5/waflib/Tools/d.py#L85-L96
LiquidPlayer/LiquidCore
9405979363f2353ac9a71ad8ab59685dd7f919c9
deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py
python
_CreateProjectObjects
(target_list, target_dicts, options, msvs_version)
return projects
Create a MSVSProject object for the targets found in target list. Arguments: target_list: the list of targets to generate project objects for. target_dicts: the dictionary of specifications. options: global generator options. msvs_version: the MSVSVersion object. Returns: A set of created projects, keyed by target.
Create a MSVSProject object for the targets found in target list.
[ "Create", "a", "MSVSProject", "object", "for", "the", "targets", "found", "in", "target", "list", "." ]
def _CreateProjectObjects(target_list, target_dicts, options, msvs_version): """Create a MSVSProject object for the targets found in target list. Arguments: target_list: the list of targets to generate project objects for. target_dicts: the dictionary of specifications. options: global generator options. msvs_version: the MSVSVersion object. Returns: A set of created projects, keyed by target. """ global fixpath_prefix # Generate each project. projects = {} for qualified_target in target_list: spec = target_dicts[qualified_target] if spec['toolset'] != 'target': raise GypError( 'Multiple toolsets not supported in msvs build (target %s)' % qualified_target) proj_path, fixpath_prefix = _GetPathOfProject(qualified_target, spec, options, msvs_version) guid = _GetGuidOfProject(proj_path, spec) overrides = _GetPlatformOverridesOfProject(spec) build_file = gyp.common.BuildFile(qualified_target) # Create object for this project. obj = MSVSNew.MSVSProject( proj_path, name=spec['target_name'], guid=guid, spec=spec, build_file=build_file, config_platform_overrides=overrides, fixpath_prefix=fixpath_prefix) # Set project toolset if any (MS build only) if msvs_version.UsesVcxproj(): obj.set_msbuild_toolset( _GetMsbuildToolsetOfProject(proj_path, spec, msvs_version)) projects[qualified_target] = obj # Set all the dependencies, but not if we are using an external builder like # ninja for project in projects.values(): if not project.spec.get('msvs_external_builder'): deps = project.spec.get('dependencies', []) deps = [projects[d] for d in deps] project.set_dependencies(deps) return projects
[ "def", "_CreateProjectObjects", "(", "target_list", ",", "target_dicts", ",", "options", ",", "msvs_version", ")", ":", "global", "fixpath_prefix", "# Generate each project.", "projects", "=", "{", "}", "for", "qualified_target", "in", "target_list", ":", "spec", "=...
https://github.com/LiquidPlayer/LiquidCore/blob/9405979363f2353ac9a71ad8ab59685dd7f919c9/deps/node-10.15.3/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/msvs.py#L1812-L1858
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/decomposition/kernel_pca.py
python
KernelPCA.transform
(self, X)
return np.dot(K, self.alphas_ / np.sqrt(self.lambdas_))
Transform X. Parameters ---------- X: array-like, shape (n_samples, n_features) Returns ------- X_new: array-like, shape (n_samples, n_components)
Transform X.
[ "Transform", "X", "." ]
def transform(self, X): """Transform X. Parameters ---------- X: array-like, shape (n_samples, n_features) Returns ------- X_new: array-like, shape (n_samples, n_components) """ check_is_fitted(self, 'X_fit_') K = self._centerer.transform(self._get_kernel(X, self.X_fit_)) return np.dot(K, self.alphas_ / np.sqrt(self.lambdas_))
[ "def", "transform", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "'X_fit_'", ")", "K", "=", "self", ".", "_centerer", ".", "transform", "(", "self", ".", "_get_kernel", "(", "X", ",", "self", ".", "X_fit_", ")", ")", "return"...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/decomposition/kernel_pca.py#L269-L283
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/util/memory.py
python
dismantle_ordered_dict
(ordered_dict)
Remove reference cycle in OrderedDict `ordered_dict`. Helpful for making sure the garbage collector doesn't need to run after using an OrderedDict. Args: ordered_dict: A `OrderedDict` object to destroy. This object is unusable after this function runs.
Remove reference cycle in OrderedDict `ordered_dict`.
[ "Remove", "reference", "cycle", "in", "OrderedDict", "ordered_dict", "." ]
def dismantle_ordered_dict(ordered_dict): """Remove reference cycle in OrderedDict `ordered_dict`. Helpful for making sure the garbage collector doesn't need to run after using an OrderedDict. Args: ordered_dict: A `OrderedDict` object to destroy. This object is unusable after this function runs. """ # OrderedDict, makes a simple reference loop # and hides it in an __attribute in some Python versions. We don't need to # throw an error if we can't find it, but if we do find it we can break the # loop to avoid creating work for the garbage collector. problematic_cycle = ordered_dict.__dict__.get("_OrderedDict__root", None) # pylint: disable=protected-access if problematic_cycle: try: del problematic_cycle[0][:] except TypeError: # This is probably not one of the problematic Python versions. Continue # with the rest of our cleanup. pass
[ "def", "dismantle_ordered_dict", "(", "ordered_dict", ")", ":", "# OrderedDict, makes a simple reference loop", "# and hides it in an __attribute in some Python versions. We don't need to", "# throw an error if we can't find it, but if we do find it we can break the", "# loop to avoid creating wor...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/util/memory.py#L20-L41
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/format.py
python
write_array_header_1_0
(fp, d)
Write the header for an array using the 1.0 format. Parameters ---------- fp : filelike object d : dict This has the appropriate entries for writing its string representation to the header of the file.
Write the header for an array using the 1.0 format.
[ "Write", "the", "header", "for", "an", "array", "using", "the", "1", ".", "0", "format", "." ]
def write_array_header_1_0(fp, d): """ Write the header for an array using the 1.0 format. Parameters ---------- fp : filelike object d : dict This has the appropriate entries for writing its string representation to the header of the file. """ import struct header = ["{"] for key, value in sorted(d.items()): # Need to use repr here, since we eval these when reading header.append("'%s': %s, " % (key, repr(value))) header.append("}") header = "".join(header) # Pad the header with spaces and a final newline such that the magic # string, the header-length short and the header are aligned on a 16-byte # boundary. Hopefully, some system, possibly memory-mapping, can take # advantage of our premature optimization. current_header_len = MAGIC_LEN + 2 + len(header) + 1 # 1 for the newline topad = 16 - (current_header_len % 16) header = asbytes(header + ' '*topad + '\n') if len(header) >= (256*256): raise ValueError("header does not fit inside %s bytes" % (256*256)) header_len_str = struct.pack('<H', len(header)) fp.write(header_len_str) fp.write(header)
[ "def", "write_array_header_1_0", "(", "fp", ",", "d", ")", ":", "import", "struct", "header", "=", "[", "\"{\"", "]", "for", "key", ",", "value", "in", "sorted", "(", "d", ".", "items", "(", ")", ")", ":", "# Need to use repr here, since we eval these when r...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/lib/format.py#L261-L289
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/_pyio.py
python
IOBase.closed
(self)
return self.__closed
closed: bool. True iff the file has been closed. For backwards compatibility, this is a property, not a predicate.
closed: bool. True iff the file has been closed.
[ "closed", ":", "bool", ".", "True", "iff", "the", "file", "has", "been", "closed", "." ]
def closed(self): """closed: bool. True iff the file has been closed. For backwards compatibility, this is a property, not a predicate. """ return self.__closed
[ "def", "closed", "(", "self", ")", ":", "return", "self", ".", "__closed" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/_pyio.py#L479-L484
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/ogl/_basic.py
python
Shape.AssignNewIds
(self)
Assign new ids to this image and its children.
Assign new ids to this image and its children.
[ "Assign", "new", "ids", "to", "this", "image", "and", "its", "children", "." ]
def AssignNewIds(self): """Assign new ids to this image and its children.""" self._id = wx.NewId() for child in self._children: child.AssignNewIds()
[ "def", "AssignNewIds", "(", "self", ")", ":", "self", ".", "_id", "=", "wx", ".", "NewId", "(", ")", "for", "child", "in", "self", ".", "_children", ":", "child", ".", "AssignNewIds", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/ogl/_basic.py#L728-L732
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/sping/colors.py
python
Color.__init__
(self, red=0, green=0, blue=0)
Initialize with red, green, blue in range [0-1].
Initialize with red, green, blue in range [0-1].
[ "Initialize", "with", "red", "green", "blue", "in", "range", "[", "0", "-", "1", "]", "." ]
def __init__(self, red=0, green=0, blue=0): "Initialize with red, green, blue in range [0-1]." _float = float d = self.__dict__ d["red"] = _float(red) d["green"] = _float(green) d["blue"] = _float(blue)
[ "def", "__init__", "(", "self", ",", "red", "=", "0", ",", "green", "=", "0", ",", "blue", "=", "0", ")", ":", "_float", "=", "float", "d", "=", "self", ".", "__dict__", "d", "[", "\"red\"", "]", "=", "_float", "(", "red", ")", "d", "[", "\"g...
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/colors.py#L10-L16
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py
python
MatrixTable.set_matrix
(self, matrix)
return
:param matrix: :return:
[]
def set_matrix(self, matrix): """ :param matrix: :return: """ # check inputs assert isinstance(matrix, numpy.ndarray) and matrix.shape == (4, 4), 'Matrix {0} must be ndarray with {1}.' \ ''.format(matrix, matrix.shape) for i in range(matrix.shape[0]): for j in range(matrix.shape[1]): self.set_value_cell(i, j, matrix[i, j]) return
[ "def", "set_matrix", "(", "self", ",", "matrix", ")", ":", "# check inputs", "assert", "isinstance", "(", "matrix", ",", "numpy", ".", "ndarray", ")", "and", "matrix", ".", "shape", "==", "(", "4", ",", "4", ")", ",", "'Matrix {0} must be ndarray with {1}.'"...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py#L125-L138
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/help.py
python
HelpParser.indent
(self, amt=1)
Change indent (+1, 0, -1) and tags.
Change indent (+1, 0, -1) and tags.
[ "Change", "indent", "(", "+", "1", "0", "-", "1", ")", "and", "tags", "." ]
def indent(self, amt=1): "Change indent (+1, 0, -1) and tags." self.level += amt self.tags = '' if self.level == 0 else 'l'+str(self.level)
[ "def", "indent", "(", "self", ",", "amt", "=", "1", ")", ":", "self", ".", "level", "+=", "amt", "self", ".", "tags", "=", "''", "if", "self", ".", "level", "==", "0", "else", "'l'", "+", "str", "(", "self", ".", "level", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/help.py#L67-L70
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
URI.setServer
(self, server)
Set the server part of an URI.
Set the server part of an URI.
[ "Set", "the", "server", "part", "of", "an", "URI", "." ]
def setServer(self, server): """Set the server part of an URI. """ libxml2mod.xmlURISetServer(self._o, server)
[ "def", "setServer", "(", "self", ",", "server", ")", ":", "libxml2mod", ".", "xmlURISetServer", "(", "self", ".", "_o", ",", "server", ")" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L6259-L6261
networkit/networkit
695b7a786a894a303fa8587597d5ef916e797729
extrafiles/tooling/CppClangFormat.py
python
findClangFormat
()
Tries to find clang-format-XXX variants within the path
Tries to find clang-format-XXX variants within the path
[ "Tries", "to", "find", "clang", "-", "format", "-", "XXX", "variants", "within", "the", "path" ]
def findClangFormat(): """Tries to find clang-format-XXX variants within the path""" cmd = "clang-format" allowed = [cmd] + [cmd + "-" + str(x) for x in range(nkt.MIN_CLANG_FORMAT_VERSION, nkt.MAX_CLANG_FORMAT_VERSION + 1)] for candidate in allowed: if isSupported(candidate): if nkt.isVerbose(): version = str(subprocess.check_output([candidate, "--version"], universal_newlines=True, env=getEnv())).strip() print("clang-format: %s\n -> Version: %s" % (candidate, version)) return candidate raise FileNotFoundError("clang-format binary not found. We searched for:\n " + "\n ".join(allowed))
[ "def", "findClangFormat", "(", ")", ":", "cmd", "=", "\"clang-format\"", "allowed", "=", "[", "cmd", "]", "+", "[", "cmd", "+", "\"-\"", "+", "str", "(", "x", ")", "for", "x", "in", "range", "(", "nkt", ".", "MIN_CLANG_FORMAT_VERSION", ",", "nkt", "....
https://github.com/networkit/networkit/blob/695b7a786a894a303fa8587597d5ef916e797729/extrafiles/tooling/CppClangFormat.py#L37-L50
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/operations/array_ops.py
python
Range.infer_value
(self, start_value, limit_value, delat_value)
return None
Infer the value of input for Range.
Infer the value of input for Range.
[ "Infer", "the", "value", "of", "input", "for", "Range", "." ]
def infer_value(self, start_value, limit_value, delat_value): """Infer the value of input for Range.""" if start_value is not None and limit_value is not None and delat_value is not None: start = np.asscalar(start_value.asnumpy()) limit = np.asscalar(limit_value.asnumpy()) delat = np.asscalar(delat_value.asnumpy()) return Tensor(np.arange(start, limit, delat), dtype=start_value.dtype) return None
[ "def", "infer_value", "(", "self", ",", "start_value", ",", "limit_value", ",", "delat_value", ")", ":", "if", "start_value", "is", "not", "None", "and", "limit_value", "is", "not", "None", "and", "delat_value", "is", "not", "None", ":", "start", "=", "np"...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/operations/array_ops.py#L6168-L6175
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
build/unix/makepchinput.py
python
getIncludeLinesFromDict
(dictFileName)
return allHeadersPartContent
Search for the headers after the line 'static const char* headers[]' Return the code to be added to the allHeaders as string
Search for the headers after the line 'static const char* headers[]' Return the code to be added to the allHeaders as string
[ "Search", "for", "the", "headers", "after", "the", "line", "static", "const", "char", "*", "headers", "[]", "Return", "the", "code", "to", "be", "added", "to", "the", "allHeaders", "as", "string" ]
def getIncludeLinesFromDict(dictFileName): """ Search for the headers after the line 'static const char* headers[]' Return the code to be added to the allHeaders as string """ allHeadersPartContent="" selectedLines = getLinesFromDict('static const char* headers[]', dictFileName) allHeadersPartContent += "// %s\n" % dictFileName for selectedLine in selectedLines: header = selectedLine[:-1] # remove the "," allHeadersPartContent += "#include %s\n" %header return allHeadersPartContent
[ "def", "getIncludeLinesFromDict", "(", "dictFileName", ")", ":", "allHeadersPartContent", "=", "\"\"", "selectedLines", "=", "getLinesFromDict", "(", "'static const char* headers[]'", ",", "dictFileName", ")", "allHeadersPartContent", "+=", "\"// %s\\n\"", "%", "dictFileNam...
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/build/unix/makepchinput.py#L288-L300
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/ops/linalg_ops.py
python
batch_svd
(tensor, compute_uv=True, full_matrices=False, name=None)
Computes the singular value decompositions of a batch of matrices. Computes the SVD of each inner matrix in `tensor` such that `tensor[..., :, :] = u[..., :, :] * diag(s[..., :, :]) * transpose(v[..., :, :])` ```prettyprint # a is a tensor. # s is a tensor of singular values. # u is a tensor of left singular vectors. # v is a tensor of right singular vectors. s, u, v = batch_svd(a) s = batch_svd(a, compute_uv=False) ``` Args: matrix: `Tensor` of shape `[..., M, N]`. Let `P` be the minimum of `M` and `N`. compute_uv: If `True` then left and right singular vectors will be computed and returned in `u` and `v`, respectively. Otherwise, only the singular values will be computed, which can be significantly faster. full_matrices: If true, compute full-sized `u` and `v`. If false (the default), compute only the leading `P` singular vectors. Ignored if `compute_uv` is `False`. name: string, optional name of the operation. Returns: s: Singular values. Shape is `[..., P]`. u: Right singular vectors. If `full_matrices` is `False` (default) then shape is `[..., M, P]`; if `full_matrices` is `True` then shape is `[..., M, M]`. Not returned if `compute_uv` is `False`. v: Left singular vectors. If `full_matrices` is `False` (default) then shape is `[..., N, P]`. If `full_matrices` is `True` then shape is `[..., N, N]`. Not returned if `compute_uv` is `False`.
Computes the singular value decompositions of a batch of matrices.
[ "Computes", "the", "singular", "value", "decompositions", "of", "a", "batch", "of", "matrices", "." ]
def batch_svd(tensor, compute_uv=True, full_matrices=False, name=None): """Computes the singular value decompositions of a batch of matrices. Computes the SVD of each inner matrix in `tensor` such that `tensor[..., :, :] = u[..., :, :] * diag(s[..., :, :]) * transpose(v[..., :, :])` ```prettyprint # a is a tensor. # s is a tensor of singular values. # u is a tensor of left singular vectors. # v is a tensor of right singular vectors. s, u, v = batch_svd(a) s = batch_svd(a, compute_uv=False) ``` Args: matrix: `Tensor` of shape `[..., M, N]`. Let `P` be the minimum of `M` and `N`. compute_uv: If `True` then left and right singular vectors will be computed and returned in `u` and `v`, respectively. Otherwise, only the singular values will be computed, which can be significantly faster. full_matrices: If true, compute full-sized `u` and `v`. If false (the default), compute only the leading `P` singular vectors. Ignored if `compute_uv` is `False`. name: string, optional name of the operation. Returns: s: Singular values. Shape is `[..., P]`. u: Right singular vectors. If `full_matrices` is `False` (default) then shape is `[..., M, P]`; if `full_matrices` is `True` then shape is `[..., M, M]`. Not returned if `compute_uv` is `False`. v: Left singular vectors. If `full_matrices` is `False` (default) then shape is `[..., N, P]`. If `full_matrices` is `True` then shape is `[..., N, N]`. Not returned if `compute_uv` is `False`. """ s, u, v = gen_linalg_ops.batch_svd( tensor, compute_uv=compute_uv, full_matrices=full_matrices) if compute_uv: return s, u, v else: return s
[ "def", "batch_svd", "(", "tensor", ",", "compute_uv", "=", "True", ",", "full_matrices", "=", "False", ",", "name", "=", "None", ")", ":", "s", ",", "u", ",", "v", "=", "gen_linalg_ops", ".", "batch_svd", "(", "tensor", ",", "compute_uv", "=", "compute...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/ops/linalg_ops.py#L522-L563
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/cfour.py
python
harvest_GRD
(grd)
return mol, grad
Parses the contents *grd* of the Cfour GRD file into the gradient array and coordinate information. The coordinate info is converted into a rather dinky Molecule (no charge, multiplicity, or fragment), but this is these coordinates that govern the reading of molecule orientation by Cfour. Return qcdb.Molecule and gradient array.
Parses the contents *grd* of the Cfour GRD file into the gradient array and coordinate information. The coordinate info is converted into a rather dinky Molecule (no charge, multiplicity, or fragment), but this is these coordinates that govern the reading of molecule orientation by Cfour. Return qcdb.Molecule and gradient array.
[ "Parses", "the", "contents", "*", "grd", "*", "of", "the", "Cfour", "GRD", "file", "into", "the", "gradient", "array", "and", "coordinate", "information", ".", "The", "coordinate", "info", "is", "converted", "into", "a", "rather", "dinky", "Molecule", "(", ...
def harvest_GRD(grd): """Parses the contents *grd* of the Cfour GRD file into the gradient array and coordinate information. The coordinate info is converted into a rather dinky Molecule (no charge, multiplicity, or fragment), but this is these coordinates that govern the reading of molecule orientation by Cfour. Return qcdb.Molecule and gradient array. """ grd = grd.splitlines() Nat = int(grd[0].split()[0]) molxyz = '%d bohr\n\n' % (Nat) grad = [] for at in range(Nat): mline = grd[at + 1].split() el = 'GH' if int(float(mline[0])) == 0 else qcel.periodictable.to_E(int(float(mline[0]))) molxyz += '%s %16s %16s %16s\n' % (el, mline[-3], mline[-2], mline[-1]) lline = grd[at + 1 + Nat].split() grad.append([float(lline[-3]), float(lline[-2]), float(lline[-1])]) mol = Molecule.from_string(molxyz, dtype='xyz+', fix_com=True, fix_orientation=True) return mol, grad
[ "def", "harvest_GRD", "(", "grd", ")", ":", "grd", "=", "grd", ".", "splitlines", "(", ")", "Nat", "=", "int", "(", "grd", "[", "0", "]", ".", "split", "(", ")", "[", "0", "]", ")", "molxyz", "=", "'%d bohr\\n\\n'", "%", "(", "Nat", ")", "grad"...
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/cfour.py#L707-L728
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/RNN/rnn_quantizer/nndct_shared/compile/xop_creator.py
python
reshape
(xgraph: XGraph, node: Node, quant_config: NndctQuantInfo)
r""" nndct reshape is a macro operator, including pack, reshape
r""" nndct reshape is a macro operator, including pack, reshape
[ "r", "nndct", "reshape", "is", "a", "macro", "operator", "including", "pack", "reshape" ]
def reshape(xgraph: XGraph, node: Node, quant_config: NndctQuantInfo) -> NoReturn: r""" nndct reshape is a macro operator, including pack, reshape """ shape = node.node_attr(node.op.AttrName.SHAPE) sub_op_pack, pack_list = _pack(xgraph, node, "shape", shape, quant_config) input_ops: Dict[str, List[Op]] = {} input_ops["shape"] = [sub_op_pack] input_ops["input"] = [xgraph.get_op_by_name(node.in_nodes[0])] xgraph.create_fixed_normal_op( node.name, "reshape", quant_config, input_ops=input_ops)
[ "def", "reshape", "(", "xgraph", ":", "XGraph", ",", "node", ":", "Node", ",", "quant_config", ":", "NndctQuantInfo", ")", "->", "NoReturn", ":", "shape", "=", "node", ".", "node_attr", "(", "node", ".", "op", ".", "AttrName", ".", "SHAPE", ")", "sub_o...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/RNN/rnn_quantizer/nndct_shared/compile/xop_creator.py#L211-L221
qgis/QGIS
15a77662d4bb712184f6aa60d0bd663010a76a75
python/pyplugin_installer/installer_data.py
python
Plugins.allUpgradeable
(self)
return result
return all upgradeable plugins
return all upgradeable plugins
[ "return", "all", "upgradeable", "plugins" ]
def allUpgradeable(self): """ return all upgradeable plugins """ result = {} for i in self.mPlugins: if self.mPlugins[i]["status"] == "upgradeable": result[i] = self.mPlugins[i] return result
[ "def", "allUpgradeable", "(", "self", ")", ":", "result", "=", "{", "}", "for", "i", "in", "self", ".", "mPlugins", ":", "if", "self", ".", "mPlugins", "[", "i", "]", "[", "\"status\"", "]", "==", "\"upgradeable\"", ":", "result", "[", "i", "]", "=...
https://github.com/qgis/QGIS/blob/15a77662d4bb712184f6aa60d0bd663010a76a75/python/pyplugin_installer/installer_data.py#L515-L521
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/framework/io.py
python
save
(obj, path, protocol=4, **configs)
Save an object to the specified path. .. note:: Now supports saving ``state_dict`` of Layer/Optimizer, Tensor and nested structure containing Tensor, Program. .. note:: Different from ``paddle.jit.save``, since the save result of ``paddle.save`` is a single file, there is no need to distinguish multiple saved files by adding a suffix. The argument ``path`` of ``paddle.save`` will be directly used as the saved file name instead of a prefix. In order to unify the saved file name format, we recommend using the paddle standard suffix: 1. for ``Layer.state_dict`` , recommend to use ``.pdparams`` ; 2. for ``Optimizer.state_dict`` , recommend to use ``.pdopt`` . For specific examples, please refer to API code examples. Args: obj(Object) : The object to be saved. path(str|BytesIO) : The path/buffer of the object to be saved. If saved in the current directory, the input path string will be used as the file name. protocol(int, optional): The protocol version of pickle module must be greater than 1 and less than 5. Default: 4 **configs(dict, optional): optional keyword arguments. The following options are currently supported: use_binary_format(bool): When the saved object is static graph variable, you can specify ``use_binary_for_var``. If True, save the file in the c++ binary format when saving a single static graph variable; otherwise, save it in pickle format. Default: False Returns: None Examples: .. code-block:: python # example 1: dynamic graph import paddle emb = paddle.nn.Embedding(10, 10) layer_state_dict = emb.state_dict() # save state_dict of emb paddle.save(layer_state_dict, "emb.pdparams") scheduler = paddle.optimizer.lr.NoamDecay( d_model=0.01, warmup_steps=100, verbose=True) adam = paddle.optimizer.Adam( learning_rate=scheduler, parameters=emb.parameters()) opt_state_dict = adam.state_dict() # save state_dict of optimizer paddle.save(opt_state_dict, "adam.pdopt") # save weight of emb paddle.save(emb.weight, "emb.weight.pdtensor") # example 2: Save multiple state_dict at the same time from paddle import nn from paddle.optimizer import Adam layer = paddle.nn.Linear(3, 4) adam = Adam(learning_rate=0.001, parameters=layer.parameters()) obj = {'model': layer.state_dict(), 'opt': adam.state_dict(), 'epoch': 100} path = 'example/model.pdparams' paddle.save(obj, path) # example 3: static graph import paddle import paddle.static as static paddle.enable_static() # create network x = paddle.static.data(name="x", shape=[None, 224], dtype='float32') z = paddle.static.nn.fc(x, 10) place = paddle.CPUPlace() exe = paddle.static.Executor(place) exe.run(paddle.static.default_startup_program()) prog = paddle.static.default_main_program() for var in prog.list_vars(): if list(var.shape) == [224, 10]: tensor = var.get_value() break # save/load tensor path_tensor = 'temp/tensor.pdtensor' paddle.save(tensor, path_tensor) # save/load state_dict path_state_dict = 'temp/model.pdparams' paddle.save(prog.state_dict("param"), path_tensor) # example 4: save program import paddle paddle.enable_static() data = paddle.static.data( name='x_static_save', shape=(None, 224), dtype='float32') y_static = z = paddle.static.nn.fc(data, 10) main_program = paddle.static.default_main_program() path = "example/main_program.pdmodel" paddle.save(main_program, path) # example 5: save object to memory from io import BytesIO import paddle from paddle.nn import Linear paddle.disable_static() linear = Linear(5, 10) state_dict = linear.state_dict() byio = BytesIO() paddle.save(state_dict, byio) tensor = paddle.randn([2, 3], dtype='float32') paddle.save(tensor, byio)
Save an object to the specified path. .. note:: Now supports saving ``state_dict`` of Layer/Optimizer, Tensor and nested structure containing Tensor, Program.
[ "Save", "an", "object", "to", "the", "specified", "path", ".", "..", "note", "::", "Now", "supports", "saving", "state_dict", "of", "Layer", "/", "Optimizer", "Tensor", "and", "nested", "structure", "containing", "Tensor", "Program", "." ]
def save(obj, path, protocol=4, **configs): ''' Save an object to the specified path. .. note:: Now supports saving ``state_dict`` of Layer/Optimizer, Tensor and nested structure containing Tensor, Program. .. note:: Different from ``paddle.jit.save``, since the save result of ``paddle.save`` is a single file, there is no need to distinguish multiple saved files by adding a suffix. The argument ``path`` of ``paddle.save`` will be directly used as the saved file name instead of a prefix. In order to unify the saved file name format, we recommend using the paddle standard suffix: 1. for ``Layer.state_dict`` , recommend to use ``.pdparams`` ; 2. for ``Optimizer.state_dict`` , recommend to use ``.pdopt`` . For specific examples, please refer to API code examples. Args: obj(Object) : The object to be saved. path(str|BytesIO) : The path/buffer of the object to be saved. If saved in the current directory, the input path string will be used as the file name. protocol(int, optional): The protocol version of pickle module must be greater than 1 and less than 5. Default: 4 **configs(dict, optional): optional keyword arguments. The following options are currently supported: use_binary_format(bool): When the saved object is static graph variable, you can specify ``use_binary_for_var``. If True, save the file in the c++ binary format when saving a single static graph variable; otherwise, save it in pickle format. Default: False Returns: None Examples: .. code-block:: python # example 1: dynamic graph import paddle emb = paddle.nn.Embedding(10, 10) layer_state_dict = emb.state_dict() # save state_dict of emb paddle.save(layer_state_dict, "emb.pdparams") scheduler = paddle.optimizer.lr.NoamDecay( d_model=0.01, warmup_steps=100, verbose=True) adam = paddle.optimizer.Adam( learning_rate=scheduler, parameters=emb.parameters()) opt_state_dict = adam.state_dict() # save state_dict of optimizer paddle.save(opt_state_dict, "adam.pdopt") # save weight of emb paddle.save(emb.weight, "emb.weight.pdtensor") # example 2: Save multiple state_dict at the same time from paddle import nn from paddle.optimizer import Adam layer = paddle.nn.Linear(3, 4) adam = Adam(learning_rate=0.001, parameters=layer.parameters()) obj = {'model': layer.state_dict(), 'opt': adam.state_dict(), 'epoch': 100} path = 'example/model.pdparams' paddle.save(obj, path) # example 3: static graph import paddle import paddle.static as static paddle.enable_static() # create network x = paddle.static.data(name="x", shape=[None, 224], dtype='float32') z = paddle.static.nn.fc(x, 10) place = paddle.CPUPlace() exe = paddle.static.Executor(place) exe.run(paddle.static.default_startup_program()) prog = paddle.static.default_main_program() for var in prog.list_vars(): if list(var.shape) == [224, 10]: tensor = var.get_value() break # save/load tensor path_tensor = 'temp/tensor.pdtensor' paddle.save(tensor, path_tensor) # save/load state_dict path_state_dict = 'temp/model.pdparams' paddle.save(prog.state_dict("param"), path_tensor) # example 4: save program import paddle paddle.enable_static() data = paddle.static.data( name='x_static_save', shape=(None, 224), dtype='float32') y_static = z = paddle.static.nn.fc(data, 10) main_program = paddle.static.default_main_program() path = "example/main_program.pdmodel" paddle.save(main_program, path) # example 5: save object to memory from io import BytesIO import paddle from paddle.nn import Linear paddle.disable_static() linear = Linear(5, 10) state_dict = linear.state_dict() byio = BytesIO() paddle.save(state_dict, byio) tensor = paddle.randn([2, 3], dtype='float32') paddle.save(tensor, byio) ''' if _is_file_path(path): # 1. input check filename = os.path.basename(path) if filename == "": raise ValueError( "The input path MUST be format of dirname/filename " "[dirname\\filename in Windows system], but received " "filename is empty string.") # 2. save object dirname = os.path.dirname(path) if dirname and not os.path.exists(dirname): os.makedirs(dirname) elif not _is_memory_buffer(path): raise ValueError( "only supports saving objects to file and `BytesIO`, but got {}". format(type(path))) config = _parse_save_config(configs) if not isinstance(config.use_binary_format, bool): raise TypeError( "Type of `use_binary_format` should be bool, but received {}.". format(type(config.use_binary_format))) if config.use_binary_format: _save_binary_var(obj, path) else: # `protocol` need to be used, `pickle_protocol` is a deprecated arg. if config.pickle_protocol is not None: protocol = config.pickle_protocol warnings.warn( "'pickle_protocol' is a deprecated argument. Please use 'protocol' instead." ) if isinstance(obj, Program): obj.desc.flush() with _open_file_buffer(path, "wb") as f: f.write(obj.desc.serialize_to_string()) elif _is_state_dict(obj): if in_dygraph_mode(): _legacy_save(obj, path, protocol) else: _legacy_static_save(obj, path, protocol) else: with _open_file_buffer(path, 'wb') as f: _pickle_save(obj, f, protocol)
[ "def", "save", "(", "obj", ",", "path", ",", "protocol", "=", "4", ",", "*", "*", "configs", ")", ":", "if", "_is_file_path", "(", "path", ")", ":", "# 1. input check", "filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "f...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/framework/io.py#L553-L718
epiqc/ScaffCC
66a79944ee4cd116b27bc1a69137276885461db8
llvm/bindings/python/llvm/core.py
python
MemoryBuffer.__init__
(self, filename=None)
Create a new memory buffer. Currently, we support creating from the contents of a file at the specified filename.
Create a new memory buffer.
[ "Create", "a", "new", "memory", "buffer", "." ]
def __init__(self, filename=None): """Create a new memory buffer. Currently, we support creating from the contents of a file at the specified filename. """ if filename is None: raise Exception("filename argument must be defined") memory = c_object_p() out = c_char_p(None) result = lib.LLVMCreateMemoryBufferWithContentsOfFile(filename, byref(memory), byref(out)) if result: raise Exception("Could not create memory buffer: %s" % out.value) LLVMObject.__init__(self, memory, disposer=lib.LLVMDisposeMemoryBuffer)
[ "def", "__init__", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "raise", "Exception", "(", "\"filename argument must be defined\"", ")", "memory", "=", "c_object_p", "(", ")", "out", "=", "c_char_p", "(", "None", ...
https://github.com/epiqc/ScaffCC/blob/66a79944ee4cd116b27bc1a69137276885461db8/llvm/bindings/python/llvm/core.py#L151-L169
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/lib-tk/turtle.py
python
ScrolledCanvas.unbind
(self, *args, **kwargs)
'forward' method, which canvas itself has inherited...
'forward' method, which canvas itself has inherited...
[ "forward", "method", "which", "canvas", "itself", "has", "inherited", "..." ]
def unbind(self, *args, **kwargs): """ 'forward' method, which canvas itself has inherited... """ self._canvas.unbind(*args, **kwargs)
[ "def", "unbind", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_canvas", ".", "unbind", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/lib-tk/turtle.py#L442-L445
RLBot/RLBot
34332b12cf158b3ef8dbf174ae67c53683368a9d
src/legacy/python/legacy_gui/rlbot_legacy_gui/index_manager.py
python
IndexManager.has_free_slots
(self)
return next(filterfalse(self.numbers.__contains__, count(1))) < self.size
Checks if there is a free value smaller than self.size :return: True if there is a free value, False if not
Checks if there is a free value smaller than self.size :return: True if there is a free value, False if not
[ "Checks", "if", "there", "is", "a", "free", "value", "smaller", "than", "self", ".", "size", ":", "return", ":", "True", "if", "there", "is", "a", "free", "value", "False", "if", "not" ]
def has_free_slots(self): """ Checks if there is a free value smaller than self.size :return: True if there is a free value, False if not """ return next(filterfalse(self.numbers.__contains__, count(1))) < self.size
[ "def", "has_free_slots", "(", "self", ")", ":", "return", "next", "(", "filterfalse", "(", "self", ".", "numbers", ".", "__contains__", ",", "count", "(", "1", ")", ")", ")", "<", "self", ".", "size" ]
https://github.com/RLBot/RLBot/blob/34332b12cf158b3ef8dbf174ae67c53683368a9d/src/legacy/python/legacy_gui/rlbot_legacy_gui/index_manager.py#L32-L37
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py
python
MaskedArray.sort
(self, axis= -1, kind='quicksort', order=None, endwith=True, fill_value=None)
return
Sort the array, in-place Parameters ---------- a : array_like Array to be sorted. axis : int, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {'quicksort', 'mergesort', 'heapsort'}, optional Sorting algorithm. Default is 'quicksort'. order : list, optional When `a` is a structured array, this argument specifies which fields to compare first, second, and so on. This list does not need to include all of the fields. endwith : {True, False}, optional Whether missing values (if any) should be forced in the upper indices (at the end of the array) (True) or lower indices (at the beginning). fill_value : {var}, optional Value used internally for the masked values. If ``fill_value`` is not None, it supersedes ``endwith``. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- ndarray.sort : Method to sort an array in-place. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. searchsorted : Find elements in a sorted array. Notes ----- See ``sort`` for notes on the different sorting algorithms. Examples -------- >>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Default >>> a.sort() >>> print a [1 3 5 -- --] >>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Put missing values in the front >>> a.sort(endwith=False) >>> print a [-- -- 1 3 5] >>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # fill_value takes over endwith >>> a.sort(endwith=False, fill_value=3) >>> print a [1 -- -- 3 5]
Sort the array, in-place
[ "Sort", "the", "array", "in", "-", "place" ]
def sort(self, axis= -1, kind='quicksort', order=None, endwith=True, fill_value=None): """ Sort the array, in-place Parameters ---------- a : array_like Array to be sorted. axis : int, optional Axis along which to sort. If None, the array is flattened before sorting. The default is -1, which sorts along the last axis. kind : {'quicksort', 'mergesort', 'heapsort'}, optional Sorting algorithm. Default is 'quicksort'. order : list, optional When `a` is a structured array, this argument specifies which fields to compare first, second, and so on. This list does not need to include all of the fields. endwith : {True, False}, optional Whether missing values (if any) should be forced in the upper indices (at the end of the array) (True) or lower indices (at the beginning). fill_value : {var}, optional Value used internally for the masked values. If ``fill_value`` is not None, it supersedes ``endwith``. Returns ------- sorted_array : ndarray Array of the same type and shape as `a`. See Also -------- ndarray.sort : Method to sort an array in-place. argsort : Indirect sort. lexsort : Indirect stable sort on multiple keys. searchsorted : Find elements in a sorted array. Notes ----- See ``sort`` for notes on the different sorting algorithms. Examples -------- >>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Default >>> a.sort() >>> print a [1 3 5 -- --] >>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # Put missing values in the front >>> a.sort(endwith=False) >>> print a [-- -- 1 3 5] >>> a = ma.array([1, 2, 5, 4, 3],mask=[0, 1, 0, 1, 0]) >>> # fill_value takes over endwith >>> a.sort(endwith=False, fill_value=3) >>> print a [1 -- -- 3 5] """ if self._mask is nomask: ndarray.sort(self, axis=axis, kind=kind, order=order) else: if self is masked: return self if fill_value is None: if endwith: filler = minimum_fill_value(self) else: filler = maximum_fill_value(self) else: filler = fill_value idx = np.indices(self.shape) idx[axis] = self.filled(filler).argsort(axis=axis, kind=kind, order=order) idx_l = idx.tolist() tmp_mask = self._mask[idx_l].flat tmp_data = self._data[idx_l].flat self._data.flat = tmp_data self._mask.flat = tmp_mask return
[ "def", "sort", "(", "self", ",", "axis", "=", "-", "1", ",", "kind", "=", "'quicksort'", ",", "order", "=", "None", ",", "endwith", "=", "True", ",", "fill_value", "=", "None", ")", ":", "if", "self", ".", "_mask", "is", "nomask", ":", "ndarray", ...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py#L5000-L5082
nsnam/ns-3-dev-git
efdb2e21f45c0a87a60b47c547b68fa140a7b686
src/visualizer/visualizer/ipython_view.py
python
ConsoleView.onKeyPress
(self, widget, event)
return self.onKeyPressExtend(event)
! Key press callback used for correcting behavior for console-like interfaces. For example 'home' should go to prompt, not to beginning of line. @param widget: Widget that key press accored in. @param event: Event object @return Return True if event should not trickle.
! Key press callback used for correcting behavior for console-like interfaces. For example 'home' should go to prompt, not to beginning of line.
[ "!", "Key", "press", "callback", "used", "for", "correcting", "behavior", "for", "console", "-", "like", "interfaces", ".", "For", "example", "home", "should", "go", "to", "prompt", "not", "to", "beginning", "of", "line", "." ]
def onKeyPress(self, widget, event): """! Key press callback used for correcting behavior for console-like interfaces. For example 'home' should go to prompt, not to beginning of line. @param widget: Widget that key press accored in. @param event: Event object @return Return True if event should not trickle. """ insert_mark = self.text_buffer.get_insert() insert_iter = self.text_buffer.get_iter_at_mark(insert_mark) selection_mark = self.text_buffer.get_selection_bound() selection_iter = self.text_buffer.get_iter_at_mark(selection_mark) start_iter = self.text_buffer.get_iter_at_mark(self.line_start) if event.keyval == Gdk.KEY_Home: if event.get_state() & Gdk.ModifierType.CONTROL_MASK or event.get_state() & Gdk.ModifierType.MOD1_MASK: pass elif event.get_state() & Gdk.ModifierType.SHIFT_MASK: self.text_buffer.move_mark(insert_mark, start_iter) return True else: self.text_buffer.place_cursor(start_iter) return True elif event.keyval == Gdk.KEY_Left: insert_iter.backward_cursor_position() if not insert_iter.editable(True): return True elif not event.string: pass elif start_iter.compare(insert_iter) <= 0 and \ start_iter.compare(selection_iter) <= 0: pass elif start_iter.compare(insert_iter) > 0 and \ start_iter.compare(selection_iter) > 0: self.text_buffer.place_cursor(start_iter) elif insert_iter.compare(selection_iter) < 0: self.text_buffer.move_mark(insert_mark, start_iter) elif insert_iter.compare(selection_iter) > 0: self.text_buffer.move_mark(selection_mark, start_iter) return self.onKeyPressExtend(event)
[ "def", "onKeyPress", "(", "self", ",", "widget", ",", "event", ")", ":", "insert_mark", "=", "self", ".", "text_buffer", ".", "get_insert", "(", ")", "insert_iter", "=", "self", ".", "text_buffer", ".", "get_iter_at_mark", "(", "insert_mark", ")", "selection...
https://github.com/nsnam/ns-3-dev-git/blob/efdb2e21f45c0a87a60b47c547b68fa140a7b686/src/visualizer/visualizer/ipython_view.py#L515-L556
synfig/synfig
a5ec91db5b751dc12e4400ccfb5c063fd6d2d928
synfig-studio/plugins/lottie-exporter/common/Hermite.py
python
Hermite.find_distance
(self, r, s, steps = 7)
return ret
https://github.com/synfig/synfig/blob/15607089680af560ad031465d31878425af927eb/ETL/ETL/_bezier.h#L577 Args: r (float) : Time type s (float) : Time type Returns: (float) : The distance according to the Synfig link
https://github.com/synfig/synfig/blob/15607089680af560ad031465d31878425af927eb/ETL/ETL/_bezier.h#L577
[ "https", ":", "//", "github", ".", "com", "/", "synfig", "/", "synfig", "/", "blob", "/", "15607089680af560ad031465d31878425af927eb", "/", "ETL", "/", "ETL", "/", "_bezier", ".", "h#L577" ]
def find_distance(self, r, s, steps = 7): """ https://github.com/synfig/synfig/blob/15607089680af560ad031465d31878425af927eb/ETL/ETL/_bezier.h#L577 Args: r (float) : Time type s (float) : Time type Returns: (float) : The distance according to the Synfig link """ inc = (s - r) / steps if not inc: return 0 ret = 0.0 last = self.single_operator(r) r += inc while r < s: n = self.single_operator(r) ret += self.uncook(self.double_operator(last, n)) last = n r += inc ret += self.uncook(self.double_operator(last, self.single_operator(r)))*(s-(r-inc))/inc return ret
[ "def", "find_distance", "(", "self", ",", "r", ",", "s", ",", "steps", "=", "7", ")", ":", "inc", "=", "(", "s", "-", "r", ")", "/", "steps", "if", "not", "inc", ":", "return", "0", "ret", "=", "0.0", "last", "=", "self", ".", "single_operator"...
https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/common/Hermite.py#L85-L111
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/linked-list-in-binary-tree.py
python
Solution2.isSubPath
(self, head, root)
return dfs(head, root) or \ self.isSubPath(head, root.left) or \ self.isSubPath(head, root.right)
:type head: ListNode :type root: TreeNode :rtype: bool
:type head: ListNode :type root: TreeNode :rtype: bool
[ ":", "type", "head", ":", "ListNode", ":", "type", "root", ":", "TreeNode", ":", "rtype", ":", "bool" ]
def isSubPath(self, head, root): """ :type head: ListNode :type root: TreeNode :rtype: bool """ def dfs(head, root): if not head: return True if not root: return False return root.val == head.val and \ (dfs(head.next, root.left) or dfs(head.next, root.right)) if not head: return True if not root: return False return dfs(head, root) or \ self.isSubPath(head, root.left) or \ self.isSubPath(head, root.right)
[ "def", "isSubPath", "(", "self", ",", "head", ",", "root", ")", ":", "def", "dfs", "(", "head", ",", "root", ")", ":", "if", "not", "head", ":", "return", "True", "if", "not", "root", ":", "return", "False", "return", "root", ".", "val", "==", "h...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/linked-list-in-binary-tree.py#L63-L84
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py
python
Misc.winfo_geometry
(self)
return self.tk.call('winfo', 'geometry', self._w)
Return geometry string for this widget in the form "widthxheight+X+Y".
Return geometry string for this widget in the form "widthxheight+X+Y".
[ "Return", "geometry", "string", "for", "this", "widget", "in", "the", "form", "widthxheight", "+", "X", "+", "Y", "." ]
def winfo_geometry(self): """Return geometry string for this widget in the form "widthxheight+X+Y".""" return self.tk.call('winfo', 'geometry', self._w)
[ "def", "winfo_geometry", "(", "self", ")", ":", "return", "self", ".", "tk", ".", "call", "(", "'winfo'", ",", "'geometry'", ",", "self", ".", "_w", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py#L994-L996
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2.py
python
uCSIsSupplementalMathematicalOperators
(code)
return ret
Check whether the character is part of SupplementalMathematicalOperators UCS Block
Check whether the character is part of SupplementalMathematicalOperators UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "SupplementalMathematicalOperators", "UCS", "Block" ]
def uCSIsSupplementalMathematicalOperators(code): """Check whether the character is part of SupplementalMathematicalOperators UCS Block """ ret = libxml2mod.xmlUCSIsSupplementalMathematicalOperators(code) return ret
[ "def", "uCSIsSupplementalMathematicalOperators", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsSupplementalMathematicalOperators", "(", "code", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2.py#L2882-L2886
SpenceKonde/megaTinyCore
1c4a70b18a149fe6bcb551dfa6db11ca50b8997b
megaavr/tools/libs/pymcuprog/serialupdi/application.py
python
UpdiApplication.unlock
(self)
Unlock by chip erase
Unlock by chip erase
[ "Unlock", "by", "chip", "erase" ]
def unlock(self): """ Unlock by chip erase """ # Put in the key self.readwrite.write_key(constants.UPDI_KEY_64, constants.UPDI_KEY_CHIPERASE) # Check key status key_status = self.readwrite.read_cs(constants.UPDI_ASI_KEY_STATUS) self.logger.debug("Key status = 0x%02X", key_status) if not key_status & (1 << constants.UPDI_ASI_KEY_STATUS_CHIPERASE): raise PymcuprogError("Key not accepted") # Toggle reset self.reset(apply_reset=True) self.reset(apply_reset=False) # And wait for unlock if not self.wait_unlocked(100): raise PymcuprogError("Failed to chip erase using key")
[ "def", "unlock", "(", "self", ")", ":", "# Put in the key", "self", ".", "readwrite", ".", "write_key", "(", "constants", ".", "UPDI_KEY_64", ",", "constants", ".", "UPDI_KEY_CHIPERASE", ")", "# Check key status", "key_status", "=", "self", ".", "readwrite", "."...
https://github.com/SpenceKonde/megaTinyCore/blob/1c4a70b18a149fe6bcb551dfa6db11ca50b8997b/megaavr/tools/libs/pymcuprog/serialupdi/application.py#L189-L209
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
FileTypeInfo.IsValid
(*args, **kwargs)
return _misc_.FileTypeInfo_IsValid(*args, **kwargs)
IsValid(self) -> bool
IsValid(self) -> bool
[ "IsValid", "(", "self", ")", "-", ">", "bool" ]
def IsValid(*args, **kwargs): """IsValid(self) -> bool""" return _misc_.FileTypeInfo_IsValid(*args, **kwargs)
[ "def", "IsValid", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "FileTypeInfo_IsValid", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L2503-L2505
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_misc.py
python
MutexGuiEnter
(*args)
return _misc_.MutexGuiEnter(*args)
MutexGuiEnter()
MutexGuiEnter()
[ "MutexGuiEnter", "()" ]
def MutexGuiEnter(*args): """MutexGuiEnter()""" return _misc_.MutexGuiEnter(*args)
[ "def", "MutexGuiEnter", "(", "*", "args", ")", ":", "return", "_misc_", ".", "MutexGuiEnter", "(", "*", "args", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_misc.py#L631-L633
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/random.py
python
SystemRandom.random
(self)
return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
Get the next random number in the range [0.0, 1.0).
Get the next random number in the range [0.0, 1.0).
[ "Get", "the", "next", "random", "number", "in", "the", "range", "[", "0", ".", "0", "1", ".", "0", ")", "." ]
def random(self): """Get the next random number in the range [0.0, 1.0).""" return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
[ "def", "random", "(", "self", ")", ":", "return", "(", "long", "(", "_hexlify", "(", "_urandom", "(", "7", ")", ")", ",", "16", ")", ">>", "3", ")", "*", "RECIP_BPF" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/random.py#L815-L817
openmm/openmm
cb293447c4fc8b03976dfe11399f107bab70f3d9
wrappers/python/openmm/app/pdbfile.py
python
PDBFile.getPositions
(self, asNumpy=False, frame=0)
return self._positions[frame]
Get the atomic positions. Parameters ---------- asNumpy : boolean=False if true, the values are returned as a numpy array instead of a list of Vec3s frame : int=0 the index of the frame for which to get positions
Get the atomic positions.
[ "Get", "the", "atomic", "positions", "." ]
def getPositions(self, asNumpy=False, frame=0): """Get the atomic positions. Parameters ---------- asNumpy : boolean=False if true, the values are returned as a numpy array instead of a list of Vec3s frame : int=0 the index of the frame for which to get positions """ if asNumpy: if self._numpyPositions is None: self._numpyPositions = [None]*len(self._positions) if self._numpyPositions[frame] is None: self._numpyPositions[frame] = Quantity(numpy.array(self._positions[frame].value_in_unit(nanometers)), nanometers) return self._numpyPositions[frame] return self._positions[frame]
[ "def", "getPositions", "(", "self", ",", "asNumpy", "=", "False", ",", "frame", "=", "0", ")", ":", "if", "asNumpy", ":", "if", "self", ".", "_numpyPositions", "is", "None", ":", "self", ".", "_numpyPositions", "=", "[", "None", "]", "*", "len", "(",...
https://github.com/openmm/openmm/blob/cb293447c4fc8b03976dfe11399f107bab70f3d9/wrappers/python/openmm/app/pdbfile.py#L209-L226
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
grc/core/utils/expr_utils.py
python
_sort_variables
(exprs)
return reversed(sorted_vars)
Get a list of variables in order of dependencies. Args: exprs: a mapping of variable name to expression Returns: a list of variable names @throws Exception circular dependencies
Get a list of variables in order of dependencies.
[ "Get", "a", "list", "of", "variables", "in", "order", "of", "dependencies", "." ]
def _sort_variables(exprs): """ Get a list of variables in order of dependencies. Args: exprs: a mapping of variable name to expression Returns: a list of variable names @throws Exception circular dependencies """ var_graph = _get_graph(exprs) sorted_vars = list() # Determine dependency order while var_graph.get_nodes(): # Get a list of nodes with no edges indep_vars = [var for var in var_graph.get_nodes() if not var_graph.get_edges(var)] if not indep_vars: raise Exception('circular dependency caught in sort_variables') # Add the indep vars to the end of the list sorted_vars.extend(sorted(indep_vars)) # Remove each edge-less node from the graph for var in indep_vars: var_graph.remove_node(var) return reversed(sorted_vars)
[ "def", "_sort_variables", "(", "exprs", ")", ":", "var_graph", "=", "_get_graph", "(", "exprs", ")", "sorted_vars", "=", "list", "(", ")", "# Determine dependency order", "while", "var_graph", ".", "get_nodes", "(", ")", ":", "# Get a list of nodes with no edges", ...
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/core/utils/expr_utils.py#L189-L214