nwo stringlengths 5 106 | sha stringlengths 40 40 | path stringlengths 4 174 | language stringclasses 1
value | identifier stringlengths 1 140 | parameters stringlengths 0 87.7k | argument_list stringclasses 1
value | return_statement stringlengths 0 426k | docstring stringlengths 0 64.3k | docstring_summary stringlengths 0 26.3k | docstring_tokens list | function stringlengths 18 4.83M | function_tokens list | url stringlengths 83 304 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jgagneastro/coffeegrindsize | 22661ebd21831dba4cf32bfc6ba59fe3d49f879c | App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/projections/polar.py | python | PolarAxes.can_zoom | (self) | return False | Return *True* if this axes supports the zoom box button functionality.
Polar axes do not support zoom boxes. | Return *True* if this axes supports the zoom box button functionality. | [
"Return",
"*",
"True",
"*",
"if",
"this",
"axes",
"supports",
"the",
"zoom",
"box",
"button",
"functionality",
"."
] | def can_zoom(self):
"""
Return *True* if this axes supports the zoom box button functionality.
Polar axes do not support zoom boxes.
"""
return False | [
"def",
"can_zoom",
"(",
"self",
")",
":",
"return",
"False"
] | https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/matplotlib/projections/polar.py#L1349-L1355 | |
jessemelpolio/Faster_RCNN_for_DOTA | 499b32c3893ccd8850e0aca07e5afb952d08943e | lib/utils/load_model.py | python | load_checkpoint | (prefix, epoch) | return arg_params, aux_params | Load model checkpoint from file.
:param prefix: Prefix of model name.
:param epoch: Epoch number of model we would like to load.
:return: (arg_params, aux_params)
arg_params : dict of str to NDArray
Model parameter, dict of name to NDArray of net's weights.
aux_params : dict of str to NDArray
Model parameter, dict of name to NDArray of net's auxiliary states. | Load model checkpoint from file.
:param prefix: Prefix of model name.
:param epoch: Epoch number of model we would like to load.
:return: (arg_params, aux_params)
arg_params : dict of str to NDArray
Model parameter, dict of name to NDArray of net's weights.
aux_params : dict of str to NDArray
Model parameter, dict of name to NDArray of net's auxiliary states. | [
"Load",
"model",
"checkpoint",
"from",
"file",
".",
":",
"param",
"prefix",
":",
"Prefix",
"of",
"model",
"name",
".",
":",
"param",
"epoch",
":",
"Epoch",
"number",
"of",
"model",
"we",
"would",
"like",
"to",
"load",
".",
":",
"return",
":",
"(",
"a... | def load_checkpoint(prefix, epoch):
"""
Load model checkpoint from file.
:param prefix: Prefix of model name.
:param epoch: Epoch number of model we would like to load.
:return: (arg_params, aux_params)
arg_params : dict of str to NDArray
Model parameter, dict of name to NDArray of net's weights.
aux_params : dict of str to NDArray
Model parameter, dict of name to NDArray of net's auxiliary states.
"""
save_dict = mx.nd.load('%s-%04d.params' % (prefix, epoch))
arg_params = {}
aux_params = {}
for k, v in save_dict.items():
tp, name = k.split(':', 1)
if tp == 'arg':
arg_params[name] = v
if tp == 'aux':
aux_params[name] = v
return arg_params, aux_params | [
"def",
"load_checkpoint",
"(",
"prefix",
",",
"epoch",
")",
":",
"save_dict",
"=",
"mx",
".",
"nd",
".",
"load",
"(",
"'%s-%04d.params'",
"%",
"(",
"prefix",
",",
"epoch",
")",
")",
"arg_params",
"=",
"{",
"}",
"aux_params",
"=",
"{",
"}",
"for",
"k"... | https://github.com/jessemelpolio/Faster_RCNN_for_DOTA/blob/499b32c3893ccd8850e0aca07e5afb952d08943e/lib/utils/load_model.py#L4-L24 | |
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/IronPython/27/Lib/lib2to3/refactor.py | python | RefactoringTool.get_fixers | (self) | return (pre_order_fixers, post_order_fixers) | Inspects the options to load the requested patterns and handlers.
Returns:
(pre_order, post_order), where pre_order is the list of fixers that
want a pre-order AST traversal, and post_order is the list that want
post-order traversal. | Inspects the options to load the requested patterns and handlers. | [
"Inspects",
"the",
"options",
"to",
"load",
"the",
"requested",
"patterns",
"and",
"handlers",
"."
] | def get_fixers(self):
"""Inspects the options to load the requested patterns and handlers.
Returns:
(pre_order, post_order), where pre_order is the list of fixers that
want a pre-order AST traversal, and post_order is the list that want
post-order traversal.
"""
pre_order_fixers = []
post_order_fixers = []
for fix_mod_path in self.fixers:
mod = __import__(fix_mod_path, {}, {}, ["*"])
fix_name = fix_mod_path.rsplit(".", 1)[-1]
if fix_name.startswith(self.FILE_PREFIX):
fix_name = fix_name[len(self.FILE_PREFIX):]
parts = fix_name.split("_")
class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts])
try:
fix_class = getattr(mod, class_name)
except AttributeError:
raise FixerError("Can't find %s.%s" % (fix_name, class_name))
fixer = fix_class(self.options, self.fixer_log)
if fixer.explicit and self.explicit is not True and \
fix_mod_path not in self.explicit:
self.log_message("Skipping optional fixer: %s", fix_name)
continue
self.log_debug("Adding transformation: %s", fix_name)
if fixer.order == "pre":
pre_order_fixers.append(fixer)
elif fixer.order == "post":
post_order_fixers.append(fixer)
else:
raise FixerError("Illegal fixer order: %r" % fixer.order)
key_func = operator.attrgetter("run_order")
pre_order_fixers.sort(key=key_func)
post_order_fixers.sort(key=key_func)
return (pre_order_fixers, post_order_fixers) | [
"def",
"get_fixers",
"(",
"self",
")",
":",
"pre_order_fixers",
"=",
"[",
"]",
"post_order_fixers",
"=",
"[",
"]",
"for",
"fix_mod_path",
"in",
"self",
".",
"fixers",
":",
"mod",
"=",
"__import__",
"(",
"fix_mod_path",
",",
"{",
"}",
",",
"{",
"}",
","... | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/lib2to3/refactor.py#L234-L272 | |
microsoft/RepPoints | 22cc39c9b57e1315ebbf9e2307edcc1fdcb448c4 | src/reppoints_generator/point_target.py | python | unmap | (data, count, inds, fill=0) | return ret | Unmap a subset of item (data) back to the original set of items (of
size count) | Unmap a subset of item (data) back to the original set of items (of
size count) | [
"Unmap",
"a",
"subset",
"of",
"item",
"(",
"data",
")",
"back",
"to",
"the",
"original",
"set",
"of",
"items",
"(",
"of",
"size",
"count",
")"
] | def unmap(data, count, inds, fill=0):
""" Unmap a subset of item (data) back to the original set of items (of
size count) """
if data.dim() == 1:
ret = data.new_full((count, ), fill)
ret[inds] = data
else:
new_size = (count, ) + data.size()[1:]
ret = data.new_full(new_size, fill)
ret[inds, :] = data
return ret | [
"def",
"unmap",
"(",
"data",
",",
"count",
",",
"inds",
",",
"fill",
"=",
"0",
")",
":",
"if",
"data",
".",
"dim",
"(",
")",
"==",
"1",
":",
"ret",
"=",
"data",
".",
"new_full",
"(",
"(",
"count",
",",
")",
",",
"fill",
")",
"ret",
"[",
"in... | https://github.com/microsoft/RepPoints/blob/22cc39c9b57e1315ebbf9e2307edcc1fdcb448c4/src/reppoints_generator/point_target.py#L155-L165 | |
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/xml/etree/ElementTree.py | python | ElementTree.iterfind | (self, path, namespaces=None) | return self._root.iterfind(path, namespaces) | Find all matching subelements by tag name or path.
Same as getroot().iterfind(path), which is element.iterfind()
*path* is a string having either an element tag or an XPath,
*namespaces* is an optional mapping from namespace prefix to full name.
Return an iterable yielding all matching elements in document order. | Find all matching subelements by tag name or path. | [
"Find",
"all",
"matching",
"subelements",
"by",
"tag",
"name",
"or",
"path",
"."
] | def iterfind(self, path, namespaces=None):
"""Find all matching subelements by tag name or path.
Same as getroot().iterfind(path), which is element.iterfind()
*path* is a string having either an element tag or an XPath,
*namespaces* is an optional mapping from namespace prefix to full name.
Return an iterable yielding all matching elements in document order.
"""
# assert self._root is not None
if path[:1] == "/":
path = "." + path
warnings.warn(
"This search is broken in 1.3 and earlier, and will be "
"fixed in a future version. If you rely on the current "
"behaviour, change it to %r" % path,
FutureWarning, stacklevel=2
)
return self._root.iterfind(path, namespaces) | [
"def",
"iterfind",
"(",
"self",
",",
"path",
",",
"namespaces",
"=",
"None",
")",
":",
"# assert self._root is not None",
"if",
"path",
"[",
":",
"1",
"]",
"==",
"\"/\"",
":",
"path",
"=",
"\".\"",
"+",
"path",
"warnings",
".",
"warn",
"(",
"\"This searc... | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/xml/etree/ElementTree.py#L671-L691 | |
gnome-terminator/terminator | ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1 | terminatorlib/ipc.py | python | DBusService.set_tab_title | (self, uuid=None, options=dbus.Dictionary()) | Set the title of a parent tab of a given terminal | Set the title of a parent tab of a given terminal | [
"Set",
"the",
"title",
"of",
"a",
"parent",
"tab",
"of",
"a",
"given",
"terminal"
] | def set_tab_title(self, uuid=None, options=dbus.Dictionary()):
"""Set the title of a parent tab of a given terminal"""
tab_title = options.get('tab-title')
maker = Factory()
terminal = self.terminator.find_terminal_by_uuid(uuid)
window = terminal.get_toplevel()
if not window.is_child_notebook():
return
notebook = window.get_children()[0]
n_page = notebook.get_current_page()
page = notebook.get_nth_page(n_page)
label = notebook.get_tab_label(page)
label.set_custom_label(tab_title, force=True) | [
"def",
"set_tab_title",
"(",
"self",
",",
"uuid",
"=",
"None",
",",
"options",
"=",
"dbus",
".",
"Dictionary",
"(",
")",
")",
":",
"tab_title",
"=",
"options",
".",
"get",
"(",
"'tab-title'",
")",
"maker",
"=",
"Factory",
"(",
")",
"terminal",
"=",
"... | https://github.com/gnome-terminator/terminator/blob/ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1/terminatorlib/ipc.py#L288-L303 | ||
robclewley/pydstool | 939e3abc9dd1f180d35152bacbde57e24c85ff26 | PyDSTool/Toolbox/adjointPRC.py | python | rotate_phase | (pts, phase0_ix) | return pts_0 | Phase shift a pointset (assumed to be a cycle) about index
phase0_ix, i.e. 'rotate' it to put the point at phase0_ix at the
beginning of the pointset.
NOTE: Does not update any label info that might be attached to pts! | Phase shift a pointset (assumed to be a cycle) about index
phase0_ix, i.e. 'rotate' it to put the point at phase0_ix at the
beginning of the pointset. | [
"Phase",
"shift",
"a",
"pointset",
"(",
"assumed",
"to",
"be",
"a",
"cycle",
")",
"about",
"index",
"phase0_ix",
"i",
".",
"e",
".",
"rotate",
"it",
"to",
"put",
"the",
"point",
"at",
"phase0_ix",
"at",
"the",
"beginning",
"of",
"the",
"pointset",
"."
... | def rotate_phase(pts, phase0_ix):
"""Phase shift a pointset (assumed to be a cycle) about index
phase0_ix, i.e. 'rotate' it to put the point at phase0_ix at the
beginning of the pointset.
NOTE: Does not update any label info that might be attached to pts!
"""
assert phase0_ix > 0 and phase0_ix < len(pts), "phase 0 index out of range"
try:
t0 = pts['t'][phase0_ix]
parameterized = True
except PyDSTool_KeyError:
parameterized = False
pts_0 = pts[phase0_ix:]
if parameterized:
pts_0.indepvararray -= t0
pts_1 = pts[:phase0_ix]
if parameterized:
pts_1.indepvararray += (pts['t'][-1]-pts['t'][phase0_ix-1])
pts_0.extend(pts_1)
return pts_0 | [
"def",
"rotate_phase",
"(",
"pts",
",",
"phase0_ix",
")",
":",
"assert",
"phase0_ix",
">",
"0",
"and",
"phase0_ix",
"<",
"len",
"(",
"pts",
")",
",",
"\"phase 0 index out of range\"",
"try",
":",
"t0",
"=",
"pts",
"[",
"'t'",
"]",
"[",
"phase0_ix",
"]",
... | https://github.com/robclewley/pydstool/blob/939e3abc9dd1f180d35152bacbde57e24c85ff26/PyDSTool/Toolbox/adjointPRC.py#L232-L252 | |
opendatacube/datacube-core | b062184be61c140a168de94510bc3661748f112e | datacube/utils/geometry/_base.py | python | CRS.units | (self) | List of dimension units of the CRS.
The ordering of the units is intended to reflect the `numpy` array axis order of the loaded raster. | List of dimension units of the CRS.
The ordering of the units is intended to reflect the `numpy` array axis order of the loaded raster. | [
"List",
"of",
"dimension",
"units",
"of",
"the",
"CRS",
".",
"The",
"ordering",
"of",
"the",
"units",
"is",
"intended",
"to",
"reflect",
"the",
"numpy",
"array",
"axis",
"order",
"of",
"the",
"loaded",
"raster",
"."
] | def units(self) -> Tuple[str, str]:
"""
List of dimension units of the CRS.
The ordering of the units is intended to reflect the `numpy` array axis order of the loaded raster.
"""
if self.geographic:
return 'degrees_north', 'degrees_east'
if self.projected:
x, y = self._crs.axis_info
return x.unit_name, y.unit_name
raise ValueError('Neither projected nor geographic') | [
"def",
"units",
"(",
"self",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"if",
"self",
".",
"geographic",
":",
"return",
"'degrees_north'",
",",
"'degrees_east'",
"if",
"self",
".",
"projected",
":",
"x",
",",
"y",
"=",
"self",
".",
"_crs",... | https://github.com/opendatacube/datacube-core/blob/b062184be61c140a168de94510bc3661748f112e/datacube/utils/geometry/_base.py#L242-L254 | ||
twilio/twilio-python | 6e1e811ea57a1edfadd5161ace87397c563f6915 | twilio/rest/taskrouter/v1/workspace/workspace_statistics.py | python | WorkspaceStatisticsInstance.__repr__ | (self) | return '<Twilio.Taskrouter.V1.WorkspaceStatisticsInstance {}>'.format(context) | Provide a friendly representation
:returns: Machine friendly representation
:rtype: str | Provide a friendly representation | [
"Provide",
"a",
"friendly",
"representation"
] | def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Taskrouter.V1.WorkspaceStatisticsInstance {}>'.format(context) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"context",
"=",
"' '",
".",
"join",
"(",
"'{}={}'",
".",
"format",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_solution",
".",
"items",
"(",
")",
")",
"return",
"'<Twilio.Taskrouter.... | https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py#L268-L276 | |
bikalims/bika.lims | 35e4bbdb5a3912cae0b5eb13e51097c8b0486349 | bika/lims/browser/contact.py | python | ContactLoginDetailsView.linkable_users | (self) | return out | Search Plone users which are not linked to a contact | Search Plone users which are not linked to a contact | [
"Search",
"Plone",
"users",
"which",
"are",
"not",
"linked",
"to",
"a",
"contact"
] | def linkable_users(self):
"""Search Plone users which are not linked to a contact
"""
# We make use of the existing controlpanel `@@usergroup-userprefs` view
# logic to make sure we get all users from all plugins (e.g. LDAP)
users_view = UsersOverviewControlPanel(self.context, self.request)
users = users_view.doSearch("")
out = []
for user in users:
userid = user.get("id", None)
if userid is None:
continue
# Skip users which are already linked to a Contact
contact = Contact.getContactByUsername(userid)
labcontact = LabContact.getContactByUsername(userid)
if contact or labcontact:
continue
userdata = {
"userid": userid,
"email": user.get("email"),
"fullname": user.get("title"),
}
# filter out users which do not match the searchstring
if self.searchstring:
s = self.searchstring.lower()
if not any(map(lambda v: re.search(s, str(v).lower()), userdata.values())):
continue
# update data (maybe for later use)
userdata.update(user)
# Append the userdata for the results
out.append(userdata)
out.sort(lambda x, y: cmp(x["fullname"], y["fullname"]))
return out | [
"def",
"linkable_users",
"(",
"self",
")",
":",
"# We make use of the existing controlpanel `@@usergroup-userprefs` view",
"# logic to make sure we get all users from all plugins (e.g. LDAP)",
"users_view",
"=",
"UsersOverviewControlPanel",
"(",
"self",
".",
"context",
",",
"self",
... | https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/browser/contact.py#L93-L136 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_hxb2/lib/python3.5/site-packages/pip/_vendor/pkg_resources/__init__.py | python | ResourceManager.resource_filename | (self, package_or_requirement, resource_name) | return get_provider(package_or_requirement).get_resource_filename(
self, resource_name
) | Return a true filesystem path for specified resource | Return a true filesystem path for specified resource | [
"Return",
"a",
"true",
"filesystem",
"path",
"for",
"specified",
"resource"
] | def resource_filename(self, package_or_requirement, resource_name):
"""Return a true filesystem path for specified resource"""
return get_provider(package_or_requirement).get_resource_filename(
self, resource_name
) | [
"def",
"resource_filename",
"(",
"self",
",",
"package_or_requirement",
",",
"resource_name",
")",
":",
"return",
"get_provider",
"(",
"package_or_requirement",
")",
".",
"get_resource_filename",
"(",
"self",
",",
"resource_name",
")"
] | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/pip/_vendor/pkg_resources/__init__.py#L1200-L1204 | |
rdiff-backup/rdiff-backup | 321e0cd6e5e47d4c158a0172e47ab38240a8b653 | src/rdiffbackup/locations/_repo_shadow.py | python | _CacheCollatedPostProcess.__next__ | (self) | return source_rorp, dest_rorp | Return next (source_rorp, dest_rorp) pair. StopIteration passed | Return next (source_rorp, dest_rorp) pair. StopIteration passed | [
"Return",
"next",
"(",
"source_rorp",
"dest_rorp",
")",
"pair",
".",
"StopIteration",
"passed"
] | def __next__(self):
"""Return next (source_rorp, dest_rorp) pair. StopIteration passed"""
source_rorp, dest_rorp = next(self.iter)
self._pre_process(source_rorp, dest_rorp)
index = source_rorp and source_rorp.index or dest_rorp.index
self.cache_dict[index] = [source_rorp, dest_rorp, 0, 0, None]
self.cache_indices.append(index)
if len(self.cache_indices) > self.cache_size:
self._shorten_cache()
return source_rorp, dest_rorp | [
"def",
"__next__",
"(",
"self",
")",
":",
"source_rorp",
",",
"dest_rorp",
"=",
"next",
"(",
"self",
".",
"iter",
")",
"self",
".",
"_pre_process",
"(",
"source_rorp",
",",
"dest_rorp",
")",
"index",
"=",
"source_rorp",
"and",
"source_rorp",
".",
"index",
... | https://github.com/rdiff-backup/rdiff-backup/blob/321e0cd6e5e47d4c158a0172e47ab38240a8b653/src/rdiffbackup/locations/_repo_shadow.py#L1112-L1122 | |
uqfoundation/multiprocess | 028cc73f02655e6451d92e5147d19d8c10aebe50 | py3.3/multiprocess/util.py | python | get_logger | () | return _logger | Returns logger used by multiprocessing | Returns logger used by multiprocessing | [
"Returns",
"logger",
"used",
"by",
"multiprocessing"
] | def get_logger():
'''
Returns logger used by multiprocessing
'''
global _logger
import logging
logging._acquireLock()
try:
if not _logger:
_logger = logging.getLogger(LOGGER_NAME)
_logger.propagate = 0
logging.addLevelName(SUBDEBUG, 'SUBDEBUG')
logging.addLevelName(SUBWARNING, 'SUBWARNING')
# XXX multiprocessing should cleanup before logging
if hasattr(atexit, 'unregister'):
atexit.unregister(_exit_function)
atexit.register(_exit_function)
else:
atexit._exithandlers.remove((_exit_function, (), {}))
atexit._exithandlers.append((_exit_function, (), {}))
finally:
logging._releaseLock()
return _logger | [
"def",
"get_logger",
"(",
")",
":",
"global",
"_logger",
"import",
"logging",
"logging",
".",
"_acquireLock",
"(",
")",
"try",
":",
"if",
"not",
"_logger",
":",
"_logger",
"=",
"logging",
".",
"getLogger",
"(",
"LOGGER_NAME",
")",
"_logger",
".",
"propagat... | https://github.com/uqfoundation/multiprocess/blob/028cc73f02655e6451d92e5147d19d8c10aebe50/py3.3/multiprocess/util.py#L61-L88 | |
IronLanguages/ironpython2 | 51fdedeeda15727717fb8268a805f71b06c0b9f1 | Src/StdLib/Lib/ftplib.py | python | test | () | Test program.
Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...
-d dir
-l list
-p password | Test program.
Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ... | [
"Test",
"program",
".",
"Usage",
":",
"ftp",
"[",
"-",
"d",
"]",
"[",
"-",
"r",
"[",
"file",
"]]",
"host",
"[",
"-",
"l",
"[",
"dir",
"]]",
"[",
"-",
"d",
"[",
"dir",
"]]",
"[",
"-",
"p",
"]",
"[",
"file",
"]",
"..."
] | def test():
'''Test program.
Usage: ftp [-d] [-r[file]] host [-l[dir]] [-d[dir]] [-p] [file] ...
-d dir
-l list
-p password
'''
if len(sys.argv) < 2:
print test.__doc__
sys.exit(0)
debugging = 0
rcfile = None
while sys.argv[1] == '-d':
debugging = debugging+1
del sys.argv[1]
if sys.argv[1][:2] == '-r':
# get name of alternate ~/.netrc file:
rcfile = sys.argv[1][2:]
del sys.argv[1]
host = sys.argv[1]
ftp = FTP(host)
ftp.set_debuglevel(debugging)
userid = passwd = acct = ''
try:
netrc = Netrc(rcfile)
except IOError:
if rcfile is not None:
sys.stderr.write("Could not open account file"
" -- using anonymous login.")
else:
try:
userid, passwd, acct = netrc.get_account(host)
except KeyError:
# no account for host
sys.stderr.write(
"No account -- using anonymous login.")
ftp.login(userid, passwd, acct)
for file in sys.argv[2:]:
if file[:2] == '-l':
ftp.dir(file[2:])
elif file[:2] == '-d':
cmd = 'CWD'
if file[2:]: cmd = cmd + ' ' + file[2:]
resp = ftp.sendcmd(cmd)
elif file == '-p':
ftp.set_pasv(not ftp.passiveserver)
else:
ftp.retrbinary('RETR ' + file, \
sys.stdout.write, 1024)
ftp.quit() | [
"def",
"test",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"<",
"2",
":",
"print",
"test",
".",
"__doc__",
"sys",
".",
"exit",
"(",
"0",
")",
"debugging",
"=",
"0",
"rcfile",
"=",
"None",
"while",
"sys",
".",
"argv",
"[",
"1",
"... | https://github.com/IronLanguages/ironpython2/blob/51fdedeeda15727717fb8268a805f71b06c0b9f1/Src/StdLib/Lib/ftplib.py#L1034-L1086 | ||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/django-1.5/django/core/exceptions.py | python | ValidationError.__init__ | (self, message, code=None, params=None) | ValidationError can be passed any object that can be printed (usually
a string), a list of objects or a dictionary. | ValidationError can be passed any object that can be printed (usually
a string), a list of objects or a dictionary. | [
"ValidationError",
"can",
"be",
"passed",
"any",
"object",
"that",
"can",
"be",
"printed",
"(",
"usually",
"a",
"string",
")",
"a",
"list",
"of",
"objects",
"or",
"a",
"dictionary",
"."
] | def __init__(self, message, code=None, params=None):
import operator
from django.utils.encoding import force_text
"""
ValidationError can be passed any object that can be printed (usually
a string), a list of objects or a dictionary.
"""
if isinstance(message, dict):
self.message_dict = message
# Reduce each list of messages into a single list.
message = reduce(operator.add, message.values())
if isinstance(message, list):
self.messages = [force_text(msg) for msg in message]
else:
self.code = code
self.params = params
message = force_text(message)
self.messages = [message] | [
"def",
"__init__",
"(",
"self",
",",
"message",
",",
"code",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"import",
"operator",
"from",
"django",
".",
"utils",
".",
"encoding",
"import",
"force_text",
"if",
"isinstance",
"(",
"message",
",",
"dict"... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/core/exceptions.py#L56-L74 | ||
CvvT/dumpDex | 92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1 | python/idaapi.py | python | regval_t._set_float | (self, *args) | return _idaapi.regval_t__set_float(self, *args) | _set_float(self, x) | _set_float(self, x) | [
"_set_float",
"(",
"self",
"x",
")"
] | def _set_float(self, *args):
"""
_set_float(self, x)
"""
return _idaapi.regval_t__set_float(self, *args) | [
"def",
"_set_float",
"(",
"self",
",",
"*",
"args",
")",
":",
"return",
"_idaapi",
".",
"regval_t__set_float",
"(",
"self",
",",
"*",
"args",
")"
] | https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L3266-L3270 | |
microsoft/debugpy | be8dd607f6837244e0b565345e497aff7a0c08bf | src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/util.py | python | Regenerator.__iter__ | (self) | return self | x.__iter__() <==> iter(x) | x.__iter__() <==> iter(x) | [
"x",
".",
"__iter__",
"()",
"<",
"==",
">",
"iter",
"(",
"x",
")"
] | def __iter__(self):
'x.__iter__() <==> iter(x)'
return self | [
"def",
"__iter__",
"(",
"self",
")",
":",
"return",
"self"
] | https://github.com/microsoft/debugpy/blob/be8dd607f6837244e0b565345e497aff7a0c08bf/src/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/util.py#L136-L138 | |
explosion/srsly | 8617ecc099d1f34a60117b5287bef5424ea2c837 | srsly/ruamel_yaml/compat.py | python | Nprint.set_max_print | (self, i) | [] | def set_max_print(self, i):
# type: (int) -> None
self._max_print = i
self._count = None | [
"def",
"set_max_print",
"(",
"self",
",",
"i",
")",
":",
"# type: (int) -> None",
"self",
".",
"_max_print",
"=",
"i",
"self",
".",
"_count",
"=",
"None"
] | https://github.com/explosion/srsly/blob/8617ecc099d1f34a60117b5287bef5424ea2c837/srsly/ruamel_yaml/compat.py#L219-L222 | ||||
pyqt/examples | 843bb982917cecb2350b5f6d7f42c9b7fb142ec1 | src/pyqt-official/designer/plugins/python/counterlabelplugin.py | python | CounterLabelPlugin.createWidget | (self, parent) | return widget | [] | def createWidget(self, parent):
widget = CounterLabel(parent)
widget.setValue(1)
return widget | [
"def",
"createWidget",
"(",
"self",
",",
"parent",
")",
":",
"widget",
"=",
"CounterLabel",
"(",
"parent",
")",
"widget",
".",
"setValue",
"(",
"1",
")",
"return",
"widget"
] | https://github.com/pyqt/examples/blob/843bb982917cecb2350b5f6d7f42c9b7fb142ec1/src/pyqt-official/designer/plugins/python/counterlabelplugin.py#L60-L63 | |||
UncleGoogle/galaxy-integration-humblebundle | ffe063ed3c047053039851256cf23a5343317f2e | tasks.py | python | asset_name | (tag, platform) | return f'humble_{tag}_{platform[:3].lower()}.zip' | [] | def asset_name(tag, platform):
return f'humble_{tag}_{platform[:3].lower()}.zip' | [
"def",
"asset_name",
"(",
"tag",
",",
"platform",
")",
":",
"return",
"f'humble_{tag}_{platform[:3].lower()}.zip'"
] | https://github.com/UncleGoogle/galaxy-integration-humblebundle/blob/ffe063ed3c047053039851256cf23a5343317f2e/tasks.py#L50-L51 | |||
joblib/joblib | 7742f5882273889f7aaf1d483a8a1c72a97d57e3 | joblib/numpy_pickle_compat.py | python | NDArrayWrapper.read | (self, unpickler) | Reconstruct the array. | Reconstruct the array. | [
"Reconstruct",
"the",
"array",
"."
] | def read(self, unpickler):
"""Reconstruct the array."""
filename = os.path.join(unpickler._dirname, self.filename)
# Load the array from the disk
# use getattr instead of self.allow_mmap to ensure backward compat
# with NDArrayWrapper instances pickled with joblib < 0.9.0
allow_mmap = getattr(self, 'allow_mmap', True)
kwargs = {}
if allow_mmap:
kwargs['mmap_mode'] = unpickler.mmap_mode
if "allow_pickle" in inspect.signature(unpickler.np.load).parameters:
# Required in numpy 1.16.3 and later to aknowledge the security
# risk.
kwargs["allow_pickle"] = True
array = unpickler.np.load(filename, **kwargs)
# Detect byte order mis-match and swap as needed.
array = _ensure_native_byte_order(array)
# Reconstruct subclasses. This does not work with old
# versions of numpy
if (hasattr(array, '__array_prepare__') and
self.subclass not in (unpickler.np.ndarray,
unpickler.np.memmap)):
# We need to reconstruct another subclass
new_array = unpickler.np.core.multiarray._reconstruct(
self.subclass, (0,), 'b')
return new_array.__array_prepare__(array)
else:
return array | [
"def",
"read",
"(",
"self",
",",
"unpickler",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"unpickler",
".",
"_dirname",
",",
"self",
".",
"filename",
")",
"# Load the array from the disk",
"# use getattr instead of self.allow_mmap to ensure backw... | https://github.com/joblib/joblib/blob/7742f5882273889f7aaf1d483a8a1c72a97d57e3/joblib/numpy_pickle_compat.py#L92-L121 | ||
chrisjbryant/errant | 9111c6c5ca0dffdd5d8023faab91cc94aa3aef93 | errant/en/lancaster.py | python | LancasterStemmer.__stripPrefix | (self, word) | return word | Remove prefix from a word.
This function originally taken from Whoosh. | Remove prefix from a word. | [
"Remove",
"prefix",
"from",
"a",
"word",
"."
] | def __stripPrefix(self, word):
"""Remove prefix from a word.
This function originally taken from Whoosh.
"""
for prefix in (
"kilo",
"micro",
"milli",
"intra",
"ultra",
"mega",
"nano",
"pico",
"pseudo",
):
if word.startswith(prefix):
return word[len(prefix) :]
return word | [
"def",
"__stripPrefix",
"(",
"self",
",",
"word",
")",
":",
"for",
"prefix",
"in",
"(",
"\"kilo\"",
",",
"\"micro\"",
",",
"\"milli\"",
",",
"\"intra\"",
",",
"\"ultra\"",
",",
"\"mega\"",
",",
"\"nano\"",
",",
"\"pico\"",
",",
"\"pseudo\"",
",",
")",
":... | https://github.com/chrisjbryant/errant/blob/9111c6c5ca0dffdd5d8023faab91cc94aa3aef93/errant/en/lancaster.py#L327-L346 | |
mayank93/Twitter-Sentiment-Analysis | f095c6ca6bf69787582b5dabb140fefaf278eb37 | front-end/web2py/gluon/contrib/memcache/memcache.py | python | Client.cas | (self, key, val, time=0, min_compress_len=0) | return self._set("cas", key, val, time, min_compress_len) | Sets a key to a given value in the memcache if it hasn't been
altered since last fetched. (See L{gets}).
The C{key} can optionally be an tuple, with the first element
being the server hash value and the second being the key.
If you want to avoid making this module calculate a hash value.
You may prefer, for example, to keep all of a given user's objects
on the same memcache server, so you could use the user's unique
id as the hash value.
@return: Nonzero on success.
@rtype: int
@param time: Tells memcached the time which this value should expire,
either as a delta number of seconds, or an absolute unix
time-since-the-epoch value. See the memcached protocol docs section
"Storage Commands" for more info on <exptime>. We default to
0 == cache forever.
@param min_compress_len: The threshold length to kick in
auto-compression of the value using the zlib.compress() routine. If
the value being cached is a string, then the length of the string is
measured, else if the value is an object, then the length of the
pickle result is measured. If the resulting attempt at compression
yeilds a larger string than the input, then it is discarded. For
backwards compatability, this parameter defaults to 0, indicating
don't ever try to compress. | Sets a key to a given value in the memcache if it hasn't been
altered since last fetched. (See L{gets}). | [
"Sets",
"a",
"key",
"to",
"a",
"given",
"value",
"in",
"the",
"memcache",
"if",
"it",
"hasn",
"t",
"been",
"altered",
"since",
"last",
"fetched",
".",
"(",
"See",
"L",
"{",
"gets",
"}",
")",
"."
] | def cas(self, key, val, time=0, min_compress_len=0):
'''Sets a key to a given value in the memcache if it hasn't been
altered since last fetched. (See L{gets}).
The C{key} can optionally be an tuple, with the first element
being the server hash value and the second being the key.
If you want to avoid making this module calculate a hash value.
You may prefer, for example, to keep all of a given user's objects
on the same memcache server, so you could use the user's unique
id as the hash value.
@return: Nonzero on success.
@rtype: int
@param time: Tells memcached the time which this value should expire,
either as a delta number of seconds, or an absolute unix
time-since-the-epoch value. See the memcached protocol docs section
"Storage Commands" for more info on <exptime>. We default to
0 == cache forever.
@param min_compress_len: The threshold length to kick in
auto-compression of the value using the zlib.compress() routine. If
the value being cached is a string, then the length of the string is
measured, else if the value is an object, then the length of the
pickle result is measured. If the resulting attempt at compression
yeilds a larger string than the input, then it is discarded. For
backwards compatability, this parameter defaults to 0, indicating
don't ever try to compress.
'''
return self._set("cas", key, val, time, min_compress_len) | [
"def",
"cas",
"(",
"self",
",",
"key",
",",
"val",
",",
"time",
"=",
"0",
",",
"min_compress_len",
"=",
"0",
")",
":",
"return",
"self",
".",
"_set",
"(",
"\"cas\"",
",",
"key",
",",
"val",
",",
"time",
",",
"min_compress_len",
")"
] | https://github.com/mayank93/Twitter-Sentiment-Analysis/blob/f095c6ca6bf69787582b5dabb140fefaf278eb37/front-end/web2py/gluon/contrib/memcache/memcache.py#L568-L595 | |
caiiiac/Machine-Learning-with-Python | 1a26c4467da41ca4ebc3d5bd789ea942ef79422f | MachineLearning/venv/lib/python3.5/site-packages/pandas/core/sorting.py | python | get_group_index | (labels, shape, sort, xnull) | return loop(list(labels), list(shape)) | For the particular label_list, gets the offsets into the hypothetical list
representing the totally ordered cartesian product of all possible label
combinations, *as long as* this space fits within int64 bounds;
otherwise, though group indices identify unique combinations of
labels, they cannot be deconstructed.
- If `sort`, rank of returned ids preserve lexical ranks of labels.
i.e. returned id's can be used to do lexical sort on labels;
- If `xnull` nulls (-1 labels) are passed through.
Parameters
----------
labels: sequence of arrays
Integers identifying levels at each location
shape: sequence of ints same length as labels
Number of unique levels at each location
sort: boolean
If the ranks of returned ids should match lexical ranks of labels
xnull: boolean
If true nulls are excluded. i.e. -1 values in the labels are
passed through
Returns
-------
An array of type int64 where two elements are equal if their corresponding
labels are equal at all location. | For the particular label_list, gets the offsets into the hypothetical list
representing the totally ordered cartesian product of all possible label
combinations, *as long as* this space fits within int64 bounds;
otherwise, though group indices identify unique combinations of
labels, they cannot be deconstructed.
- If `sort`, rank of returned ids preserve lexical ranks of labels.
i.e. returned id's can be used to do lexical sort on labels;
- If `xnull` nulls (-1 labels) are passed through. | [
"For",
"the",
"particular",
"label_list",
"gets",
"the",
"offsets",
"into",
"the",
"hypothetical",
"list",
"representing",
"the",
"totally",
"ordered",
"cartesian",
"product",
"of",
"all",
"possible",
"label",
"combinations",
"*",
"as",
"long",
"as",
"*",
"this"... | def get_group_index(labels, shape, sort, xnull):
"""
For the particular label_list, gets the offsets into the hypothetical list
representing the totally ordered cartesian product of all possible label
combinations, *as long as* this space fits within int64 bounds;
otherwise, though group indices identify unique combinations of
labels, they cannot be deconstructed.
- If `sort`, rank of returned ids preserve lexical ranks of labels.
i.e. returned id's can be used to do lexical sort on labels;
- If `xnull` nulls (-1 labels) are passed through.
Parameters
----------
labels: sequence of arrays
Integers identifying levels at each location
shape: sequence of ints same length as labels
Number of unique levels at each location
sort: boolean
If the ranks of returned ids should match lexical ranks of labels
xnull: boolean
If true nulls are excluded. i.e. -1 values in the labels are
passed through
Returns
-------
An array of type int64 where two elements are equal if their corresponding
labels are equal at all location.
"""
def _int64_cut_off(shape):
acc = long(1)
for i, mul in enumerate(shape):
acc *= long(mul)
if not acc < _INT64_MAX:
return i
return len(shape)
def loop(labels, shape):
# how many levels can be done without overflow:
nlev = _int64_cut_off(shape)
# compute flat ids for the first `nlev` levels
stride = np.prod(shape[1:nlev], dtype='i8')
out = stride * labels[0].astype('i8', subok=False, copy=False)
for i in range(1, nlev):
if shape[i] == 0:
stride = 0
else:
stride //= shape[i]
out += labels[i] * stride
if xnull: # exclude nulls
mask = labels[0] == -1
for lab in labels[1:nlev]:
mask |= lab == -1
out[mask] = -1
if nlev == len(shape): # all levels done!
return out
# compress what has been done so far in order to avoid overflow
# to retain lexical ranks, obs_ids should be sorted
comp_ids, obs_ids = compress_group_index(out, sort=sort)
labels = [comp_ids] + labels[nlev:]
shape = [len(obs_ids)] + shape[nlev:]
return loop(labels, shape)
def maybe_lift(lab, size): # pormote nan values
return (lab + 1, size + 1) if (lab == -1).any() else (lab, size)
labels = map(_ensure_int64, labels)
if not xnull:
labels, shape = map(list, zip(*map(maybe_lift, labels, shape)))
return loop(list(labels), list(shape)) | [
"def",
"get_group_index",
"(",
"labels",
",",
"shape",
",",
"sort",
",",
"xnull",
")",
":",
"def",
"_int64_cut_off",
"(",
"shape",
")",
":",
"acc",
"=",
"long",
"(",
"1",
")",
"for",
"i",
",",
"mul",
"in",
"enumerate",
"(",
"shape",
")",
":",
"acc"... | https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/pandas/core/sorting.py#L19-L94 | |
dimagi/commcare-hq | d67ff1d3b4c51fa050c19e60c3253a79d3452a39 | corehq/apps/users/models.py | python | get_fixture_statuses | (user_id) | return last_modifieds | [] | def get_fixture_statuses(user_id):
from corehq.apps.fixtures.models import UserFixtureType, UserFixtureStatus
last_modifieds = {choice[0]: UserFixtureStatus.DEFAULT_LAST_MODIFIED
for choice in UserFixtureType.CHOICES}
for fixture_status in UserFixtureStatus.objects.filter(user_id=user_id):
last_modifieds[fixture_status.fixture_type] = fixture_status.last_modified
return last_modifieds | [
"def",
"get_fixture_statuses",
"(",
"user_id",
")",
":",
"from",
"corehq",
".",
"apps",
".",
"fixtures",
".",
"models",
"import",
"UserFixtureType",
",",
"UserFixtureStatus",
"last_modifieds",
"=",
"{",
"choice",
"[",
"0",
"]",
":",
"UserFixtureStatus",
".",
"... | https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/users/models.py#L2349-L2355 | |||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/encodings/utf_16_le.py | python | decode | (input, errors='strict') | return codecs.utf_16_le_decode(input, errors, True) | [] | def decode(input, errors='strict'):
return codecs.utf_16_le_decode(input, errors, True) | [
"def",
"decode",
"(",
"input",
",",
"errors",
"=",
"'strict'",
")",
":",
"return",
"codecs",
".",
"utf_16_le_decode",
"(",
"input",
",",
"errors",
",",
"True",
")"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/encodings/utf_16_le.py#L15-L16 | |||
khalim19/gimp-plugin-export-layers | b37255f2957ad322f4d332689052351cdea6e563 | export_layers/pygimplib/_lib/future/libpasteurize/fixes/fix_division.py | python | FixDivision.match | (self, node) | return match_division(node) | u"""
Since the tree needs to be fixed once and only once if and only if it
matches, then we can start discarding matches after we make the first. | u"""
Since the tree needs to be fixed once and only once if and only if it
matches, then we can start discarding matches after we make the first. | [
"u",
"Since",
"the",
"tree",
"needs",
"to",
"be",
"fixed",
"once",
"and",
"only",
"once",
"if",
"and",
"only",
"if",
"it",
"matches",
"then",
"we",
"can",
"start",
"discarding",
"matches",
"after",
"we",
"make",
"the",
"first",
"."
] | def match(self, node):
u"""
Since the tree needs to be fixed once and only once if and only if it
matches, then we can start discarding matches after we make the first.
"""
return match_division(node) | [
"def",
"match",
"(",
"self",
",",
"node",
")",
":",
"return",
"match_division",
"(",
"node",
")"
] | https://github.com/khalim19/gimp-plugin-export-layers/blob/b37255f2957ad322f4d332689052351cdea6e563/export_layers/pygimplib/_lib/future/libpasteurize/fixes/fix_division.py#L20-L25 | |
lad1337/XDM | 0c1b7009fe00f06f102a6f67c793478f515e7efe | site-packages/profilehooks.py | python | profile | (fn=None, skip=0, filename=None, immediate=False, dirs=False,
sort=None, entries=40,
profiler=('cProfile', 'profile', 'hotshot')) | return new_fn | Mark `fn` for profiling.
If `skip` is > 0, first `skip` calls to `fn` will not be profiled.
If `immediate` is False, profiling results will be printed to
sys.stdout on program termination. Otherwise results will be printed
after each call.
If `dirs` is False only the name of the file will be printed.
Otherwise the full path is used.
`sort` can be a list of sort keys (defaulting to ['cumulative',
'time', 'calls']). The following ones are recognized::
'calls' -- call count
'cumulative' -- cumulative time
'file' -- file name
'line' -- line number
'module' -- file name
'name' -- function name
'nfl' -- name/file/line
'pcalls' -- call count
'stdname' -- standard name
'time' -- internal time
`entries` limits the output to the first N entries.
`profiler` can be used to select the preferred profiler, or specify a
sequence of them, in order of preference. The default is ('cProfile'.
'profile', 'hotshot').
If `filename` is specified, the profile stats will be stored in the
named file. You can load them pstats.Stats(filename).
Usage::
def fn(...):
...
fn = profile(fn, skip=1)
If you are using Python 2.4, you should be able to use the decorator
syntax::
@profile(skip=3)
def fn(...):
...
or just ::
@profile
def fn(...):
... | Mark `fn` for profiling. | [
"Mark",
"fn",
"for",
"profiling",
"."
] | def profile(fn=None, skip=0, filename=None, immediate=False, dirs=False,
sort=None, entries=40,
profiler=('cProfile', 'profile', 'hotshot')):
"""Mark `fn` for profiling.
If `skip` is > 0, first `skip` calls to `fn` will not be profiled.
If `immediate` is False, profiling results will be printed to
sys.stdout on program termination. Otherwise results will be printed
after each call.
If `dirs` is False only the name of the file will be printed.
Otherwise the full path is used.
`sort` can be a list of sort keys (defaulting to ['cumulative',
'time', 'calls']). The following ones are recognized::
'calls' -- call count
'cumulative' -- cumulative time
'file' -- file name
'line' -- line number
'module' -- file name
'name' -- function name
'nfl' -- name/file/line
'pcalls' -- call count
'stdname' -- standard name
'time' -- internal time
`entries` limits the output to the first N entries.
`profiler` can be used to select the preferred profiler, or specify a
sequence of them, in order of preference. The default is ('cProfile'.
'profile', 'hotshot').
If `filename` is specified, the profile stats will be stored in the
named file. You can load them pstats.Stats(filename).
Usage::
def fn(...):
...
fn = profile(fn, skip=1)
If you are using Python 2.4, you should be able to use the decorator
syntax::
@profile(skip=3)
def fn(...):
...
or just ::
@profile
def fn(...):
...
"""
if fn is None: # @profile() syntax -- we are a decorator maker
def decorator(fn):
return profile(fn, skip=skip, filename=filename,
immediate=immediate, dirs=dirs,
sort=sort, entries=entries,
profiler=profiler)
return decorator
# @profile syntax -- we are a decorator.
if isinstance(profiler, str):
profiler = [profiler]
for p in profiler:
if p in AVAILABLE_PROFILERS:
profiler_class = AVAILABLE_PROFILERS[p]
break
else:
raise ValueError('only these profilers are available: %s'
% ', '.join(AVAILABLE_PROFILERS))
fp = profiler_class(fn, skip=skip, filename=filename,
immediate=immediate, dirs=dirs,
sort=sort, entries=entries)
# fp = HotShotFuncProfile(fn, skip=skip, filename=filename, ...)
# or HotShotFuncProfile
# We cannot return fp or fp.__call__ directly as that would break method
# definitions, instead we need to return a plain function.
def new_fn(*args, **kw):
return fp(*args, **kw)
new_fn.__doc__ = fn.__doc__
new_fn.__name__ = fn.__name__
new_fn.__dict__ = fn.__dict__
new_fn.__module__ = fn.__module__
return new_fn | [
"def",
"profile",
"(",
"fn",
"=",
"None",
",",
"skip",
"=",
"0",
",",
"filename",
"=",
"None",
",",
"immediate",
"=",
"False",
",",
"dirs",
"=",
"False",
",",
"sort",
"=",
"None",
",",
"entries",
"=",
"40",
",",
"profiler",
"=",
"(",
"'cProfile'",
... | https://github.com/lad1337/XDM/blob/0c1b7009fe00f06f102a6f67c793478f515e7efe/site-packages/profilehooks.py#L138-L225 | |
omz/PythonistaAppTemplate | f560f93f8876d82a21d108977f90583df08d55af | PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/markdown/extensions/headerid.py | python | HeaderIdTreeprocessor._get_meta | (self) | return level, force | Return meta data suported by this ext as a tuple | Return meta data suported by this ext as a tuple | [
"Return",
"meta",
"data",
"suported",
"by",
"this",
"ext",
"as",
"a",
"tuple"
] | def _get_meta(self):
""" Return meta data suported by this ext as a tuple """
level = int(self.config['level']) - 1
force = self._str2bool(self.config['forceid'])
if hasattr(self.md, 'Meta'):
if self.md.Meta.has_key('header_level'):
level = int(self.md.Meta['header_level'][0]) - 1
if self.md.Meta.has_key('header_forceid'):
force = self._str2bool(self.md.Meta['header_forceid'][0])
return level, force | [
"def",
"_get_meta",
"(",
"self",
")",
":",
"level",
"=",
"int",
"(",
"self",
".",
"config",
"[",
"'level'",
"]",
")",
"-",
"1",
"force",
"=",
"self",
".",
"_str2bool",
"(",
"self",
".",
"config",
"[",
"'forceid'",
"]",
")",
"if",
"hasattr",
"(",
... | https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib/site-packages/markdown/extensions/headerid.py#L148-L157 | |
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_project.py | python | OCProject.needs_update | (self) | return False | verify an update is needed | verify an update is needed | [
"verify",
"an",
"update",
"is",
"needed"
] | def needs_update(self):
''' verify an update is needed '''
if self.config.config_options['display_name']['value'] is not None:
result = self.project.find_annotation("display-name")
if result != self.config.config_options['display_name']['value']:
return True
if self.config.config_options['description']['value'] is not None:
result = self.project.find_annotation("description")
if result != self.config.config_options['description']['value']:
return True
if self.config.config_options['node_selector']['value'] is not None:
result = self.project.find_annotation("node-selector")
if result != self.config.config_options['node_selector']['value']:
return True
return False | [
"def",
"needs_update",
"(",
"self",
")",
":",
"if",
"self",
".",
"config",
".",
"config_options",
"[",
"'display_name'",
"]",
"[",
"'value'",
"]",
"is",
"not",
"None",
":",
"result",
"=",
"self",
".",
"project",
".",
"find_annotation",
"(",
"\"display-name... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_project.py#L1629-L1646 | |
khalim19/gimp-plugin-export-layers | b37255f2957ad322f4d332689052351cdea6e563 | export_layers/pygimplib/_lib/future/future/backports/email/generator.py | python | BytesGenerator._handle_text | (self, msg) | [] | def _handle_text(self, msg):
# If the string has surrogates the original source was bytes, so
# just write it back out.
if msg._payload is None:
return
if _has_surrogates(msg._payload) and not self.policy.cte_type=='7bit':
if self._mangle_from_:
msg._payload = fcre.sub(">From ", msg._payload)
self._write_lines(msg._payload)
else:
super(BytesGenerator,self)._handle_text(msg) | [
"def",
"_handle_text",
"(",
"self",
",",
"msg",
")",
":",
"# If the string has surrogates the original source was bytes, so",
"# just write it back out.",
"if",
"msg",
".",
"_payload",
"is",
"None",
":",
"return",
"if",
"_has_surrogates",
"(",
"msg",
".",
"_payload",
... | https://github.com/khalim19/gimp-plugin-export-layers/blob/b37255f2957ad322f4d332689052351cdea6e563/export_layers/pygimplib/_lib/future/future/backports/email/generator.py#L416-L426 | ||||
MycroftAI/mycroft-core | 3d963cee402e232174850f36918313e87313fb13 | mycroft/audio/audioservice.py | python | AudioService.play | (self, tracks, prefered_service, repeat=False) | play starts playing the audio on the prefered service if it
supports the uri. If not the next best backend is found.
Args:
tracks: list of tracks to play.
repeat: should the playlist repeat
prefered_service: indecates the service the user prefer to play
the tracks. | play starts playing the audio on the prefered service if it
supports the uri. If not the next best backend is found. | [
"play",
"starts",
"playing",
"the",
"audio",
"on",
"the",
"prefered",
"service",
"if",
"it",
"supports",
"the",
"uri",
".",
"If",
"not",
"the",
"next",
"best",
"backend",
"is",
"found",
"."
] | def play(self, tracks, prefered_service, repeat=False):
"""
play starts playing the audio on the prefered service if it
supports the uri. If not the next best backend is found.
Args:
tracks: list of tracks to play.
repeat: should the playlist repeat
prefered_service: indecates the service the user prefer to play
the tracks.
"""
self._perform_stop()
if isinstance(tracks[0], str):
uri_type = tracks[0].split(':')[0]
else:
uri_type = tracks[0][0].split(':')[0]
# check if user requested a particular service
if prefered_service and uri_type in prefered_service.supported_uris():
selected_service = prefered_service
# check if default supports the uri
elif self.default and uri_type in self.default.supported_uris():
LOG.debug("Using default backend ({})".format(self.default.name))
selected_service = self.default
else: # Check if any other service can play the media
LOG.debug("Searching the services")
for s in self.service:
if uri_type in s.supported_uris():
LOG.debug("Service {} supports URI {}".format(s, uri_type))
selected_service = s
break
else:
LOG.info('No service found for uri_type: ' + uri_type)
return
if not selected_service.supports_mime_hints:
tracks = [t[0] if isinstance(t, list) else t for t in tracks]
selected_service.clear_list()
selected_service.add_list(tracks)
selected_service.play(repeat)
self.current = selected_service
self.play_start_time = time.monotonic() | [
"def",
"play",
"(",
"self",
",",
"tracks",
",",
"prefered_service",
",",
"repeat",
"=",
"False",
")",
":",
"self",
".",
"_perform_stop",
"(",
")",
"if",
"isinstance",
"(",
"tracks",
"[",
"0",
"]",
",",
"str",
")",
":",
"uri_type",
"=",
"tracks",
"[",... | https://github.com/MycroftAI/mycroft-core/blob/3d963cee402e232174850f36918313e87313fb13/mycroft/audio/audioservice.py#L401-L442 | ||
beeware/ouroboros | a29123c6fab6a807caffbb7587cf548e0c370296 | ouroboros/lib2to3/btm_matcher.py | python | BottomMatcher.run | (self, leaves) | return results | The main interface with the bottom matcher. The tree is
traversed from the bottom using the constructed
automaton. Nodes are only checked once as the tree is
retraversed. When the automaton fails, we give it one more
shot(in case the above tree matches as a whole with the
rejected leaf), then we break for the next leaf. There is the
special case of multiple arguments(see code comments) where we
recheck the nodes
Args:
The leaves of the AST tree to be matched
Returns:
A dictionary of node matches with fixers as the keys | The main interface with the bottom matcher. The tree is
traversed from the bottom using the constructed
automaton. Nodes are only checked once as the tree is
retraversed. When the automaton fails, we give it one more
shot(in case the above tree matches as a whole with the
rejected leaf), then we break for the next leaf. There is the
special case of multiple arguments(see code comments) where we
recheck the nodes | [
"The",
"main",
"interface",
"with",
"the",
"bottom",
"matcher",
".",
"The",
"tree",
"is",
"traversed",
"from",
"the",
"bottom",
"using",
"the",
"constructed",
"automaton",
".",
"Nodes",
"are",
"only",
"checked",
"once",
"as",
"the",
"tree",
"is",
"retraverse... | def run(self, leaves):
"""The main interface with the bottom matcher. The tree is
traversed from the bottom using the constructed
automaton. Nodes are only checked once as the tree is
retraversed. When the automaton fails, we give it one more
shot(in case the above tree matches as a whole with the
rejected leaf), then we break for the next leaf. There is the
special case of multiple arguments(see code comments) where we
recheck the nodes
Args:
The leaves of the AST tree to be matched
Returns:
A dictionary of node matches with fixers as the keys
"""
current_ac_node = self.root
results = defaultdict(list)
for leaf in leaves:
current_ast_node = leaf
while current_ast_node:
current_ast_node.was_checked = True
for child in current_ast_node.children:
# multiple statements, recheck
if isinstance(child, pytree.Leaf) and child.value == ";":
current_ast_node.was_checked = False
break
if current_ast_node.type == 1:
#name
node_token = current_ast_node.value
else:
node_token = current_ast_node.type
if node_token in current_ac_node.transition_table:
#token matches
current_ac_node = current_ac_node.transition_table[node_token]
for fixer in current_ac_node.fixers:
if not fixer in results:
results[fixer] = []
results[fixer].append(current_ast_node)
else:
#matching failed, reset automaton
current_ac_node = self.root
if (current_ast_node.parent is not None
and current_ast_node.parent.was_checked):
#the rest of the tree upwards has been checked, next leaf
break
#recheck the rejected node once from the root
if node_token in current_ac_node.transition_table:
#token matches
current_ac_node = current_ac_node.transition_table[node_token]
for fixer in current_ac_node.fixers:
if not fixer in results.keys():
results[fixer] = []
results[fixer].append(current_ast_node)
current_ast_node = current_ast_node.parent
return results | [
"def",
"run",
"(",
"self",
",",
"leaves",
")",
":",
"current_ac_node",
"=",
"self",
".",
"root",
"results",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"leaf",
"in",
"leaves",
":",
"current_ast_node",
"=",
"leaf",
"while",
"current_ast_node",
":",
"curren... | https://github.com/beeware/ouroboros/blob/a29123c6fab6a807caffbb7587cf548e0c370296/ouroboros/lib2to3/btm_matcher.py#L83-L142 | |
pjkundert/cpppo | 4c217b6c06b88bede3888cc5ea2731f271a95086 | server/enip/client.py | python | client.get_attribute_single | ( self, path,
route_path=None, send_path=None, timeout=None, send=True,
data_size=None, elements=None, tag_type=None, # for response data_size estimation
sender_context=b'', **kwds ) | return req | [] | def get_attribute_single( self, path,
route_path=None, send_path=None, timeout=None, send=True,
data_size=None, elements=None, tag_type=None, # for response data_size estimation
sender_context=b'', **kwds ):
req = dotdict()
req.path = { 'segment': [
dotdict( d ) for d in device.parse_path( path )
]}
req.get_attribute_single= True
if send:
self.req_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context, **kwds )
return req | [
"def",
"get_attribute_single",
"(",
"self",
",",
"path",
",",
"route_path",
"=",
"None",
",",
"send_path",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"send",
"=",
"True",
",",
"data_size",
"=",
"None",
",",
"elements",
"=",
"None",
",",
"tag_type",
... | https://github.com/pjkundert/cpppo/blob/4c217b6c06b88bede3888cc5ea2731f271a95086/server/enip/client.py#L860-L873 | |||
pymedusa/Medusa | 1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38 | ext/adba/aniDBAbstracter.py | python | Episode.load_data | (self) | load the data from anidb | load the data from anidb | [
"load",
"the",
"data",
"from",
"anidb"
] | def load_data(self):
"""load the data from anidb"""
if self.filePath and not (self.ed2k or self.size):
(self.ed2k, self.size) = self._calculate_file_stuff(self.filePath)
self.rawData = self.aniDB.file(fid=self.fid, size=self.size, ed2k=self.ed2k, aid=self.aid, aname=None, gid=None, gname=None, epno=self.epno, fmask=self.bitCodeF, amask=self.bitCodeA)
self._fill(self.rawData.datalines[0])
self._build_names()
self.laoded = True | [
"def",
"load_data",
"(",
"self",
")",
":",
"if",
"self",
".",
"filePath",
"and",
"not",
"(",
"self",
".",
"ed2k",
"or",
"self",
".",
"size",
")",
":",
"(",
"self",
".",
"ed2k",
",",
"self",
".",
"size",
")",
"=",
"self",
".",
"_calculate_file_stuff... | https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/adba/aniDBAbstracter.py#L255-L263 | ||
vaexio/vaex | 6c1571f4f1ac030eb7128c1b35b2ccbb5dd29cac | packages/vaex-core/vaex/functions.py | python | str_isalpha | (x) | return _to_string_sequence(x).isalpha() | Check if all characters in a string sample are alphabetic.
:returns: an expression evaluated to True if a sample contains only alphabetic characters, otherwise False.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.isalpha()
Expression = str_isalpha(text)
Length: 5 dtype: bool (expression)
----------------------------------
0 True
1 False
2 False
3 True
4 False | Check if all characters in a string sample are alphabetic. | [
"Check",
"if",
"all",
"characters",
"in",
"a",
"string",
"sample",
"are",
"alphabetic",
"."
] | def str_isalpha(x):
"""Check if all characters in a string sample are alphabetic.
:returns: an expression evaluated to True if a sample contains only alphabetic characters, otherwise False.
Example:
>>> import vaex
>>> text = ['Something', 'very pretty', 'is coming', 'our', 'way.']
>>> df = vaex.from_arrays(text=text)
>>> df
# text
0 Something
1 very pretty
2 is coming
3 our
4 way.
>>> df.text.str.isalpha()
Expression = str_isalpha(text)
Length: 5 dtype: bool (expression)
----------------------------------
0 True
1 False
2 False
3 True
4 False
"""
return _to_string_sequence(x).isalpha() | [
"def",
"str_isalpha",
"(",
"x",
")",
":",
"return",
"_to_string_sequence",
"(",
"x",
")",
".",
"isalpha",
"(",
")"
] | https://github.com/vaexio/vaex/blob/6c1571f4f1ac030eb7128c1b35b2ccbb5dd29cac/packages/vaex-core/vaex/functions.py#L2218-L2246 | |
boto/boto | b2a6f08122b2f1b89888d2848e730893595cd001 | boto/opsworks/layer1.py | python | OpsWorksConnection.describe_stack_summary | (self, stack_id) | return self.make_request(action='DescribeStackSummary',
body=json.dumps(params)) | Describes the number of layers and apps in a specified stack,
and the number of instances in each state, such as
`running_setup` or `online`.
**Required Permissions**: To use this action, an IAM user must
have a Show, Deploy, or Manage permissions level for the
stack, or an attached policy that explicitly grants
permissions. For more information on user permissions, see
`Managing User Permissions`_.
:type stack_id: string
:param stack_id: The stack ID. | Describes the number of layers and apps in a specified stack,
and the number of instances in each state, such as
`running_setup` or `online`. | [
"Describes",
"the",
"number",
"of",
"layers",
"and",
"apps",
"in",
"a",
"specified",
"stack",
"and",
"the",
"number",
"of",
"instances",
"in",
"each",
"state",
"such",
"as",
"running_setup",
"or",
"online",
"."
] | def describe_stack_summary(self, stack_id):
"""
Describes the number of layers and apps in a specified stack,
and the number of instances in each state, such as
`running_setup` or `online`.
**Required Permissions**: To use this action, an IAM user must
have a Show, Deploy, or Manage permissions level for the
stack, or an attached policy that explicitly grants
permissions. For more information on user permissions, see
`Managing User Permissions`_.
:type stack_id: string
:param stack_id: The stack ID.
"""
params = {'StackId': stack_id, }
return self.make_request(action='DescribeStackSummary',
body=json.dumps(params)) | [
"def",
"describe_stack_summary",
"(",
"self",
",",
"stack_id",
")",
":",
"params",
"=",
"{",
"'StackId'",
":",
"stack_id",
",",
"}",
"return",
"self",
".",
"make_request",
"(",
"action",
"=",
"'DescribeStackSummary'",
",",
"body",
"=",
"json",
".",
"dumps",
... | https://github.com/boto/boto/blob/b2a6f08122b2f1b89888d2848e730893595cd001/boto/opsworks/layer1.py#L1802-L1820 | |
aws/aws-sam-cli | 2aa7bf01b2e0b0864ef63b1898a8b30577443acc | samcli/lib/sync/exceptions.py | python | MissingPhysicalResourceError.resource_identifier | (self) | return self._resource_identifier | Returns
-------
str
Resource identifier of the resource that does not have a remote/physical counterpart | Returns
-------
str
Resource identifier of the resource that does not have a remote/physical counterpart | [
"Returns",
"-------",
"str",
"Resource",
"identifier",
"of",
"the",
"resource",
"that",
"does",
"not",
"have",
"a",
"remote",
"/",
"physical",
"counterpart"
] | def resource_identifier(self) -> Optional[str]:
"""
Returns
-------
str
Resource identifier of the resource that does not have a remote/physical counterpart
"""
return self._resource_identifier | [
"def",
"resource_identifier",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"return",
"self",
".",
"_resource_identifier"
] | https://github.com/aws/aws-sam-cli/blob/2aa7bf01b2e0b0864ef63b1898a8b30577443acc/samcli/lib/sync/exceptions.py#L98-L105 | |
selfteaching/selfteaching-python-camp | 9982ee964b984595e7d664b07c389cddaf158f1e | 19100205/Ceasar1978/pip-19.0.3/src/pip/_vendor/urllib3/response.py | python | HTTPResponse.supports_chunked_reads | (self) | return hasattr(self._fp, 'fp') | Checks if the underlying file-like object looks like a
httplib.HTTPResponse object. We do this by testing for the fp
attribute. If it is present we assume it returns raw chunks as
processed by read_chunked(). | Checks if the underlying file-like object looks like a
httplib.HTTPResponse object. We do this by testing for the fp
attribute. If it is present we assume it returns raw chunks as
processed by read_chunked(). | [
"Checks",
"if",
"the",
"underlying",
"file",
"-",
"like",
"object",
"looks",
"like",
"a",
"httplib",
".",
"HTTPResponse",
"object",
".",
"We",
"do",
"this",
"by",
"testing",
"for",
"the",
"fp",
"attribute",
".",
"If",
"it",
"is",
"present",
"we",
"assume... | def supports_chunked_reads(self):
"""
Checks if the underlying file-like object looks like a
httplib.HTTPResponse object. We do this by testing for the fp
attribute. If it is present we assume it returns raw chunks as
processed by read_chunked().
"""
return hasattr(self._fp, 'fp') | [
"def",
"supports_chunked_reads",
"(",
"self",
")",
":",
"return",
"hasattr",
"(",
"self",
".",
"_fp",
",",
"'fp'",
")"
] | https://github.com/selfteaching/selfteaching-python-camp/blob/9982ee964b984595e7d664b07c389cddaf158f1e/19100205/Ceasar1978/pip-19.0.3/src/pip/_vendor/urllib3/response.py#L584-L591 | |
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/urllib/request.py | python | URLopener.__init__ | (self, proxies=None, **x509) | [] | def __init__(self, proxies=None, **x509):
msg = "%(class)s style of invoking requests is deprecated. " \
"Use newer urlopen functions/methods" % {'class': self.__class__.__name__}
warnings.warn(msg, DeprecationWarning, stacklevel=3)
if proxies is None:
proxies = getproxies()
assert hasattr(proxies, 'keys'), "proxies must be a mapping"
self.proxies = proxies
self.key_file = x509.get('key_file')
self.cert_file = x509.get('cert_file')
self.addheaders = [('User-Agent', self.version), ('Accept', '*/*')]
self.__tempfiles = []
self.__unlink = os.unlink # See cleanup()
self.tempcache = None
# Undocumented feature: if you assign {} to tempcache,
# it is used to cache files retrieved with
# self.retrieve(). This is not enabled by default
# since it does not work for changing documents (and I
# haven't got the logic to check expiration headers
# yet).
self.ftpcache = ftpcache | [
"def",
"__init__",
"(",
"self",
",",
"proxies",
"=",
"None",
",",
"*",
"*",
"x509",
")",
":",
"msg",
"=",
"\"%(class)s style of invoking requests is deprecated. \"",
"\"Use newer urlopen functions/methods\"",
"%",
"{",
"'class'",
":",
"self",
".",
"__class__",
".",
... | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/urllib/request.py#L1710-L1730 | ||||
dpgaspar/Flask-AppBuilder | 557249f33b66d02a48c1322ef21324b815abe18e | flask_appbuilder/models/group.py | python | BaseGroupBy.apply | (self, data) | Override this to implement you own new filters | Override this to implement you own new filters | [
"Override",
"this",
"to",
"implement",
"you",
"own",
"new",
"filters"
] | def apply(self, data):
"""
Override this to implement you own new filters
"""
pass | [
"def",
"apply",
"(",
"self",
",",
"data",
")",
":",
"pass"
] | https://github.com/dpgaspar/Flask-AppBuilder/blob/557249f33b66d02a48c1322ef21324b815abe18e/flask_appbuilder/models/group.py#L86-L90 | ||
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/sqlalchemy/engine/result.py | python | ResultProxy.first | (self) | Fetch the first row and then close the result set unconditionally.
Returns None if no row is present.
After calling this method, the object is fully closed,
e.g. the :meth:`.ResultProxy.close` method will have been called. | Fetch the first row and then close the result set unconditionally. | [
"Fetch",
"the",
"first",
"row",
"and",
"then",
"close",
"the",
"result",
"set",
"unconditionally",
"."
] | def first(self):
"""Fetch the first row and then close the result set unconditionally.
Returns None if no row is present.
After calling this method, the object is fully closed,
e.g. the :meth:`.ResultProxy.close` method will have been called.
"""
if self._metadata is None:
return self._non_result(None)
try:
row = self._fetchone_impl()
except BaseException as e:
self.connection._handle_dbapi_exception(
e, None, None,
self.cursor, self.context)
try:
if row is not None:
return self.process_rows([row])[0]
else:
return None
finally:
self.close() | [
"def",
"first",
"(",
"self",
")",
":",
"if",
"self",
".",
"_metadata",
"is",
"None",
":",
"return",
"self",
".",
"_non_result",
"(",
"None",
")",
"try",
":",
"row",
"=",
"self",
".",
"_fetchone_impl",
"(",
")",
"except",
"BaseException",
"as",
"e",
"... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/engine/result.py#L1197-L1222 | ||
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/min/profile.py | python | fake_code.__repr__ | (self) | return repr((self.co_filename, self.co_line, self.co_name)) | [] | def __repr__(self):
return repr((self.co_filename, self.co_line, self.co_name)) | [
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"repr",
"(",
"(",
"self",
".",
"co_filename",
",",
"self",
".",
"co_line",
",",
"self",
".",
"co_name",
")",
")"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/min/profile.py#L355-L356 | |||
gem/oq-engine | 1bdb88f3914e390abcbd285600bfd39477aae47c | openquake/commonlib/shapefileparser.py | python | ShapefileParser.write | (self, destination, source_model, name=None) | Save sources - to multiple
shapefiles corresponding to different source typolgies/geometries
('_point', '_area', '_simple', '_complex', '_planar') | Save sources - to multiple
shapefiles corresponding to different source typolgies/geometries
('_point', '_area', '_simple', '_complex', '_planar') | [
"Save",
"sources",
"-",
"to",
"multiple",
"shapefiles",
"corresponding",
"to",
"different",
"source",
"typolgies",
"/",
"geometries",
"(",
"_point",
"_area",
"_simple",
"_complex",
"_planar",
")"
] | def write(self, destination, source_model, name=None):
"""
Save sources - to multiple
shapefiles corresponding to different source typolgies/geometries
('_point', '_area', '_simple', '_complex', '_planar')
"""
if os.path.exists(destination + ".shp"):
os.system("rm %s.*" % destination)
self.destination = destination
self.filter_params(source_model)
w_area = shapefile.Writer(shapefile.POLYGON)
w_point = shapefile.Writer(shapefile.POINT)
w_simple = shapefile.Writer(shapefile.POLYLINE)
w_simple3d = shapefile.Writer(shapefile.POLYGONZ)
w_complex = shapefile.Writer(shapefile.POLYLINEZ)
w_planar = shapefile.Writer(shapefile.POLYGONZ)
register_fields(w_area)
register_fields(w_point)
register_fields(w_simple)
register_fields(w_simple3d)
register_fields(w_complex)
register_fields(w_planar)
for src in source_model.sources:
# Order is important here
if "areaSource" in src.tag:
set_params(w_area, src)
set_area_geometry(w_area, src)
elif "pointSource" in src.tag:
set_params(w_point, src)
set_point_geometry(w_point, src)
elif "complexFaultSource" in src.tag:
set_params(w_complex, src)
set_complex_fault_geometry(w_complex, src)
elif "simpleFaultSource" in src.tag:
set_params(w_simple, src)
set_simple_fault_geometry(w_simple, src)
# Create the 3D polygon
set_params(w_simple3d, src)
set_simple_fault_geometry_3D(w_simple3d, src)
elif "characteristicFaultSource" in src.tag:
src_taglist = get_taglist(src)
surface_node = src.nodes[src_taglist.index("surface")]
for subnode in surface_node:
if "simpleFaultGeometry" in subnode.tag:
set_params(w_simple, src)
set_params(w_simple3d, src)
elif "complexFaultGeometry" in subnode.tag:
set_params(w_complex, src)
elif "planarSurface" in subnode.tag:
set_params(w_planar, src)
else:
raise ValueError(
'Geometry class %s not recognized'
% subnode.tag)
set_characteristic_geometry(w_simple, w_simple3d,
w_complex, w_planar, src)
else:
raise ValueError('Source type %s not recognized'
% src.tag)
root = self.destination
if len(w_area.shapes()):
w_area.save('%s_area' % root)
if len(w_point.shapes()):
w_point.save('%s_point' % root)
if len(w_complex.shapes()):
w_complex.save('%s_complex' % root)
if len(w_simple.shapes()):
w_simple.save('%s_simple' % root)
w_simple3d.save('%s_simple3d' % root)
if len(w_planar.shapes()):
w_planar.save('%s_planar' % root) | [
"def",
"write",
"(",
"self",
",",
"destination",
",",
"source_model",
",",
"name",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"destination",
"+",
"\".shp\"",
")",
":",
"os",
".",
"system",
"(",
"\"rm %s.*\"",
"%",
"destination"... | https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/commonlib/shapefileparser.py#L1018-L1093 | ||
jython/jython3 | def4f8ec47cb7a9c799ea4c745f12badf92c5769 | lib-python/3.5.1/multiprocessing/connection.py | python | _ConnectionBase.readable | (self) | return self._readable | True if the connection is readable | True if the connection is readable | [
"True",
"if",
"the",
"connection",
"is",
"readable"
] | def readable(self):
"""True if the connection is readable"""
return self._readable | [
"def",
"readable",
"(",
"self",
")",
":",
"return",
"self",
".",
"_readable"
] | https://github.com/jython/jython3/blob/def4f8ec47cb7a9c799ea4c745f12badf92c5769/lib-python/3.5.1/multiprocessing/connection.py#L159-L161 | |
numenta/nupic | b9ebedaf54f49a33de22d8d44dff7c765cdb5548 | examples/prediction/category_prediction/webdata.py | python | computeAccuracy | (model, size, top) | return np.mean(accuracy) | Compute prediction accuracy by checking if the next page in the sequence is
within the top N predictions calculated by the model
Args:
model: HTM model
size: Sample size
top: top N predictions to use
Returns: Probability the next page in the sequence is within the top N
predicted pages | Compute prediction accuracy by checking if the next page in the sequence is
within the top N predictions calculated by the model
Args:
model: HTM model
size: Sample size
top: top N predictions to use | [
"Compute",
"prediction",
"accuracy",
"by",
"checking",
"if",
"the",
"next",
"page",
"in",
"the",
"sequence",
"is",
"within",
"the",
"top",
"N",
"predictions",
"calculated",
"by",
"the",
"model",
"Args",
":",
"model",
":",
"HTM",
"model",
"size",
":",
"Samp... | def computeAccuracy(model, size, top):
"""
Compute prediction accuracy by checking if the next page in the sequence is
within the top N predictions calculated by the model
Args:
model: HTM model
size: Sample size
top: top N predictions to use
Returns: Probability the next page in the sequence is within the top N
predicted pages
"""
accuracy = []
# Load MSNBC web data file
filename = os.path.join(os.path.dirname(__file__), "msnbc990928.zip")
with zipfile.ZipFile(filename) as archive:
with archive.open("msnbc990928.seq") as datafile:
# Skip header lines (first 7 lines)
for _ in xrange(7):
next(datafile)
# Skip learning data and compute accuracy using only new sessions
for _ in xrange(LEARNING_RECORDS):
next(datafile)
# Compute prediction accuracy by checking if the next page in the sequence
# is within the top N predictions calculated by the model
for _ in xrange(size):
pages = readUserSession(datafile)
model.resetSequenceStates()
for i in xrange(len(pages) - 1):
result = model.run({"page": pages[i]})
inferences = result.inferences["multiStepPredictions"][1]
# Get top N predictions for the next page
predicted = sorted(inferences.items(), key=itemgetter(1), reverse=True)[:top]
# Check if the next page is within the predicted pages
accuracy.append(1 if pages[i + 1] in zip(*predicted)[0] else 0)
return np.mean(accuracy) | [
"def",
"computeAccuracy",
"(",
"model",
",",
"size",
",",
"top",
")",
":",
"accuracy",
"=",
"[",
"]",
"# Load MSNBC web data file",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"m... | https://github.com/numenta/nupic/blob/b9ebedaf54f49a33de22d8d44dff7c765cdb5548/examples/prediction/category_prediction/webdata.py#L146-L187 | |
linxid/Machine_Learning_Study_Path | 558e82d13237114bbb8152483977806fc0c222af | Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/compat/dictconfig.py | python | DictConfigurator.add_filters | (self, filterer, filters) | Add filters to a filterer from a list of names. | Add filters to a filterer from a list of names. | [
"Add",
"filters",
"to",
"a",
"filterer",
"from",
"a",
"list",
"of",
"names",
"."
] | def add_filters(self, filterer, filters):
"""Add filters to a filterer from a list of names."""
for f in filters:
try:
filterer.addFilter(self.config['filters'][f])
except StandardError as e:
raise ValueError('Unable to add filter %r: %s' % (f, e)) | [
"def",
"add_filters",
"(",
"self",
",",
"filterer",
",",
"filters",
")",
":",
"for",
"f",
"in",
"filters",
":",
"try",
":",
"filterer",
".",
"addFilter",
"(",
"self",
".",
"config",
"[",
"'filters'",
"]",
"[",
"f",
"]",
")",
"except",
"StandardError",
... | https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/site-packages/pip/compat/dictconfig.py#L460-L466 | ||
buke/openerp-taobao | a9f0d7c1d832afb97e153a77f252c3985e4fc559 | taobao/libs/beanstalkc.py | python | Connection.tubes | (self) | return self._interact_yaml('list-tubes\r\n', ['OK']) | Return a list of all existing tubes. | Return a list of all existing tubes. | [
"Return",
"a",
"list",
"of",
"all",
"existing",
"tubes",
"."
] | def tubes(self):
"""Return a list of all existing tubes."""
return self._interact_yaml('list-tubes\r\n', ['OK']) | [
"def",
"tubes",
"(",
"self",
")",
":",
"return",
"self",
".",
"_interact_yaml",
"(",
"'list-tubes\\r\\n'",
",",
"[",
"'OK'",
"]",
")"
] | https://github.com/buke/openerp-taobao/blob/a9f0d7c1d832afb97e153a77f252c3985e4fc559/taobao/libs/beanstalkc.py#L168-L170 | |
knipknap/exscript | a20e83ae3a78ea7e5ba25f07c1d9de4e9b961e83 | Exscript/logger.py | python | Log.succeeded | (self) | Called by a logger to inform us that logging is complete. | Called by a logger to inform us that logging is complete. | [
"Called",
"by",
"a",
"logger",
"to",
"inform",
"us",
"that",
"logging",
"is",
"complete",
"."
] | def succeeded(self):
"""
Called by a logger to inform us that logging is complete.
"""
self.did_end = True | [
"def",
"succeeded",
"(",
"self",
")",
":",
"self",
".",
"did_end",
"=",
"True"
] | https://github.com/knipknap/exscript/blob/a20e83ae3a78ea7e5ba25f07c1d9de4e9b961e83/Exscript/logger.py#L86-L90 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_serviceaccount.py | python | Utils.create_tmp_files_from_contents | (content, content_type=None) | return files | Turn an array of dict: filename, content into a files array | Turn an array of dict: filename, content into a files array | [
"Turn",
"an",
"array",
"of",
"dict",
":",
"filename",
"content",
"into",
"a",
"files",
"array"
] | def create_tmp_files_from_contents(content, content_type=None):
'''Turn an array of dict: filename, content into a files array'''
if not isinstance(content, list):
content = [content]
files = []
for item in content:
path = Utils.create_tmp_file_from_contents(item['path'] + '-',
item['data'],
ftype=content_type)
files.append({'name': os.path.basename(item['path']),
'path': path})
return files | [
"def",
"create_tmp_files_from_contents",
"(",
"content",
",",
"content_type",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"content",
",",
"list",
")",
":",
"content",
"=",
"[",
"content",
"]",
"files",
"=",
"[",
"]",
"for",
"item",
"in",
"cont... | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_vendored_deps/library/oc_serviceaccount.py#L1207-L1218 | |
qibinlou/SinaWeibo-Emotion-Classification | f336fc104abd68b0ec4180fe2ed80fafe49cb790 | nltk/parse/nonprojectivedependencyparser.py | python | ProbabilisticNonprojectiveParser.collapse_nodes | (self, new_node, cycle_path, g_graph, b_graph, c_graph) | Takes a list of nodes that have been identified to belong to a cycle,
and collapses them into on larger node. The arcs of all nodes in
the graph must be updated to account for this.
:type new_node: Node.
:param new_node: A Node (Dictionary) to collapse the cycle nodes into.
:type cycle_path: A list of integers.
:param cycle_path: A list of node addresses, each of which is in the cycle.
:type g_graph, b_graph, c_graph: DependencyGraph
:param g_graph, b_graph, c_graph: Graphs which need to be updated. | Takes a list of nodes that have been identified to belong to a cycle,
and collapses them into on larger node. The arcs of all nodes in
the graph must be updated to account for this. | [
"Takes",
"a",
"list",
"of",
"nodes",
"that",
"have",
"been",
"identified",
"to",
"belong",
"to",
"a",
"cycle",
"and",
"collapses",
"them",
"into",
"on",
"larger",
"node",
".",
"The",
"arcs",
"of",
"all",
"nodes",
"in",
"the",
"graph",
"must",
"be",
"up... | def collapse_nodes(self, new_node, cycle_path, g_graph, b_graph, c_graph):
"""
Takes a list of nodes that have been identified to belong to a cycle,
and collapses them into on larger node. The arcs of all nodes in
the graph must be updated to account for this.
:type new_node: Node.
:param new_node: A Node (Dictionary) to collapse the cycle nodes into.
:type cycle_path: A list of integers.
:param cycle_path: A list of node addresses, each of which is in the cycle.
:type g_graph, b_graph, c_graph: DependencyGraph
:param g_graph, b_graph, c_graph: Graphs which need to be updated.
"""
print 'Collapsing nodes...'
# Collapse all cycle nodes into v_n+1 in G_Graph
for cycle_node_index in cycle_path:
g_graph.remove_by_address(cycle_node_index)
g_graph.nodelist.append(new_node)
g_graph.redirect_arcs(cycle_path, new_node['address']) | [
"def",
"collapse_nodes",
"(",
"self",
",",
"new_node",
",",
"cycle_path",
",",
"g_graph",
",",
"b_graph",
",",
"c_graph",
")",
":",
"print",
"'Collapsing nodes...'",
"# Collapse all cycle nodes into v_n+1 in G_Graph",
"for",
"cycle_node_index",
"in",
"cycle_path",
":",
... | https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/nltk/parse/nonprojectivedependencyparser.py#L225-L243 | ||
Theano/Theano | 8fd9203edfeecebced9344b0c70193be292a9ade | theano/tensor/basic.py | python | sgn | (a) | sign of a | sign of a | [
"sign",
"of",
"a"
] | def sgn(a):
"""sign of a""" | [
"def",
"sgn",
"(",
"a",
")",
":"
] | https://github.com/Theano/Theano/blob/8fd9203edfeecebced9344b0c70193be292a9ade/theano/tensor/basic.py#L2150-L2151 | ||
ahmetcemturan/SFACT | 7576e29ba72b33e5058049b77b7b558875542747 | fabmetheus_utilities/geometry/solids/group.py | python | Group.getMatrixChainTetragrid | (self) | return matrix.getTetragridTimesOther(self.elementNode.parentNode.xmlObject.getMatrixChainTetragrid(), self.matrix4X4.tetragrid) | Get the matrix chain tetragrid. | Get the matrix chain tetragrid. | [
"Get",
"the",
"matrix",
"chain",
"tetragrid",
"."
] | def getMatrixChainTetragrid(self):
"Get the matrix chain tetragrid."
return matrix.getTetragridTimesOther(self.elementNode.parentNode.xmlObject.getMatrixChainTetragrid(), self.matrix4X4.tetragrid) | [
"def",
"getMatrixChainTetragrid",
"(",
"self",
")",
":",
"return",
"matrix",
".",
"getTetragridTimesOther",
"(",
"self",
".",
"elementNode",
".",
"parentNode",
".",
"xmlObject",
".",
"getMatrixChainTetragrid",
"(",
")",
",",
"self",
".",
"matrix4X4",
".",
"tetra... | https://github.com/ahmetcemturan/SFACT/blob/7576e29ba72b33e5058049b77b7b558875542747/fabmetheus_utilities/geometry/solids/group.py#L70-L72 | |
tensorflow/tensor2tensor | 2a33b152d7835af66a6d20afe7961751047e28dd | tensor2tensor/models/transformer.py | python | transformer_decoder | (decoder_input,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
hparams,
cache=None,
decode_loop_step=None,
name="decoder",
nonpadding=None,
save_weights_to=None,
make_image_summary=True,
losses=None,
layer_collection=None,
recurrent_memory_by_layer=None,
chunk_number=None) | A stack of transformer layers.
Args:
decoder_input: a Tensor
encoder_output: a Tensor
decoder_self_attention_bias: bias Tensor for self-attention (see
common_attention.attention_bias())
encoder_decoder_attention_bias: bias Tensor for encoder-decoder attention
(see common_attention.attention_bias())
hparams: hyperparameters for model
cache: dict, containing tensors which are the results of previous
attentions, used for fast decoding.
decode_loop_step: An integer, step number of the decoding loop. Only used
for inference on TPU.
name: a string
nonpadding: optional Tensor with shape [batch_size, encoder_length]
indicating what positions are not padding. This is used to mask out
padding in convolutional layers. We generally only need this mask for
"packed" datasets, because for ordinary datasets, no padding is ever
followed by nonpadding.
save_weights_to: an optional dictionary to capture attention weights for
visualization; the weights tensor will be appended there under a string
key created from the variable scope (including name).
make_image_summary: Whether to make an attention image summary.
losses: optional list onto which to append extra training losses
layer_collection: A tensorflow_kfac.LayerCollection. Only used by the KFAC
optimizer. Default is None.
recurrent_memory_by_layer: Optional dict, mapping layer names to instances
of transformer_memory.RecurrentMemory. Default is None.
chunk_number: an optional integer Tensor with shape [batch] used to operate
the recurrent_memory.
Returns:
y: a Tensors | A stack of transformer layers. | [
"A",
"stack",
"of",
"transformer",
"layers",
"."
] | def transformer_decoder(decoder_input,
encoder_output,
decoder_self_attention_bias,
encoder_decoder_attention_bias,
hparams,
cache=None,
decode_loop_step=None,
name="decoder",
nonpadding=None,
save_weights_to=None,
make_image_summary=True,
losses=None,
layer_collection=None,
recurrent_memory_by_layer=None,
chunk_number=None):
"""A stack of transformer layers.
Args:
decoder_input: a Tensor
encoder_output: a Tensor
decoder_self_attention_bias: bias Tensor for self-attention (see
common_attention.attention_bias())
encoder_decoder_attention_bias: bias Tensor for encoder-decoder attention
(see common_attention.attention_bias())
hparams: hyperparameters for model
cache: dict, containing tensors which are the results of previous
attentions, used for fast decoding.
decode_loop_step: An integer, step number of the decoding loop. Only used
for inference on TPU.
name: a string
nonpadding: optional Tensor with shape [batch_size, encoder_length]
indicating what positions are not padding. This is used to mask out
padding in convolutional layers. We generally only need this mask for
"packed" datasets, because for ordinary datasets, no padding is ever
followed by nonpadding.
save_weights_to: an optional dictionary to capture attention weights for
visualization; the weights tensor will be appended there under a string
key created from the variable scope (including name).
make_image_summary: Whether to make an attention image summary.
losses: optional list onto which to append extra training losses
layer_collection: A tensorflow_kfac.LayerCollection. Only used by the KFAC
optimizer. Default is None.
recurrent_memory_by_layer: Optional dict, mapping layer names to instances
of transformer_memory.RecurrentMemory. Default is None.
chunk_number: an optional integer Tensor with shape [batch] used to operate
the recurrent_memory.
Returns:
y: a Tensors
"""
x = decoder_input
mlperf_log.transformer_print(
key=mlperf_log.MODEL_HP_NUM_HIDDEN_LAYERS,
value=hparams.num_decoder_layers or hparams.num_hidden_layers,
hparams=hparams)
mlperf_log.transformer_print(
key=mlperf_log.MODEL_HP_ATTENTION_DROPOUT,
value=hparams.attention_dropout,
hparams=hparams)
mlperf_log.transformer_print(
key=mlperf_log.MODEL_HP_ATTENTION_DENSE,
value={
"use_bias": "false",
"num_heads": hparams.num_heads,
"hidden_size": hparams.hidden_size
},
hparams=hparams)
with tf.variable_scope(name):
for layer_idx in range(hparams.num_decoder_layers or
hparams.num_hidden_layers):
x = transformer_decoder_layer(
x,
decoder_self_attention_bias,
layer_idx,
hparams,
encoder_decoder_attention_bias=encoder_decoder_attention_bias,
encoder_output=encoder_output,
cache=cache,
decode_loop_step=decode_loop_step,
nonpadding=nonpadding,
save_weights_to=save_weights_to,
make_image_summary=make_image_summary,
losses=losses,
layer_collection=layer_collection,
recurrent_memory_by_layer=recurrent_memory_by_layer,
chunk_number=chunk_number
)
# if normalization is done in layer_preprocess, then it should also be done
# on the output, since the output can grow very large, being the sum of
# a whole stack of unnormalized layer outputs.
mlperf_log.transformer_print(
key=mlperf_log.MODEL_HP_NORM,
value={"hidden_size": hparams.hidden_size})
return common_layers.layer_preprocess(
x, hparams, layer_collection=layer_collection) | [
"def",
"transformer_decoder",
"(",
"decoder_input",
",",
"encoder_output",
",",
"decoder_self_attention_bias",
",",
"encoder_decoder_attention_bias",
",",
"hparams",
",",
"cache",
"=",
"None",
",",
"decode_loop_step",
"=",
"None",
",",
"name",
"=",
"\"decoder\"",
",",... | https://github.com/tensorflow/tensor2tensor/blob/2a33b152d7835af66a6d20afe7961751047e28dd/tensor2tensor/models/transformer.py#L1626-L1723 | ||
Esri/ArcREST | ab240fde2b0200f61d4a5f6df033516e53f2f416 | tools/src/addItem.py | python | trace | () | return line, __file__, synerror | trace finds the line, the filename
and error message and returns it
to the user | trace finds the line, the filename
and error message and returns it
to the user | [
"trace",
"finds",
"the",
"line",
"the",
"filename",
"and",
"error",
"message",
"and",
"returns",
"it",
"to",
"the",
"user"
] | def trace():
"""
trace finds the line, the filename
and error message and returns it
to the user
"""
import traceback
import sys
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
# script name + line number
line = tbinfo.split(", ")[1]
# Get Python syntax error
#
synerror = traceback.format_exc().splitlines()[-1]
return line, __file__, synerror | [
"def",
"trace",
"(",
")",
":",
"import",
"traceback",
"import",
"sys",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
"tbinfo",
"=",
"traceback",
".",
"format_tb",
"(",
"tb",
")",
"[",
"0",
"]",
"# script name + line number",
"line",
"=",
... | https://github.com/Esri/ArcREST/blob/ab240fde2b0200f61d4a5f6df033516e53f2f416/tools/src/addItem.py#L21-L36 | |
projecthamster/hamster | 19d160090de30e756bdc3122ff935bdaa86e2843 | waflib/Logs.py | python | init_log | () | Initializes the logger :py:attr:`waflib.Logs.log` | Initializes the logger :py:attr:`waflib.Logs.log` | [
"Initializes",
"the",
"logger",
":",
"py",
":",
"attr",
":",
"waflib",
".",
"Logs",
".",
"log"
] | def init_log():
"""
Initializes the logger :py:attr:`waflib.Logs.log`
"""
global log
log = logging.getLogger('waflib')
log.handlers = []
log.filters = []
hdlr = log_handler()
hdlr.setFormatter(formatter())
log.addHandler(hdlr)
log.addFilter(log_filter())
log.setLevel(logging.DEBUG) | [
"def",
"init_log",
"(",
")",
":",
"global",
"log",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'waflib'",
")",
"log",
".",
"handlers",
"=",
"[",
"]",
"log",
".",
"filters",
"=",
"[",
"]",
"hdlr",
"=",
"log_handler",
"(",
")",
"hdlr",
".",
"setFo... | https://github.com/projecthamster/hamster/blob/19d160090de30e756bdc3122ff935bdaa86e2843/waflib/Logs.py#L292-L304 | ||
dask/dask | c2b962fec1ba45440fe928869dc64cfe9cc36506 | dask/dataframe/core.py | python | _take_last | (a, skipna=True) | take last row (Series) of DataFrame / last value of Series
considering NaN.
Parameters
----------
a : pd.DataFrame or pd.Series
skipna : bool, default True
Whether to exclude NaN | take last row (Series) of DataFrame / last value of Series
considering NaN. | [
"take",
"last",
"row",
"(",
"Series",
")",
"of",
"DataFrame",
"/",
"last",
"value",
"of",
"Series",
"considering",
"NaN",
"."
] | def _take_last(a, skipna=True):
"""
take last row (Series) of DataFrame / last value of Series
considering NaN.
Parameters
----------
a : pd.DataFrame or pd.Series
skipna : bool, default True
Whether to exclude NaN
"""
def _last_valid(s):
for i in range(1, min(10, len(s) + 1)):
val = s.iloc[-i]
if not pd.isnull(val):
return val
else:
nonnull = s[s.notna()]
if not nonnull.empty:
return nonnull.iloc[-1]
return None
if skipna is False:
return a.iloc[-1]
else:
# take last valid value excluding NaN, NaN location may be different
# in each column
if is_dataframe_like(a):
# create Series from appropriate backend dataframe library
series_typ = type(a.iloc[0:1, 0])
if a.empty:
return series_typ([], dtype="float")
return series_typ(
{col: _last_valid(a[col]) for col in a.columns}, index=a.columns
)
else:
return _last_valid(a) | [
"def",
"_take_last",
"(",
"a",
",",
"skipna",
"=",
"True",
")",
":",
"def",
"_last_valid",
"(",
"s",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"min",
"(",
"10",
",",
"len",
"(",
"s",
")",
"+",
"1",
")",
")",
":",
"val",
"=",
"s",
... | https://github.com/dask/dask/blob/c2b962fec1ba45440fe928869dc64cfe9cc36506/dask/dataframe/core.py#L6552-L6590 | ||
selinon/selinon | 3613153566d454022a138639f0375c63f490c4cb | selinon/flow.py | python | Flow.should_propagate_compound_failures | (self, dst_node_name) | return self._should_config(dst_node_name, self.propagate_compound_failures) | Check whether this flow should info about failures (in compound/flattered mode).
:param dst_node_name: destination node to which configuration should be propagated
:return: True if should propagate_compound_failures | Check whether this flow should info about failures (in compound/flattered mode). | [
"Check",
"whether",
"this",
"flow",
"should",
"info",
"about",
"failures",
"(",
"in",
"compound",
"/",
"flattered",
"mode",
")",
"."
] | def should_propagate_compound_failures(self, dst_node_name): # pylint: disable=invalid-name
"""Check whether this flow should info about failures (in compound/flattered mode).
:param dst_node_name: destination node to which configuration should be propagated
:return: True if should propagate_compound_failures
"""
return self._should_config(dst_node_name, self.propagate_compound_failures) | [
"def",
"should_propagate_compound_failures",
"(",
"self",
",",
"dst_node_name",
")",
":",
"# pylint: disable=invalid-name",
"return",
"self",
".",
"_should_config",
"(",
"dst_node_name",
",",
"self",
".",
"propagate_compound_failures",
")"
] | https://github.com/selinon/selinon/blob/3613153566d454022a138639f0375c63f490c4cb/selinon/flow.py#L305-L311 | |
corenel/pytorch-adda | 96f2689dd418ef275fcd0b057e5dff89be5762c5 | models/lenet.py | python | LeNetEncoder.forward | (self, input) | return feat | Forward the LeNet. | Forward the LeNet. | [
"Forward",
"the",
"LeNet",
"."
] | def forward(self, input):
"""Forward the LeNet."""
conv_out = self.encoder(input)
feat = self.fc1(conv_out.view(-1, 50 * 4 * 4))
return feat | [
"def",
"forward",
"(",
"self",
",",
"input",
")",
":",
"conv_out",
"=",
"self",
".",
"encoder",
"(",
"input",
")",
"feat",
"=",
"self",
".",
"fc1",
"(",
"conv_out",
".",
"view",
"(",
"-",
"1",
",",
"50",
"*",
"4",
"*",
"4",
")",
")",
"return",
... | https://github.com/corenel/pytorch-adda/blob/96f2689dd418ef275fcd0b057e5dff89be5762c5/models/lenet.py#L33-L37 | |
tensorflow/lingvo | ce10019243d954c3c3ebe739f7589b5eebfdf907 | lingvo/runners.py | python | Decoder.GetDecodeOutPath | (cls, decoder_dir, checkpoint_id) | return os.path.join(out_dir, 'decoder_out_%09d' % checkpoint_id) | Gets the path to decode out file. | Gets the path to decode out file. | [
"Gets",
"the",
"path",
"to",
"decode",
"out",
"file",
"."
] | def GetDecodeOutPath(cls, decoder_dir, checkpoint_id):
"""Gets the path to decode out file."""
out_dir = cls._GetTtlDir(decoder_dir, duration='7d')
return os.path.join(out_dir, 'decoder_out_%09d' % checkpoint_id) | [
"def",
"GetDecodeOutPath",
"(",
"cls",
",",
"decoder_dir",
",",
"checkpoint_id",
")",
":",
"out_dir",
"=",
"cls",
".",
"_GetTtlDir",
"(",
"decoder_dir",
",",
"duration",
"=",
"'7d'",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"out_dir",
",",
"'d... | https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/runners.py#L1158-L1161 | |
napari/napari | dbf4158e801fa7a429de8ef1cdee73bf6d64c61e | napari/layers/image/experimental/octree_chunk.py | python | OctreeChunk.needs_load | (self) | return not self.in_memory and not self.loading | Return true if this chunk needs to loaded.
An unloaded chunk's data might be a Dask or similar deferred array.
A loaded chunk's data is always an ndarray.
Returns
-------
True if the chunk needs to be loaded. | Return true if this chunk needs to loaded. | [
"Return",
"true",
"if",
"this",
"chunk",
"needs",
"to",
"loaded",
"."
] | def needs_load(self) -> bool:
"""Return true if this chunk needs to loaded.
An unloaded chunk's data might be a Dask or similar deferred array.
A loaded chunk's data is always an ndarray.
Returns
-------
True if the chunk needs to be loaded.
"""
return not self.in_memory and not self.loading | [
"def",
"needs_load",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"not",
"self",
".",
"in_memory",
"and",
"not",
"self",
".",
"loading"
] | https://github.com/napari/napari/blob/dbf4158e801fa7a429de8ef1cdee73bf6d64c61e/napari/layers/image/experimental/octree_chunk.py#L115-L125 | |
tav/pylibs | 3c16b843681f54130ee6a022275289cadb2f2a69 | paramiko/server.py | python | ServerInterface.check_auth_password | (self, username, password) | return AUTH_FAILED | Determine if a given username and password supplied by the client is
acceptable for use in authentication.
Return L{AUTH_FAILED} if the password is not accepted,
L{AUTH_SUCCESSFUL} if the password is accepted and completes
the authentication, or L{AUTH_PARTIALLY_SUCCESSFUL} if your
authentication is stateful, and this key is accepted for
authentication, but more authentication is required. (In this latter
case, L{get_allowed_auths} will be called to report to the client what
options it has for continuing the authentication.)
The default implementation always returns L{AUTH_FAILED}.
@param username: the username of the authenticating client.
@type username: str
@param password: the password given by the client.
@type password: str
@return: L{AUTH_FAILED} if the authentication fails;
L{AUTH_SUCCESSFUL} if it succeeds;
L{AUTH_PARTIALLY_SUCCESSFUL} if the password auth is
successful, but authentication must continue.
@rtype: int | Determine if a given username and password supplied by the client is
acceptable for use in authentication. | [
"Determine",
"if",
"a",
"given",
"username",
"and",
"password",
"supplied",
"by",
"the",
"client",
"is",
"acceptable",
"for",
"use",
"in",
"authentication",
"."
] | def check_auth_password(self, username, password):
"""
Determine if a given username and password supplied by the client is
acceptable for use in authentication.
Return L{AUTH_FAILED} if the password is not accepted,
L{AUTH_SUCCESSFUL} if the password is accepted and completes
the authentication, or L{AUTH_PARTIALLY_SUCCESSFUL} if your
authentication is stateful, and this key is accepted for
authentication, but more authentication is required. (In this latter
case, L{get_allowed_auths} will be called to report to the client what
options it has for continuing the authentication.)
The default implementation always returns L{AUTH_FAILED}.
@param username: the username of the authenticating client.
@type username: str
@param password: the password given by the client.
@type password: str
@return: L{AUTH_FAILED} if the authentication fails;
L{AUTH_SUCCESSFUL} if it succeeds;
L{AUTH_PARTIALLY_SUCCESSFUL} if the password auth is
successful, but authentication must continue.
@rtype: int
"""
return AUTH_FAILED | [
"def",
"check_auth_password",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"return",
"AUTH_FAILED"
] | https://github.com/tav/pylibs/blob/3c16b843681f54130ee6a022275289cadb2f2a69/paramiko/server.py#L162-L187 | |
misterch0c/shadowbroker | e3a069bea47a2c1009697941ac214adc6f90aa8d | windows/Resources/Python/Core/Lib/runpy.py | python | _run_module_as_main | (mod_name, alter_argv=True) | return _run_code(code, main_globals, None, '__main__', fname, loader, pkg_name) | Runs the designated module in the __main__ namespace
Note that the executed module will have full access to the
__main__ namespace. If this is not desirable, the run_module()
function should be used to run the module code in a fresh namespace.
At the very least, these variables in __main__ will be overwritten:
__name__
__file__
__loader__
__package__ | Runs the designated module in the __main__ namespace
Note that the executed module will have full access to the
__main__ namespace. If this is not desirable, the run_module()
function should be used to run the module code in a fresh namespace.
At the very least, these variables in __main__ will be overwritten:
__name__
__file__
__loader__
__package__ | [
"Runs",
"the",
"designated",
"module",
"in",
"the",
"__main__",
"namespace",
"Note",
"that",
"the",
"executed",
"module",
"will",
"have",
"full",
"access",
"to",
"the",
"__main__",
"namespace",
".",
"If",
"this",
"is",
"not",
"desirable",
"the",
"run_module",
... | def _run_module_as_main(mod_name, alter_argv=True):
"""Runs the designated module in the __main__ namespace
Note that the executed module will have full access to the
__main__ namespace. If this is not desirable, the run_module()
function should be used to run the module code in a fresh namespace.
At the very least, these variables in __main__ will be overwritten:
__name__
__file__
__loader__
__package__
"""
try:
if alter_argv or mod_name != '__main__':
mod_name, loader, code, fname = _get_module_details(mod_name)
else:
mod_name, loader, code, fname = _get_main_module_details()
except ImportError as exc:
msg = '%s: %s' % (sys.executable, str(exc))
sys.exit(msg)
pkg_name = mod_name.rpartition('.')[0]
main_globals = sys.modules['__main__'].__dict__
if alter_argv:
sys.argv[0] = fname
return _run_code(code, main_globals, None, '__main__', fname, loader, pkg_name) | [
"def",
"_run_module_as_main",
"(",
"mod_name",
",",
"alter_argv",
"=",
"True",
")",
":",
"try",
":",
"if",
"alter_argv",
"or",
"mod_name",
"!=",
"'__main__'",
":",
"mod_name",
",",
"loader",
",",
"code",
",",
"fname",
"=",
"_get_module_details",
"(",
"mod_na... | https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/runpy.py#L127-L153 | |
hatRiot/zarp | 2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad | src/lib/scapy/layers/inet6.py | python | _IPv6inIP._recv | (self, p, x=MTU) | return p | [] | def _recv(self, p, x=MTU):
if p is None:
return p
elif isinstance(p, IP):
# TODO: verify checksum
if p.src == self.dst and p.proto == socket.IPPROTO_IPV6:
if isinstance(p.payload, IPv6):
return p.payload
return p | [
"def",
"_recv",
"(",
"self",
",",
"p",
",",
"x",
"=",
"MTU",
")",
":",
"if",
"p",
"is",
"None",
":",
"return",
"p",
"elif",
"isinstance",
"(",
"p",
",",
"IP",
")",
":",
"# TODO: verify checksum",
"if",
"p",
".",
"src",
"==",
"self",
".",
"dst",
... | https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/scapy/layers/inet6.py#L2922-L2930 | |||
ibm-research-tokyo/dybm | a6d308c896c2f66680ee9c5d05a3d7826cc27c64 | src/pydybm/base/sgd.py | python | SGD.update_state | (self, gradients, params=None, func_gradients=None) | Wrapper method updating internal state with current parameters and gradient function
Parameters
----------
gradients : Optional[Dictionary[str, np.ndarray]]
Dictionary of gradients. It is computed if it is None and func_gradient is set.
params : Dictionary[str, np.ndarray], optional
Dictionary of parameters.
func_gradients : Callable[[Dictionary[str, np.ndarray]], Dictionary[str, np.ndarray]], optioanl
Function that maps from parameter to gradients.
If this is not used, `params` is neither used.
Otherwise, `params` must be set. | Wrapper method updating internal state with current parameters and gradient function | [
"Wrapper",
"method",
"updating",
"internal",
"state",
"with",
"current",
"parameters",
"and",
"gradient",
"function"
] | def update_state(self, gradients, params=None, func_gradients=None):
"""
Wrapper method updating internal state with current parameters and gradient function
Parameters
----------
gradients : Optional[Dictionary[str, np.ndarray]]
Dictionary of gradients. It is computed if it is None and func_gradient is set.
params : Dictionary[str, np.ndarray], optional
Dictionary of parameters.
func_gradients : Callable[[Dictionary[str, np.ndarray]], Dictionary[str, np.ndarray]], optioanl
Function that maps from parameter to gradients.
If this is not used, `params` is neither used.
Otherwise, `params` must be set.
"""
if func_gradients is None:
if self.use_func_gradient:
raise ValueError("`func_gradients` must be specified for {}".format(self.__class__.__name__))
params = None
else:
if params is None:
raise ValueError("`params` must be set if `func_gradient` is used")
if gradients is None:
gradients = func_gradients(params)
self._update_state(gradients, params, func_gradients)
if self.callback is not None:
self.callback(self) | [
"def",
"update_state",
"(",
"self",
",",
"gradients",
",",
"params",
"=",
"None",
",",
"func_gradients",
"=",
"None",
")",
":",
"if",
"func_gradients",
"is",
"None",
":",
"if",
"self",
".",
"use_func_gradient",
":",
"raise",
"ValueError",
"(",
"\"`func_gradi... | https://github.com/ibm-research-tokyo/dybm/blob/a6d308c896c2f66680ee9c5d05a3d7826cc27c64/src/pydybm/base/sgd.py#L121-L149 | ||
plotly/plotly.py | cfad7862594b35965c0e000813bd7805e8494a5b | packages/python/plotly/plotly/graph_objs/barpolar/legendgrouptitle/_font.py | python | Font.__init__ | (self, arg=None, color=None, family=None, size=None, **kwargs) | Construct a new Font object
Sets this legend group's title font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.barpolar.legen
dgrouptitle.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
size
Returns
-------
Font | Construct a new Font object
Sets this legend group's title font. | [
"Construct",
"a",
"new",
"Font",
"object",
"Sets",
"this",
"legend",
"group",
"s",
"title",
"font",
"."
] | def __init__(self, arg=None, color=None, family=None, size=None, **kwargs):
"""
Construct a new Font object
Sets this legend group's title font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.barpolar.legen
dgrouptitle.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans",, "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
size
Returns
-------
Font
"""
super(Font, self).__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.barpolar.legendgrouptitle.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.barpolar.legendgrouptitle.Font`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False | [
"def",
"__init__",
"(",
"self",
",",
"arg",
"=",
"None",
",",
"color",
"=",
"None",
",",
"family",
"=",
"None",
",",
"size",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"Font",
",",
"self",
")",
".",
"__init__",
"(",
"\"font\"",... | https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/barpolar/legendgrouptitle/_font.py#L144-L227 | ||
makehumancommunity/makehuman | 8006cf2cc851624619485658bb933a4244bbfd7c | makehuman/core/algos3d.py | python | defaultTargetLicense | () | return makehuman.getAssetLicense( {"license": "AGPL3",
"author": "MakeHuman",
"copyright": "2020 Data Collection AB, Joel Palmius, Jonas Hauquier"} ) | Default license for targets, shared for all targets that do not specify
their own custom license, which is useful for saving storage space as this
license is globally referenced by and applies to the majority of targets. | Default license for targets, shared for all targets that do not specify
their own custom license, which is useful for saving storage space as this
license is globally referenced by and applies to the majority of targets. | [
"Default",
"license",
"for",
"targets",
"shared",
"for",
"all",
"targets",
"that",
"do",
"not",
"specify",
"their",
"own",
"custom",
"license",
"which",
"is",
"useful",
"for",
"saving",
"storage",
"space",
"as",
"this",
"license",
"is",
"globally",
"referenced... | def defaultTargetLicense():
"""
Default license for targets, shared for all targets that do not specify
their own custom license, which is useful for saving storage space as this
license is globally referenced by and applies to the majority of targets.
"""
import makehuman
return makehuman.getAssetLicense( {"license": "AGPL3",
"author": "MakeHuman",
"copyright": "2020 Data Collection AB, Joel Palmius, Jonas Hauquier"} ) | [
"def",
"defaultTargetLicense",
"(",
")",
":",
"import",
"makehuman",
"return",
"makehuman",
".",
"getAssetLicense",
"(",
"{",
"\"license\"",
":",
"\"AGPL3\"",
",",
"\"author\"",
":",
"\"MakeHuman\"",
",",
"\"copyright\"",
":",
"\"2020 Data Collection AB, Joel Palmius, J... | https://github.com/makehumancommunity/makehuman/blob/8006cf2cc851624619485658bb933a4244bbfd7c/makehuman/core/algos3d.py#L500-L509 | |
bjmayor/hacker | e3ce2ad74839c2733b27dac6c0f495e0743e1866 | venv/lib/python3.5/site-packages/bs4/element.py | python | NavigableString.__new__ | (cls, value) | return u | Create a new NavigableString.
When unpickling a NavigableString, this method is called with
the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
passed in to the superclass's __new__ or the superclass won't know
how to handle non-ASCII characters. | Create a new NavigableString. | [
"Create",
"a",
"new",
"NavigableString",
"."
] | def __new__(cls, value):
"""Create a new NavigableString.
When unpickling a NavigableString, this method is called with
the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be
passed in to the superclass's __new__ or the superclass won't know
how to handle non-ASCII characters.
"""
if isinstance(value, str):
u = str.__new__(cls, value)
else:
u = str.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
u.setup()
return u | [
"def",
"__new__",
"(",
"cls",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"u",
"=",
"str",
".",
"__new__",
"(",
"cls",
",",
"value",
")",
"else",
":",
"u",
"=",
"str",
".",
"__new__",
"(",
"cls",
",",
"value"... | https://github.com/bjmayor/hacker/blob/e3ce2ad74839c2733b27dac6c0f495e0743e1866/venv/lib/python3.5/site-packages/bs4/element.py#L697-L710 | |
assemblerflow/flowcraft | 66cef255589238b1c9afe6e80b6917e1225915e7 | flowcraft/templates/assembly_report.py | python | Assembly.get_coverage_sliding | (self, coverage_file, window=2000) | return cov_res | Parameters
----------
coverage_file : str
Path to file containing the coverage info at the per-base level
(as generated by samtools depth)
window : int
Size of sliding window
Returns
------- | [] | def get_coverage_sliding(self, coverage_file, window=2000):
"""
Parameters
----------
coverage_file : str
Path to file containing the coverage info at the per-base level
(as generated by samtools depth)
window : int
Size of sliding window
Returns
-------
"""
if not self.contig_coverage:
self._get_coverage_from_file(coverage_file)
# Stores the coverage results
cov_res = []
# Make flat list of coverage values across genome
complete_cov = [x for y in self.contig_coverage.values() for x in y]
for i in range(0, len(complete_cov), window):
# Get coverage values for current window
cov_window = complete_cov[i:i + window]
# Get mean coverage
cov_res.append(int(sum(cov_window) / len(cov_window)))
return cov_res | [
"def",
"get_coverage_sliding",
"(",
"self",
",",
"coverage_file",
",",
"window",
"=",
"2000",
")",
":",
"if",
"not",
"self",
".",
"contig_coverage",
":",
"self",
".",
"_get_coverage_from_file",
"(",
"coverage_file",
")",
"# Stores the coverage results",
"cov_res",
... | https://github.com/assemblerflow/flowcraft/blob/66cef255589238b1c9afe6e80b6917e1225915e7/flowcraft/templates/assembly_report.py#L388-L419 | ||
openshift/openshift-tools | 1188778e728a6e4781acf728123e5b356380fe6f | ansible/roles/lib_oa_openshift/library/oc_serviceaccount.py | python | Yedit.separator | (self, inc_sep) | setter method for separator | setter method for separator | [
"setter",
"method",
"for",
"separator"
] | def separator(self, inc_sep):
''' setter method for separator '''
self._separator = inc_sep | [
"def",
"separator",
"(",
"self",
",",
"inc_sep",
")",
":",
"self",
".",
"_separator",
"=",
"inc_sep"
] | https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_serviceaccount.py#L169-L171 | ||
vlachoudis/bCNC | 67126b4894dabf6579baf47af8d0f9b7de35e6e3 | bCNC/lib/svg_elements.py | python | QuadraticBezier.__init__ | (self, start, control, end, **kwargs) | [] | def __init__(self, start, control, end, **kwargs):
Curve.__init__(self, start, end, **kwargs)
self.control = Point(control) if control is not None else None | [
"def",
"__init__",
"(",
"self",
",",
"start",
",",
"control",
",",
"end",
",",
"*",
"*",
"kwargs",
")",
":",
"Curve",
".",
"__init__",
"(",
"self",
",",
"start",
",",
"end",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"control",
"=",
"Point",
"(",... | https://github.com/vlachoudis/bCNC/blob/67126b4894dabf6579baf47af8d0f9b7de35e6e3/bCNC/lib/svg_elements.py#L3786-L3788 | ||||
CR-Gjx/LeakGAN | dc3360e30f2572cc4d7281cf2c8f490558e4a794 | Synthetic Data/Main.py | python | target_loss | (sess, target_lstm, data_loader) | return np.mean(nll) | [] | def target_loss(sess, target_lstm, data_loader):
# target_loss means the oracle negative log-likelihood tested with the oracle model "target_lstm"
# For more details, please see the Section 4 in https://arxiv.org/abs/1609.05473
nll = []
data_loader.reset_pointer()
for it in range(data_loader.num_batch):
batch = data_loader.next_batch()
g_loss = sess.run(target_lstm.pretrain_loss, {target_lstm.x: batch})
nll.append(g_loss)
return np.mean(nll) | [
"def",
"target_loss",
"(",
"sess",
",",
"target_lstm",
",",
"data_loader",
")",
":",
"# target_loss means the oracle negative log-likelihood tested with the oracle model \"target_lstm\"",
"# For more details, please see the Section 4 in https://arxiv.org/abs/1609.05473",
"nll",
"=",
"[",... | https://github.com/CR-Gjx/LeakGAN/blob/dc3360e30f2572cc4d7281cf2c8f490558e4a794/Synthetic Data/Main.py#L86-L96 | |||
samuelclay/NewsBlur | 2c45209df01a1566ea105e04d499367f32ac9ad2 | apps/reader/views.py | python | starred_stories_rss_feed | (request, user_id, secret_token) | return starred_stories_rss_feed_tag(request, user_id, secret_token, tag_slug=None) | [] | def starred_stories_rss_feed(request, user_id, secret_token):
return starred_stories_rss_feed_tag(request, user_id, secret_token, tag_slug=None) | [
"def",
"starred_stories_rss_feed",
"(",
"request",
",",
"user_id",
",",
"secret_token",
")",
":",
"return",
"starred_stories_rss_feed_tag",
"(",
"request",
",",
"user_id",
",",
"secret_token",
",",
"tag_slug",
"=",
"None",
")"
] | https://github.com/samuelclay/NewsBlur/blob/2c45209df01a1566ea105e04d499367f32ac9ad2/apps/reader/views.py#L1071-L1072 | |||
fuzzbunch/fuzzbunch | 4b60a6c7cf9f84cf389d3fcdb9281de84ffb5802 | fuzzbunch/pyreadline/modes/notemacs.py | python | NotEmacsMode.kill_region | (self, e) | Kill the text in the current region. By default, this command is unbound. | Kill the text in the current region. By default, this command is unbound. | [
"Kill",
"the",
"text",
"in",
"the",
"current",
"region",
".",
"By",
"default",
"this",
"command",
"is",
"unbound",
"."
] | def kill_region(self, e): # ()
'''Kill the text in the current region. By default, this command is unbound. '''
pass | [
"def",
"kill_region",
"(",
"self",
",",
"e",
")",
":",
"# ()",
"pass"
] | https://github.com/fuzzbunch/fuzzbunch/blob/4b60a6c7cf9f84cf389d3fcdb9281de84ffb5802/fuzzbunch/pyreadline/modes/notemacs.py#L360-L362 | ||
dmnfarrell/pandastable | 9c268b3e2bfe2e718eaee4a30bd02832a0ad1614 | pandastable/plotting.py | python | AnnotationOptions.addWidgets | (self) | return | Custom dialogs for manually adding annotation items like text | Custom dialogs for manually adding annotation items like text | [
"Custom",
"dialogs",
"for",
"manually",
"adding",
"annotation",
"items",
"like",
"text"
] | def addWidgets(self):
"""Custom dialogs for manually adding annotation items like text"""
frame = LabelFrame(self.main, text='add objects')
v = self.objectvar = StringVar()
v.set('textbox')
w = Combobox(frame, values=['textbox'],#'arrow'],
textvariable=v,width=14)
Label(frame,text='add object').pack()
w.pack(fill=BOTH,pady=2)
self.coordsvar = StringVar()
self.coordsvar.set('data')
w = Combobox(frame, values=['data','axes fraction','figure fraction'],
textvariable=self.coordsvar,width=14)
Label(frame,text='coord system').pack()
w.pack(fill=BOTH,pady=2)
b = Button(frame, text='Create', command=self.addObject)
b.pack(fill=X,pady=2)
b = Button(frame, text='Clear', command=self.clear)
b.pack(fill=X,pady=2)
frame.pack(side=LEFT,fill=Y)
return | [
"def",
"addWidgets",
"(",
"self",
")",
":",
"frame",
"=",
"LabelFrame",
"(",
"self",
".",
"main",
",",
"text",
"=",
"'add objects'",
")",
"v",
"=",
"self",
".",
"objectvar",
"=",
"StringVar",
"(",
")",
"v",
".",
"set",
"(",
"'textbox'",
")",
"w",
"... | https://github.com/dmnfarrell/pandastable/blob/9c268b3e2bfe2e718eaee4a30bd02832a0ad1614/pandastable/plotting.py#L1751-L1773 | |
mete0r/pyhwp | c0ba652ea53e9c29a4f672491863d64cded2db5b | src/hwp5/hwp5odt.py | python | ODFValidate.__init__ | (self, relaxng_compile=None) | >>> V = ODFValidate() | >>> V = ODFValidate() | [
">>>",
"V",
"=",
"ODFValidate",
"()"
] | def __init__(self, relaxng_compile=None):
'''
>>> V = ODFValidate()
'''
if relaxng_compile is None:
try:
relaxng_compile = self.get_default_relaxng_compile()
except ImplementationNotAvailable:
relaxng_compile = None
self.relaxng_compile = relaxng_compile | [
"def",
"__init__",
"(",
"self",
",",
"relaxng_compile",
"=",
"None",
")",
":",
"if",
"relaxng_compile",
"is",
"None",
":",
"try",
":",
"relaxng_compile",
"=",
"self",
".",
"get_default_relaxng_compile",
"(",
")",
"except",
"ImplementationNotAvailable",
":",
"rel... | https://github.com/mete0r/pyhwp/blob/c0ba652ea53e9c29a4f672491863d64cded2db5b/src/hwp5/hwp5odt.py#L66-L75 | ||
lohriialo/photoshop-scripting-python | 6b97da967a5d0a45e54f7c99631b29773b923f09 | api_reference/photoshop_CC_2019.py | python | TextItem.SetColor | (self, arg0=defaultUnnamedArg) | return self._oleobj_.InvokeTypes(1413704771, LCID, 8, (24, 0), ((9, 0),),arg0
) | color of text | color of text | [
"color",
"of",
"text"
] | def SetColor(self, arg0=defaultUnnamedArg):
'color of text'
return self._oleobj_.InvokeTypes(1413704771, LCID, 8, (24, 0), ((9, 0),),arg0
) | [
"def",
"SetColor",
"(",
"self",
",",
"arg0",
"=",
"defaultUnnamedArg",
")",
":",
"return",
"self",
".",
"_oleobj_",
".",
"InvokeTypes",
"(",
"1413704771",
",",
"LCID",
",",
"8",
",",
"(",
"24",
",",
"0",
")",
",",
"(",
"(",
"9",
",",
"0",
")",
",... | https://github.com/lohriialo/photoshop-scripting-python/blob/6b97da967a5d0a45e54f7c99631b29773b923f09/api_reference/photoshop_CC_2019.py#L3174-L3177 | |
IronLanguages/main | a949455434b1fda8c783289e897e78a9a0caabb5 | External.LCA_RESTRICTED/Languages/IronPython/27/Lib/bdb.py | python | Bdb.set_return | (self, frame) | Stop when returning from the given frame. | Stop when returning from the given frame. | [
"Stop",
"when",
"returning",
"from",
"the",
"given",
"frame",
"."
] | def set_return(self, frame):
"""Stop when returning from the given frame."""
self._set_stopinfo(frame.f_back, frame) | [
"def",
"set_return",
"(",
"self",
",",
"frame",
")",
":",
"self",
".",
"_set_stopinfo",
"(",
"frame",
".",
"f_back",
",",
"frame",
")"
] | https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/bdb.py#L208-L210 | ||
selfteaching/selfteaching-python-camp | 9982ee964b984595e7d664b07c389cddaf158f1e | 19100104/Jacquesxu666/d6_exercise_stats_word.py | python | stats_text_cn | (text) | return countcn | Count the chinese words in the text | Count the chinese words in the text | [
"Count",
"the",
"chinese",
"words",
"in",
"the",
"text"
] | def stats_text_cn(text): # 统计中文词频
"""Count the chinese words in the text """ # 使用文档字符串说明
countcn={}
for i in text:
if u'\u4e00' <= i <= u'\u9fff':
countcn[i] = text.count(i)
countcn = sorted(countcn.items(), key=lambda item: item[1], reverse=True) #按出现数字从大到小排列
return countcn | [
"def",
"stats_text_cn",
"(",
"text",
")",
":",
"# 统计中文词频",
"# 使用文档字符串说明",
"countcn",
"=",
"{",
"}",
"for",
"i",
"in",
"text",
":",
"if",
"u'\\u4e00'",
"<=",
"i",
"<=",
"u'\\u9fff'",
":",
"countcn",
"[",
"i",
"]",
"=",
"text",
".",
"count",
"(",
"i",
... | https://github.com/selfteaching/selfteaching-python-camp/blob/9982ee964b984595e7d664b07c389cddaf158f1e/19100104/Jacquesxu666/d6_exercise_stats_word.py#L7-L14 | |
richardkiss/pycoin | 61d4390bfb4e4256f12ff957525f61a62343b108 | pycoin/key/Key.py | python | Key.public_pair | (self) | return self._public_pair | Return a pair of integers representing the public key (or None). | Return a pair of integers representing the public key (or None). | [
"Return",
"a",
"pair",
"of",
"integers",
"representing",
"the",
"public",
"key",
"(",
"or",
"None",
")",
"."
] | def public_pair(self):
"""
Return a pair of integers representing the public key (or None).
"""
return self._public_pair | [
"def",
"public_pair",
"(",
"self",
")",
":",
"return",
"self",
".",
"_public_pair"
] | https://github.com/richardkiss/pycoin/blob/61d4390bfb4e4256f12ff957525f61a62343b108/pycoin/key/Key.py#L101-L105 | |
happinesslz/TANet | 2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f | pointpillars_with_TANet/second/core/non_max_suppression/nms_cpu.py | python | nms_cc | (dets, thresh) | return non_max_suppression_cpu(dets, order, thresh, 1.0) | [] | def nms_cc(dets, thresh):
scores = dets[:, 4]
order = scores.argsort()[::-1].astype(np.int32) # highest->lowest
return non_max_suppression_cpu(dets, order, thresh, 1.0) | [
"def",
"nms_cc",
"(",
"dets",
",",
"thresh",
")",
":",
"scores",
"=",
"dets",
"[",
":",
",",
"4",
"]",
"order",
"=",
"scores",
".",
"argsort",
"(",
")",
"[",
":",
":",
"-",
"1",
"]",
".",
"astype",
"(",
"np",
".",
"int32",
")",
"# highest->lowe... | https://github.com/happinesslz/TANet/blob/2d4b2ab99b8e57c03671b0f1531eab7dca8f3c1f/pointpillars_with_TANet/second/core/non_max_suppression/nms_cpu.py#L25-L28 | |||
flasgger/flasgger | beb9fa781fc6b063fe3f3081b9677dd70184a2da | examples/validation_error_handler.py | python | validation_error_404 | (err, data, schema) | Custom validation error handler which produces 404 Not Found
response in case validation fails instead of 400 Bad Request | Custom validation error handler which produces 404 Not Found
response in case validation fails instead of 400 Bad Request | [
"Custom",
"validation",
"error",
"handler",
"which",
"produces",
"404",
"Not",
"Found",
"response",
"in",
"case",
"validation",
"fails",
"instead",
"of",
"400",
"Bad",
"Request"
] | def validation_error_404(err, data, schema):
"""
Custom validation error handler which produces 404 Not Found
response in case validation fails instead of 400 Bad Request
"""
abort(Response(status=HTTPStatus.NOT_FOUND)) | [
"def",
"validation_error_404",
"(",
"err",
",",
"data",
",",
"schema",
")",
":",
"abort",
"(",
"Response",
"(",
"status",
"=",
"HTTPStatus",
".",
"NOT_FOUND",
")",
")"
] | https://github.com/flasgger/flasgger/blob/beb9fa781fc6b063fe3f3081b9677dd70184a2da/examples/validation_error_handler.py#L29-L34 | ||
AndroBugs/AndroBugs_Framework | 7fd3a2cb1cf65a9af10b7ed2129701d4451493fe | tools/modified/androguard/core/bytecodes/dvm.py | python | DalvikVMFormat.get_codes_item | (self) | return self.codes | This function returns the code item
:rtype: :class:`CodeItem` object | This function returns the code item | [
"This",
"function",
"returns",
"the",
"code",
"item"
] | def get_codes_item(self):
"""
This function returns the code item
:rtype: :class:`CodeItem` object
"""
return self.codes | [
"def",
"get_codes_item",
"(",
"self",
")",
":",
"return",
"self",
".",
"codes"
] | https://github.com/AndroBugs/AndroBugs_Framework/blob/7fd3a2cb1cf65a9af10b7ed2129701d4451493fe/tools/modified/androguard/core/bytecodes/dvm.py#L7468-L7474 | |
reviewboard/reviewboard | 7395902e4c181bcd1d633f61105012ffb1d18e1b | reviewboard/ssh/storage.py | python | SSHStorage.replace_host_key | (self, hostname, old_key, new_key) | Replaces a host key in the known hosts list with another.
This is used for replacing host keys that have changed. | Replaces a host key in the known hosts list with another. | [
"Replaces",
"a",
"host",
"key",
"in",
"the",
"known",
"hosts",
"list",
"with",
"another",
"."
] | def replace_host_key(self, hostname, old_key, new_key):
"""Replaces a host key in the known hosts list with another.
This is used for replacing host keys that have changed.
"""
raise NotImplementedError | [
"def",
"replace_host_key",
"(",
"self",
",",
"hostname",
",",
"old_key",
",",
"new_key",
")",
":",
"raise",
"NotImplementedError"
] | https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/ssh/storage.py#L75-L80 | ||
Netflix/lemur | 3468be93cc84ba7a29f789155763d087ef68b7fe | lemur/plugins/lemur_acme/ultradns.py | python | Zone.status | (self) | return self._data["properties"]["status"] | Returns the status of the zone - ACTIVE, SUSPENDED, etc | Returns the status of the zone - ACTIVE, SUSPENDED, etc | [
"Returns",
"the",
"status",
"of",
"the",
"zone",
"-",
"ACTIVE",
"SUSPENDED",
"etc"
] | def status(self):
"""
Returns the status of the zone - ACTIVE, SUSPENDED, etc
"""
return self._data["properties"]["status"] | [
"def",
"status",
"(",
"self",
")",
":",
"return",
"self",
".",
"_data",
"[",
"\"properties\"",
"]",
"[",
"\"status\"",
"]"
] | https://github.com/Netflix/lemur/blob/3468be93cc84ba7a29f789155763d087ef68b7fe/lemur/plugins/lemur_acme/ultradns.py#L75-L79 | |
tensorflow/tfx | b4a6b83269815ed12ba9df9e9154c7376fef2ea0 | tfx/orchestration/metadata.py | python | Metadata.store | (self) | return self._store | Returns underlying MetadataStore.
Raises:
RuntimeError: if this instance is not in enter state. | Returns underlying MetadataStore. | [
"Returns",
"underlying",
"MetadataStore",
"."
] | def store(self) -> mlmd.MetadataStore:
"""Returns underlying MetadataStore.
Raises:
RuntimeError: if this instance is not in enter state.
"""
if self._store is None:
raise RuntimeError('Metadata object is not in enter state')
return self._store | [
"def",
"store",
"(",
"self",
")",
"->",
"mlmd",
".",
"MetadataStore",
":",
"if",
"self",
".",
"_store",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Metadata object is not in enter state'",
")",
"return",
"self",
".",
"_store"
] | https://github.com/tensorflow/tfx/blob/b4a6b83269815ed12ba9df9e9154c7376fef2ea0/tfx/orchestration/metadata.py#L162-L170 | |
pypa/setuptools | 9f37366aab9cd8f6baa23e6a77cfdb8daf97757e | setuptools/_vendor/pyparsing.py | python | FollowedBy.parseImpl | ( self, instring, loc, doActions=True ) | return loc, [] | [] | def parseImpl( self, instring, loc, doActions=True ):
self.expr.tryParse( instring, loc )
return loc, [] | [
"def",
"parseImpl",
"(",
"self",
",",
"instring",
",",
"loc",
",",
"doActions",
"=",
"True",
")",
":",
"self",
".",
"expr",
".",
"tryParse",
"(",
"instring",
",",
"loc",
")",
"return",
"loc",
",",
"[",
"]"
] | https://github.com/pypa/setuptools/blob/9f37366aab9cd8f6baa23e6a77cfdb8daf97757e/setuptools/_vendor/pyparsing.py#L3813-L3815 | |||
HyperGAN/HyperGAN | 291ddccda847e4f4ccb273bb26121a0a0d738164 | hypergan/gans/base_gan.py | python | BaseGAN.discriminator_fake_inputs | (self) | Fake inputs to the discriminator, should be cached | Fake inputs to the discriminator, should be cached | [
"Fake",
"inputs",
"to",
"the",
"discriminator",
"should",
"be",
"cached"
] | def discriminator_fake_inputs(self):
"""
Fake inputs to the discriminator, should be cached
"""
[] | [
"def",
"discriminator_fake_inputs",
"(",
"self",
")",
":",
"[",
"]"
] | https://github.com/HyperGAN/HyperGAN/blob/291ddccda847e4f4ccb273bb26121a0a0d738164/hypergan/gans/base_gan.py#L100-L104 | ||
gem/oq-engine | 1bdb88f3914e390abcbd285600bfd39477aae47c | openquake/hmtk/parsers/source_model/nrml04_parser.py | python | parse_simple_fault_node | (node, mfd_spacing=0.1, mesh_spacing=1.0) | return simple_fault | Parses a "simpleFaultSource" node and returns an instance of the :class:
openquake.hmtk.sources.simple_fault.mtkSimpleFaultSource | Parses a "simpleFaultSource" node and returns an instance of the :class:
openquake.hmtk.sources.simple_fault.mtkSimpleFaultSource | [
"Parses",
"a",
"simpleFaultSource",
"node",
"and",
"returns",
"an",
"instance",
"of",
"the",
":",
"class",
":",
"openquake",
".",
"hmtk",
".",
"sources",
".",
"simple_fault",
".",
"mtkSimpleFaultSource"
] | def parse_simple_fault_node(node, mfd_spacing=0.1, mesh_spacing=1.0):
"""
Parses a "simpleFaultSource" node and returns an instance of the :class:
openquake.hmtk.sources.simple_fault.mtkSimpleFaultSource
"""
assert "simpleFaultSource" in node.tag
sf_taglist = get_taglist(node)
# Get metadata
sf_id, name, trt = (node.attrib["id"],
node.attrib["name"],
node.attrib["tectonicRegion"])
# Process geometry
trace, dip, upper_depth, lower_depth = node_to_simple_fault_geometry(
node.nodes[sf_taglist.index("simpleFaultGeometry")])
# Process scaling relation
msr = node_to_scalerel(node.nodes[sf_taglist.index("magScaleRel")])
# Process aspect ratio
aspect = float_(node.nodes[sf_taglist.index("ruptAspectRatio")].text)
# Process MFD
mfd = node_to_mfd(node, sf_taglist)
# Process rake
rake = float_(node.nodes[sf_taglist.index("rake")].text)
simple_fault = mtkSimpleFaultSource(sf_id, name, trt,
geometry=None,
dip=dip,
upper_depth=upper_depth,
lower_depth=lower_depth,
mag_scale_rel=msr,
rupt_aspect_ratio=aspect,
mfd=mfd,
rake=rake)
simple_fault.create_geometry(trace, dip, upper_depth, lower_depth,
mesh_spacing)
return simple_fault | [
"def",
"parse_simple_fault_node",
"(",
"node",
",",
"mfd_spacing",
"=",
"0.1",
",",
"mesh_spacing",
"=",
"1.0",
")",
":",
"assert",
"\"simpleFaultSource\"",
"in",
"node",
".",
"tag",
"sf_taglist",
"=",
"get_taglist",
"(",
"node",
")",
"# Get metadata",
"sf_id",
... | https://github.com/gem/oq-engine/blob/1bdb88f3914e390abcbd285600bfd39477aae47c/openquake/hmtk/parsers/source_model/nrml04_parser.py#L381-L414 | |
zhl2008/awd-platform | 0416b31abea29743387b10b3914581fbe8e7da5e | web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/elements.py | python | Cast.__init__ | (self, expression, type_) | Produce a ``CAST`` expression.
:func:`.cast` returns an instance of :class:`.Cast`.
E.g.::
from sqlalchemy import cast, Numeric
stmt = select([
cast(product_table.c.unit_price, Numeric(10, 4))
])
The above statement will produce SQL resembling::
SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product
The :func:`.cast` function performs two distinct functions when
used. The first is that it renders the ``CAST`` expression within
the resulting SQL string. The second is that it associates the given
type (e.g. :class:`.TypeEngine` class or instance) with the column
expression on the Python side, which means the expression will take
on the expression operator behavior associated with that type,
as well as the bound-value handling and result-row-handling behavior
of the type.
.. versionchanged:: 0.9.0 :func:`.cast` now applies the given type
to the expression such that it takes effect on the bound-value,
e.g. the Python-to-database direction, in addition to the
result handling, e.g. database-to-Python, direction.
An alternative to :func:`.cast` is the :func:`.type_coerce` function.
This function performs the second task of associating an expression
with a specific type, but does not render the ``CAST`` expression
in SQL.
:param expression: A SQL expression, such as a :class:`.ColumnElement`
expression or a Python string which will be coerced into a bound
literal value.
:param type_: A :class:`.TypeEngine` class or instance indicating
the type to which the ``CAST`` should apply.
.. seealso::
:func:`.type_coerce` - Python-side type coercion without emitting
CAST. | Produce a ``CAST`` expression. | [
"Produce",
"a",
"CAST",
"expression",
"."
] | def __init__(self, expression, type_):
"""Produce a ``CAST`` expression.
:func:`.cast` returns an instance of :class:`.Cast`.
E.g.::
from sqlalchemy import cast, Numeric
stmt = select([
cast(product_table.c.unit_price, Numeric(10, 4))
])
The above statement will produce SQL resembling::
SELECT CAST(unit_price AS NUMERIC(10, 4)) FROM product
The :func:`.cast` function performs two distinct functions when
used. The first is that it renders the ``CAST`` expression within
the resulting SQL string. The second is that it associates the given
type (e.g. :class:`.TypeEngine` class or instance) with the column
expression on the Python side, which means the expression will take
on the expression operator behavior associated with that type,
as well as the bound-value handling and result-row-handling behavior
of the type.
.. versionchanged:: 0.9.0 :func:`.cast` now applies the given type
to the expression such that it takes effect on the bound-value,
e.g. the Python-to-database direction, in addition to the
result handling, e.g. database-to-Python, direction.
An alternative to :func:`.cast` is the :func:`.type_coerce` function.
This function performs the second task of associating an expression
with a specific type, but does not render the ``CAST`` expression
in SQL.
:param expression: A SQL expression, such as a :class:`.ColumnElement`
expression or a Python string which will be coerced into a bound
literal value.
:param type_: A :class:`.TypeEngine` class or instance indicating
the type to which the ``CAST`` should apply.
.. seealso::
:func:`.type_coerce` - Python-side type coercion without emitting
CAST.
"""
self.type = type_api.to_instance(type_)
self.clause = _literal_as_binds(expression, type_=self.type)
self.typeclause = TypeClause(self.type) | [
"def",
"__init__",
"(",
"self",
",",
"expression",
",",
"type_",
")",
":",
"self",
".",
"type",
"=",
"type_api",
".",
"to_instance",
"(",
"type_",
")",
"self",
".",
"clause",
"=",
"_literal_as_binds",
"(",
"expression",
",",
"type_",
"=",
"self",
".",
... | https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/sql/elements.py#L2316-L2367 | ||
oilshell/oil | 94388e7d44a9ad879b12615f6203b38596b5a2d3 | Python-2.7.13/Lib/plat-mac/aetypes.py | python | IsLogical | (x) | return isinstance(x, Logical) | [] | def IsLogical(x):
return isinstance(x, Logical) | [
"def",
"IsLogical",
"(",
"x",
")",
":",
"return",
"isinstance",
"(",
"x",
",",
"Logical",
")"
] | https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/plat-mac/aetypes.py#L239-L240 | |||
google/grr | 8ad8a4d2c5a93c92729206b7771af19d92d4f915 | grr/client_builder/grr_response_client_builder/repacking.py | python | TemplateRepacker.RepackAllTemplates | (self, upload=False) | Repack all the templates in ClientBuilder.template_dir. | Repack all the templates in ClientBuilder.template_dir. | [
"Repack",
"all",
"the",
"templates",
"in",
"ClientBuilder",
".",
"template_dir",
"."
] | def RepackAllTemplates(self, upload=False):
"""Repack all the templates in ClientBuilder.template_dir."""
for template in os.listdir(config.CONFIG["ClientBuilder.template_dir"]):
template_path = os.path.join(config.CONFIG["ClientBuilder.template_dir"],
template)
self.RepackTemplate(
template_path,
os.path.join(config.CONFIG["ClientBuilder.executables_dir"],
"installers"),
upload=upload)
# If it's windows also repack a debug version.
if template_path.endswith(".exe.zip") or template_path.endswith(
".msi.zip"):
print("Repacking as debug installer: %s." % template_path)
self.RepackTemplate(
template_path,
os.path.join(config.CONFIG["ClientBuilder.executables_dir"],
"installers"),
upload=upload,
context=["DebugClientBuild Context"]) | [
"def",
"RepackAllTemplates",
"(",
"self",
",",
"upload",
"=",
"False",
")",
":",
"for",
"template",
"in",
"os",
".",
"listdir",
"(",
"config",
".",
"CONFIG",
"[",
"\"ClientBuilder.template_dir\"",
"]",
")",
":",
"template_path",
"=",
"os",
".",
"path",
"."... | https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/client_builder/grr_response_client_builder/repacking.py#L226-L246 | ||
triaquae/triaquae | bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9 | TriAquae/models/Ubuntu_13/rsa/_version200.py | python | gen_keys | (nbits) | return (p, q, e, d) | Generate RSA keys of nbits bits. Returns (p, q, e, d).
Note: this can take a long time, depending on the key size. | Generate RSA keys of nbits bits. Returns (p, q, e, d). | [
"Generate",
"RSA",
"keys",
"of",
"nbits",
"bits",
".",
"Returns",
"(",
"p",
"q",
"e",
"d",
")",
"."
] | def gen_keys(nbits):
"""Generate RSA keys of nbits bits. Returns (p, q, e, d).
Note: this can take a long time, depending on the key size.
"""
(p, q) = find_p_q(nbits)
(e, d) = calculate_keys(p, q, nbits)
return (p, q, e, d) | [
"def",
"gen_keys",
"(",
"nbits",
")",
":",
"(",
"p",
",",
"q",
")",
"=",
"find_p_q",
"(",
"nbits",
")",
"(",
"e",
",",
"d",
")",
"=",
"calculate_keys",
"(",
"p",
",",
"q",
",",
"nbits",
")",
"return",
"(",
"p",
",",
"q",
",",
"e",
",",
"d",... | https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_13/rsa/_version200.py#L370-L379 | |
opsmop/opsmop | 376ca587f8c5f9ca8ed1829909d075c339066034 | opsmop/callbacks/replay.py | python | ReplayCallbacks.on_host_changed_list | (self, hosts) | [] | def on_host_changed_list(self, hosts):
print("\nChanged Hosts:\n")
changed = False
for host in hosts:
changed = True
actions = host.actions()
if actions:
nice_list = self.nice_changes_list(actions)
self.info(host, nice_list)
if not changed:
print(Fore.GREEN + " (None)" + Style.RESET_ALL) | [
"def",
"on_host_changed_list",
"(",
"self",
",",
"hosts",
")",
":",
"print",
"(",
"\"\\nChanged Hosts:\\n\"",
")",
"changed",
"=",
"False",
"for",
"host",
"in",
"hosts",
":",
"changed",
"=",
"True",
"actions",
"=",
"host",
".",
"actions",
"(",
")",
"if",
... | https://github.com/opsmop/opsmop/blob/376ca587f8c5f9ca8ed1829909d075c339066034/opsmop/callbacks/replay.py#L144-L155 | ||||
kakwa/ldapcherry | 4da050236db53ef2652b41c81814574e095cecfa | ldapcherry/__init__.py | python | LdapCherry.login | (self, login, password, url=None) | login page | login page | [
"login",
"page"
] | def login(self, login, password, url=None):
"""login page
"""
auth = self._auth(login, password)
cherrypy.session['isadmin'] = auth['isadmin']
cherrypy.session['connected'] = auth['connected']
if auth['connected']:
if auth['isadmin']:
message = \
"login success for user '%(user)s' as administrator" % {
'user': login
}
else:
message = \
"login success for user '%(user)s' as normal user" % {
'user': login
}
cherrypy.log.error(
msg=message,
severity=logging.INFO
)
cherrypy.session[SESSION_KEY] = cherrypy.request.login = login
if url is None:
redirect = "/"
else:
redirect = url
raise cherrypy.HTTPRedirect(redirect)
else:
message = "login failed for user '%(user)s'" % {
'user': login
}
cherrypy.log.error(
msg=message,
severity=logging.WARNING
)
if url is None:
qs = ''
else:
qs = '?url=' + quote_plus(url)
raise cherrypy.HTTPRedirect("/signin" + qs) | [
"def",
"login",
"(",
"self",
",",
"login",
",",
"password",
",",
"url",
"=",
"None",
")",
":",
"auth",
"=",
"self",
".",
"_auth",
"(",
"login",
",",
"password",
")",
"cherrypy",
".",
"session",
"[",
"'isadmin'",
"]",
"=",
"auth",
"[",
"'isadmin'",
... | https://github.com/kakwa/ldapcherry/blob/4da050236db53ef2652b41c81814574e095cecfa/ldapcherry/__init__.py#L892-L932 | ||
tribe29/checkmk | 6260f2512e159e311f426e16b84b19d0b8e9ad0c | cmk/base/plugins/agent_based/f5_bigip_cluster.py | python | parse_f5_bigip_config_sync_v11_plus | (string_table: List[StringTable]) | return State(*string_table[0][0]) if string_table[0] else None | Read a node status encoded as stringified int
>>> parse_f5_bigip_config_sync_v11_plus([[['3', 'In Sync']]])
State(state='3', description='In Sync') | Read a node status encoded as stringified int
>>> parse_f5_bigip_config_sync_v11_plus([[['3', 'In Sync']]])
State(state='3', description='In Sync') | [
"Read",
"a",
"node",
"status",
"encoded",
"as",
"stringified",
"int",
">>>",
"parse_f5_bigip_config_sync_v11_plus",
"(",
"[[[",
"3",
"In",
"Sync",
"]]]",
")",
"State",
"(",
"state",
"=",
"3",
"description",
"=",
"In",
"Sync",
")"
] | def parse_f5_bigip_config_sync_v11_plus(string_table: List[StringTable]) -> Optional[State]:
"""Read a node status encoded as stringified int
>>> parse_f5_bigip_config_sync_v11_plus([[['3', 'In Sync']]])
State(state='3', description='In Sync')
"""
return State(*string_table[0][0]) if string_table[0] else None | [
"def",
"parse_f5_bigip_config_sync_v11_plus",
"(",
"string_table",
":",
"List",
"[",
"StringTable",
"]",
")",
"->",
"Optional",
"[",
"State",
"]",
":",
"return",
"State",
"(",
"*",
"string_table",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"if",
"string_table",
"[... | https://github.com/tribe29/checkmk/blob/6260f2512e159e311f426e16b84b19d0b8e9ad0c/cmk/base/plugins/agent_based/f5_bigip_cluster.py#L115-L120 | |
cloudlinux/kuberdock-platform | 8b3923c19755f3868e4142b62578d9b9857d2704 | kubedock/kapi/podcollection.py | python | PodCollection.dump | (self, pod_id=None) | Get full information about pods.
ATTENTION! Do not use it in methods allowed for user! It may contain
secret information. FOR ADMINS ONLY! | Get full information about pods.
ATTENTION! Do not use it in methods allowed for user! It may contain
secret information. FOR ADMINS ONLY! | [
"Get",
"full",
"information",
"about",
"pods",
".",
"ATTENTION!",
"Do",
"not",
"use",
"it",
"in",
"methods",
"allowed",
"for",
"user!",
"It",
"may",
"contain",
"secret",
"information",
".",
"FOR",
"ADMINS",
"ONLY!"
] | def dump(self, pod_id=None):
"""Get full information about pods.
ATTENTION! Do not use it in methods allowed for user! It may contain
secret information. FOR ADMINS ONLY!
"""
if pod_id is None:
return self._dump_all()
else:
return self._dump_one(pod_id) | [
"def",
"dump",
"(",
"self",
",",
"pod_id",
"=",
"None",
")",
":",
"if",
"pod_id",
"is",
"None",
":",
"return",
"self",
".",
"_dump_all",
"(",
")",
"else",
":",
"return",
"self",
".",
"_dump_one",
"(",
"pod_id",
")"
] | https://github.com/cloudlinux/kuberdock-platform/blob/8b3923c19755f3868e4142b62578d9b9857d2704/kubedock/kapi/podcollection.py#L421-L429 | ||
open-cogsci/OpenSesame | c4a3641b097a80a76937edbd8c365f036bcc9705 | libqtopensesame/widgets/tree_overview.py | python | tree_overview.delete_item | (self) | desc:
Deletes the currently selected treeitem (if supported by the
treeitem). | desc:
Deletes the currently selected treeitem (if supported by the
treeitem). | [
"desc",
":",
"Deletes",
"the",
"currently",
"selected",
"treeitem",
"(",
"if",
"supported",
"by",
"the",
"treeitem",
")",
"."
] | def delete_item(self):
"""
desc:
Deletes the currently selected treeitem (if supported by the
treeitem).
"""
target_treeitem = self.currentItem()
if target_treeitem is not None:
target_treeitem.delete() | [
"def",
"delete_item",
"(",
"self",
")",
":",
"target_treeitem",
"=",
"self",
".",
"currentItem",
"(",
")",
"if",
"target_treeitem",
"is",
"not",
"None",
":",
"target_treeitem",
".",
"delete",
"(",
")"
] | https://github.com/open-cogsci/OpenSesame/blob/c4a3641b097a80a76937edbd8c365f036bcc9705/libqtopensesame/widgets/tree_overview.py#L185-L195 | ||
oracle/graalpython | 577e02da9755d916056184ec441c26e00b70145c | graalpython/lib-python/3/turtledemo/bytedesign.py | python | Designer.pentpiece | (self, initpos, scale) | [] | def pentpiece(self, initpos, scale):
oldh = self.heading()
self.up()
self.forward(29 * scale)
self.down()
for i in range(5):
self.forward(18 * scale)
self.right(72)
self.pentr(18 * scale, 75, scale)
self.up()
self.goto(initpos)
self.setheading(oldh)
self.forward(29 * scale)
self.down()
for i in range(5):
self.forward(18 * scale)
self.right(72)
self.pentl(18 * scale, 75, scale)
self.up()
self.goto(initpos)
self.setheading(oldh)
self.left(72)
self.getscreen().update() | [
"def",
"pentpiece",
"(",
"self",
",",
"initpos",
",",
"scale",
")",
":",
"oldh",
"=",
"self",
".",
"heading",
"(",
")",
"self",
".",
"up",
"(",
")",
"self",
".",
"forward",
"(",
"29",
"*",
"scale",
")",
"self",
".",
"down",
"(",
")",
"for",
"i"... | https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/turtledemo/bytedesign.py#L85-L107 | ||||
psychopy/psychopy | 01b674094f38d0e0bd51c45a6f66f671d7041696 | psychopy/data/experiment.py | python | ExperimentHandler.addData | (self, name, value) | Add the data with a given name to the current experiment.
Typically the user does not need to use this function; if you added
your data to the loop and had already added the loop to the
experiment then the loop will automatically inform the experiment
that it has received data.
Multiple data name/value pairs can be added to any given entry of
the data file and is considered part of the same entry until the
nextEntry() call is made.
e.g.::
# add some data for this trial
exp.addData('resp.rt', 0.8)
exp.addData('resp.key', 'k')
# end of trial - move to next line in data output
exp.nextEntry() | Add the data with a given name to the current experiment. | [
"Add",
"the",
"data",
"with",
"a",
"given",
"name",
"to",
"the",
"current",
"experiment",
"."
] | def addData(self, name, value):
"""Add the data with a given name to the current experiment.
Typically the user does not need to use this function; if you added
your data to the loop and had already added the loop to the
experiment then the loop will automatically inform the experiment
that it has received data.
Multiple data name/value pairs can be added to any given entry of
the data file and is considered part of the same entry until the
nextEntry() call is made.
e.g.::
# add some data for this trial
exp.addData('resp.rt', 0.8)
exp.addData('resp.key', 'k')
# end of trial - move to next line in data output
exp.nextEntry()
"""
if name not in self.dataNames:
self.dataNames.append(name)
# could just copy() every value, but not always needed, so check:
try:
hash(value)
except TypeError:
# unhashable type (list, dict, ...) == mutable, so need a copy()
value = copy.deepcopy(value)
self.thisEntry[name] = value | [
"def",
"addData",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"dataNames",
":",
"self",
".",
"dataNames",
".",
"append",
"(",
"name",
")",
"# could just copy() every value, but not always needed, so check:",
"try",
... | https://github.com/psychopy/psychopy/blob/01b674094f38d0e0bd51c45a6f66f671d7041696/psychopy/data/experiment.py#L192-L220 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.