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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
eliben/pyelftools | 8f7a0becaface09435c4374947548b7851e3d1a2 | elftools/dwarf/die.py | python | DIE.__init__ | (self, cu, stream, offset) | cu:
CompileUnit object this DIE belongs to. Used to obtain context
information (structs, abbrev table, etc.)
stream, offset:
The stream and offset into it where this DIE's data is located | cu:
CompileUnit object this DIE belongs to. Used to obtain context
information (structs, abbrev table, etc.) | [
"cu",
":",
"CompileUnit",
"object",
"this",
"DIE",
"belongs",
"to",
".",
"Used",
"to",
"obtain",
"context",
"information",
"(",
"structs",
"abbrev",
"table",
"etc",
".",
")"
] | def __init__(self, cu, stream, offset):
""" cu:
CompileUnit object this DIE belongs to. Used to obtain context
information (structs, abbrev table, etc.)
stream, offset:
The stream and offset into it where this DIE's data is located
"""
self.cu = cu
self.dwarfinfo = self.cu.dwarfinfo # get DWARFInfo context
self.stream = stream
self.offset = offset
self.attributes = OrderedDict()
self.tag = None
self.has_children = None
self.abbrev_code = None
self.size = 0
# Null DIE terminator. It can be used to obtain offset range occupied
# by this DIE including its whole subtree.
self._terminator = None
self._parent = None
self._parse_DIE() | [
"def",
"__init__",
"(",
"self",
",",
"cu",
",",
"stream",
",",
"offset",
")",
":",
"self",
".",
"cu",
"=",
"cu",
"self",
".",
"dwarfinfo",
"=",
"self",
".",
"cu",
".",
"dwarfinfo",
"# get DWARFInfo context",
"self",
".",
"stream",
"=",
"stream",
"self"... | https://github.com/eliben/pyelftools/blob/8f7a0becaface09435c4374947548b7851e3d1a2/elftools/dwarf/die.py#L71-L94 | ||
golismero/golismero | 7d605b937e241f51c1ca4f47b20f755eeefb9d76 | tools/sqlmap/thirdparty/bottle/bottle.py | python | run | (app=None, server='wsgiref', host='127.0.0.1', port=8080,
interval=1, reloader=False, quiet=False, plugins=None,
debug=False, **kargs) | Start a server instance. This method blocks until the server terminates.
:param app: WSGI application or target string supported by
:func:`load_app`. (default: :func:`default_app`)
:param server: Server adapter to use. See :data:`server_names` keys
for valid names or pass a :class:`ServerAdapter` subclass.
(default: `wsgiref`)
:param host: Server address to bind to. Pass ``0.0.0.0`` to listens on
all interfaces including the external one. (default: 127.0.0.1)
:param port: Server port to bind to. Values below 1024 require root
privileges. (default: 8080)
:param reloader: Start auto-reloading server? (default: False)
:param interval: Auto-reloader interval in seconds (default: 1)
:param quiet: Suppress output to stdout and stderr? (default: False)
:param options: Options passed to the server adapter. | Start a server instance. This method blocks until the server terminates. | [
"Start",
"a",
"server",
"instance",
".",
"This",
"method",
"blocks",
"until",
"the",
"server",
"terminates",
"."
] | def run(app=None, server='wsgiref', host='127.0.0.1', port=8080,
interval=1, reloader=False, quiet=False, plugins=None,
debug=False, **kargs):
""" Start a server instance. This method blocks until the server terminates.
:param app: WSGI application or target string supported by
:func:`load_app`. (default: :func:`default_app`)
:param server: Server adapter to use. See :data:`server_names` keys
for valid names or pass a :class:`ServerAdapter` subclass.
(default: `wsgiref`)
:param host: Server address to bind to. Pass ``0.0.0.0`` to listens on
all interfaces including the external one. (default: 127.0.0.1)
:param port: Server port to bind to. Values below 1024 require root
privileges. (default: 8080)
:param reloader: Start auto-reloading server? (default: False)
:param interval: Auto-reloader interval in seconds (default: 1)
:param quiet: Suppress output to stdout and stderr? (default: False)
:param options: Options passed to the server adapter.
"""
if NORUN: return
if reloader and not os.environ.get('BOTTLE_CHILD'):
try:
lockfile = None
fd, lockfile = tempfile.mkstemp(prefix='bottle.', suffix='.lock')
os.close(fd) # We only need this file to exist. We never write to it
while os.path.exists(lockfile):
args = [sys.executable] + sys.argv
environ = os.environ.copy()
environ['BOTTLE_CHILD'] = 'true'
environ['BOTTLE_LOCKFILE'] = lockfile
p = subprocess.Popen(args, env=environ)
while p.poll() is None: # Busy wait...
os.utime(lockfile, None) # I am alive!
time.sleep(interval)
if p.poll() != 3:
if os.path.exists(lockfile): os.unlink(lockfile)
sys.exit(p.poll())
except KeyboardInterrupt:
pass
finally:
if os.path.exists(lockfile):
os.unlink(lockfile)
return
try:
_debug(debug)
app = app or default_app()
if isinstance(app, basestring):
app = load_app(app)
if not callable(app):
raise ValueError("Application is not callable: %r" % app)
for plugin in plugins or []:
app.install(plugin)
if server in server_names:
server = server_names.get(server)
if isinstance(server, basestring):
server = load(server)
if isinstance(server, type):
server = server(host=host, port=port, **kargs)
if not isinstance(server, ServerAdapter):
raise ValueError("Unknown or unsupported server: %r" % server)
server.quiet = server.quiet or quiet
if not server.quiet:
_stderr("Bottle v%s server starting up (using %s)...\n" % (__version__, repr(server)))
_stderr("Listening on http://%s:%d/\n" % (server.host, server.port))
_stderr("Hit Ctrl-C to quit.\n\n")
if reloader:
lockfile = os.environ.get('BOTTLE_LOCKFILE')
bgcheck = FileCheckerThread(lockfile, interval)
with bgcheck:
server.run(app)
if bgcheck.status == 'reload':
sys.exit(3)
else:
server.run(app)
except KeyboardInterrupt:
pass
except (SystemExit, MemoryError):
raise
except:
if not reloader: raise
if not getattr(server, 'quiet', quiet):
print_exc()
time.sleep(interval)
sys.exit(3) | [
"def",
"run",
"(",
"app",
"=",
"None",
",",
"server",
"=",
"'wsgiref'",
",",
"host",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"8080",
",",
"interval",
"=",
"1",
",",
"reloader",
"=",
"False",
",",
"quiet",
"=",
"False",
",",
"plugins",
"=",
"None",
",... | https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/tools/sqlmap/thirdparty/bottle/bottle.py#L2629-L2717 | ||
pikpikcu/Pentest-Tools-Framework | cd6e6107764a809943dc4e073cde8149c1a2cd03 | modules/dirsearch/thirdparty/requests/utils.py | python | select_proxy | (url, proxies) | return proxy | Select a proxy for the url, if applicable.
:param url: The url being for the request
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs | Select a proxy for the url, if applicable. | [
"Select",
"a",
"proxy",
"for",
"the",
"url",
"if",
"applicable",
"."
] | def select_proxy(url, proxies):
"""Select a proxy for the url, if applicable.
:param url: The url being for the request
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
"""
proxies = proxies or {}
urlparts = urlparse(url)
proxy = proxies.get(urlparts.scheme+'://'+urlparts.hostname)
if proxy is None:
proxy = proxies.get(urlparts.scheme)
return proxy | [
"def",
"select_proxy",
"(",
"url",
",",
"proxies",
")",
":",
"proxies",
"=",
"proxies",
"or",
"{",
"}",
"urlparts",
"=",
"urlparse",
"(",
"url",
")",
"proxy",
"=",
"proxies",
".",
"get",
"(",
"urlparts",
".",
"scheme",
"+",
"'://'",
"+",
"urlparts",
... | https://github.com/pikpikcu/Pentest-Tools-Framework/blob/cd6e6107764a809943dc4e073cde8149c1a2cd03/modules/dirsearch/thirdparty/requests/utils.py#L540-L551 | |
cournape/Bento | 37de23d784407a7c98a4a15770ffc570d5f32d70 | bento/private/_yaku/yaku/tools/cxxtasks.py | python | CXXBuilder.clone | (self) | return CXXBuilder(self.ctx) | [] | def clone(self):
return CXXBuilder(self.ctx) | [
"def",
"clone",
"(",
"self",
")",
":",
"return",
"CXXBuilder",
"(",
"self",
".",
"ctx",
")"
] | https://github.com/cournape/Bento/blob/37de23d784407a7c98a4a15770ffc570d5f32d70/bento/private/_yaku/yaku/tools/cxxtasks.py#L66-L67 | |||
EventGhost/EventGhost | 177be516849e74970d2e13cda82244be09f277ce | eg/Classes/Log.py | python | Log.PrintDebugNotice | (self, *args) | Logs a message if eg.debugLevel is set. | Logs a message if eg.debugLevel is set. | [
"Logs",
"a",
"message",
"if",
"eg",
".",
"debugLevel",
"is",
"set",
"."
] | def PrintDebugNotice(self, *args):
"""
Logs a message if eg.debugLevel is set.
"""
if eg.debugLevel:
msg = _build_notice(DEBUG_ICON, args)
self.Write(msg, DEBUG_ICON) | [
"def",
"PrintDebugNotice",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"eg",
".",
"debugLevel",
":",
"msg",
"=",
"_build_notice",
"(",
"DEBUG_ICON",
",",
"args",
")",
"self",
".",
"Write",
"(",
"msg",
",",
"DEBUG_ICON",
")"
] | https://github.com/EventGhost/EventGhost/blob/177be516849e74970d2e13cda82244be09f277ce/eg/Classes/Log.py#L187-L193 | ||
buke/GreenOdoo | 3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df | runtime/python/lib/python2.7/site-packages/Werkzeug-0.8.3-py2.7.egg/werkzeug/contrib/sessions.py | python | ModificationTrackingDict.copy | (self) | return result | Create a flat copy of the dict. | Create a flat copy of the dict. | [
"Create",
"a",
"flat",
"copy",
"of",
"the",
"dict",
"."
] | def copy(self):
"""Create a flat copy of the dict."""
missing = object()
result = object.__new__(self.__class__)
for name in self.__slots__:
val = getattr(self, name, missing)
if val is not missing:
setattr(result, name, val)
return result | [
"def",
"copy",
"(",
"self",
")",
":",
"missing",
"=",
"object",
"(",
")",
"result",
"=",
"object",
".",
"__new__",
"(",
"self",
".",
"__class__",
")",
"for",
"name",
"in",
"self",
".",
"__slots__",
":",
"val",
"=",
"getattr",
"(",
"self",
",",
"nam... | https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/Werkzeug-0.8.3-py2.7.egg/werkzeug/contrib/sessions.py#L96-L104 | |
bruderstein/PythonScript | df9f7071ddf3a079e3a301b9b53a6dc78cf1208f | PythonLib/full/enum.py | python | Enum.__reduce_ex__ | (self, proto) | return self.__class__, (self._value_, ) | [] | def __reduce_ex__(self, proto):
return self.__class__, (self._value_, ) | [
"def",
"__reduce_ex__",
"(",
"self",
",",
"proto",
")",
":",
"return",
"self",
".",
"__class__",
",",
"(",
"self",
".",
"_value_",
",",
")"
] | https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/enum.py#L786-L787 | |||
etetoolkit/ete | 2b207357dc2a40ccad7bfd8f54964472c72e4726 | examples/treeview/item_faces.py | python | random_color | (h=None) | return _hls2hex(h, l, s) | Generates a random color in RGB format. | Generates a random color in RGB format. | [
"Generates",
"a",
"random",
"color",
"in",
"RGB",
"format",
"."
] | def random_color(h=None):
"""Generates a random color in RGB format."""
if not h:
h = random.random()
s = 0.5
l = 0.5
return _hls2hex(h, l, s) | [
"def",
"random_color",
"(",
"h",
"=",
"None",
")",
":",
"if",
"not",
"h",
":",
"h",
"=",
"random",
".",
"random",
"(",
")",
"s",
"=",
"0.5",
"l",
"=",
"0.5",
"return",
"_hls2hex",
"(",
"h",
",",
"l",
",",
"s",
")"
] | https://github.com/etetoolkit/ete/blob/2b207357dc2a40ccad7bfd8f54964472c72e4726/examples/treeview/item_faces.py#L42-L48 | |
wintoncode/winton-kafka-streams | 5867a1c42fc80bba07173fd1d004b2849b429fdf | winton_kafka_streams/processor/processor_context.py | python | ProcessorContext.forward | (self, key, value) | Forward the key/value to the next node in the topology | Forward the key/value to the next node in the topology | [
"Forward",
"the",
"key",
"/",
"value",
"to",
"the",
"next",
"node",
"in",
"the",
"topology"
] | def forward(self, key, value):
"""
Forward the key/value to the next node in the topology
"""
previous_node = self.current_node
try:
for child in self.current_node.children:
self.current_node = child
child.process(key, value)
finally:
self.current_node = previous_node | [
"def",
"forward",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"previous_node",
"=",
"self",
".",
"current_node",
"try",
":",
"for",
"child",
"in",
"self",
".",
"current_node",
".",
"children",
":",
"self",
".",
"current_node",
"=",
"child",
"child",... | https://github.com/wintoncode/winton-kafka-streams/blob/5867a1c42fc80bba07173fd1d004b2849b429fdf/winton_kafka_streams/processor/processor_context.py#L40-L51 | ||
dpp/simply_lift | cf49f7dcce81c7f1557314dd0f0bb08aaedc73da | elyxer.py | python | Path.getmtime | (self) | return os.path.getmtime(self.path) | Return last modification time | Return last modification time | [
"Return",
"last",
"modification",
"time"
] | def getmtime(self):
"Return last modification time"
return os.path.getmtime(self.path) | [
"def",
"getmtime",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"getmtime",
"(",
"self",
".",
"path",
")"
] | https://github.com/dpp/simply_lift/blob/cf49f7dcce81c7f1557314dd0f0bb08aaedc73da/elyxer.py#L6215-L6217 | |
holzschu/Carnets | 44effb10ddfc6aa5c8b0687582a724ba82c6b547 | Library/lib/python3.7/random.py | python | Random.vonmisesvariate | (self, mu, kappa) | return theta | Circular data distribution.
mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero. If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi. | Circular data distribution. | [
"Circular",
"data",
"distribution",
"."
] | def vonmisesvariate(self, mu, kappa):
"""Circular data distribution.
mu is the mean angle, expressed in radians between 0 and 2*pi, and
kappa is the concentration parameter, which must be greater than or
equal to zero. If kappa is equal to zero, this distribution reduces
to a uniform random angle over the range 0 to 2*pi.
"""
# mu: mean angle (in radians between 0 and 2*pi)
# kappa: concentration parameter kappa (>= 0)
# if kappa = 0 generate uniform random angle
# Based upon an algorithm published in: Fisher, N.I.,
# "Statistical Analysis of Circular Data", Cambridge
# University Press, 1993.
# Thanks to Magnus Kessler for a correction to the
# implementation of step 4.
random = self.random
if kappa <= 1e-6:
return TWOPI * random()
s = 0.5 / kappa
r = s + _sqrt(1.0 + s * s)
while 1:
u1 = random()
z = _cos(_pi * u1)
d = z / (r + z)
u2 = random()
if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d):
break
q = 1.0 / r
f = (q + z) / (1.0 + q * z)
u3 = random()
if u3 > 0.5:
theta = (mu + _acos(f)) % TWOPI
else:
theta = (mu - _acos(f)) % TWOPI
return theta | [
"def",
"vonmisesvariate",
"(",
"self",
",",
"mu",
",",
"kappa",
")",
":",
"# mu: mean angle (in radians between 0 and 2*pi)",
"# kappa: concentration parameter kappa (>= 0)",
"# if kappa = 0 generate uniform random angle",
"# Based upon an algorithm published in: Fisher, N.I.,",
"# \"... | https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/random.py#L456-L500 | |
s-block/django-nested-inline | 51936d8c003c8619b5f952dfb177385931ad62d5 | nested_inline/admin.py | python | NestedModelAdmin.save_formset | (self, request, form, formset, change) | Given an inline formset save it to the database. | Given an inline formset save it to the database. | [
"Given",
"an",
"inline",
"formset",
"save",
"it",
"to",
"the",
"database",
"."
] | def save_formset(self, request, form, formset, change):
"""
Given an inline formset save it to the database.
"""
formset.save()
for form in formset.forms:
if hasattr(form, 'nested_formsets') and form not in formset.deleted_forms:
for nested_formset in form.nested_formsets:
self.save_formset(request, form, nested_formset, change) | [
"def",
"save_formset",
"(",
"self",
",",
"request",
",",
"form",
",",
"formset",
",",
"change",
")",
":",
"formset",
".",
"save",
"(",
")",
"for",
"form",
"in",
"formset",
".",
"forms",
":",
"if",
"hasattr",
"(",
"form",
",",
"'nested_formsets'",
")",
... | https://github.com/s-block/django-nested-inline/blob/51936d8c003c8619b5f952dfb177385931ad62d5/nested_inline/admin.py#L54-L63 | ||
llSourcell/AI_Artist | 3038c06c2e389b9c919c881c9a169efe2fd7810e | lib/python2.7/site-packages/pip/_vendor/requests/utils.py | python | get_netrc_auth | (url, raise_errors=False) | Returns the Requests tuple auth for a given url from netrc. | Returns the Requests tuple auth for a given url from netrc. | [
"Returns",
"the",
"Requests",
"tuple",
"auth",
"for",
"a",
"given",
"url",
"from",
"netrc",
"."
] | def get_netrc_auth(url, raise_errors=False):
"""Returns the Requests tuple auth for a given url from netrc."""
try:
from netrc import netrc, NetrcParseError
netrc_path = None
for f in NETRC_FILES:
try:
loc = os.path.expanduser('~/{0}'.format(f))
except KeyError:
# os.path.expanduser can fail when $HOME is undefined and
# getpwuid fails. See http://bugs.python.org/issue20164 &
# https://github.com/kennethreitz/requests/issues/1846
return
if os.path.exists(loc):
netrc_path = loc
break
# Abort early if there isn't one.
if netrc_path is None:
return
ri = urlparse(url)
# Strip port numbers from netloc. This weird `if...encode`` dance is
# used for Python 3.2, which doesn't support unicode literals.
splitstr = b':'
if isinstance(url, str):
splitstr = splitstr.decode('ascii')
host = ri.netloc.split(splitstr)[0]
try:
_netrc = netrc(netrc_path).authenticators(host)
if _netrc:
# Return with login / password
login_i = (0 if _netrc[0] else 1)
return (_netrc[login_i], _netrc[2])
except (NetrcParseError, IOError):
# If there was a parsing error or a permissions issue reading the file,
# we'll just skip netrc auth unless explicitly asked to raise errors.
if raise_errors:
raise
# AppEngine hackiness.
except (ImportError, AttributeError):
pass | [
"def",
"get_netrc_auth",
"(",
"url",
",",
"raise_errors",
"=",
"False",
")",
":",
"try",
":",
"from",
"netrc",
"import",
"netrc",
",",
"NetrcParseError",
"netrc_path",
"=",
"None",
"for",
"f",
"in",
"NETRC_FILES",
":",
"try",
":",
"loc",
"=",
"os",
".",
... | https://github.com/llSourcell/AI_Artist/blob/3038c06c2e389b9c919c881c9a169efe2fd7810e/lib/python2.7/site-packages/pip/_vendor/requests/utils.py#L96-L144 | ||
reviewboard/reviewboard | 7395902e4c181bcd1d633f61105012ffb1d18e1b | reviewboard/reviews/models/review_request.py | python | ReviewRequest.close | (self, close_type=None, user=None, description=None,
rich_text=False, **kwargs) | Closes the review request.
Args:
close_type (unicode):
How the close occurs. This should be one of
:py:attr:`SUBMITTED` or :py:attr:`DISCARDED`.
user (django.contrib.auth.models.User):
The user who is closing the review request.
description (unicode):
An optional description that indicates why the review request
was closed.
rich_text (bool):
Indicates whether or not that the description is rich text.
Raises:
ValueError:
The provided close type is not a valid value.
PermissionError:
The user does not have permission to close the review request.
TypeError:
Keyword arguments were supplied to the function.
.. versionchanged:: 3.0
The ``type`` argument is deprecated: ``close_type`` should be used
instead.
This method raises :py:exc:`ValueError` instead of
:py:exc:`AttributeError` when the ``close_type`` has an incorrect
value. | Closes the review request. | [
"Closes",
"the",
"review",
"request",
"."
] | def close(self, close_type=None, user=None, description=None,
rich_text=False, **kwargs):
"""Closes the review request.
Args:
close_type (unicode):
How the close occurs. This should be one of
:py:attr:`SUBMITTED` or :py:attr:`DISCARDED`.
user (django.contrib.auth.models.User):
The user who is closing the review request.
description (unicode):
An optional description that indicates why the review request
was closed.
rich_text (bool):
Indicates whether or not that the description is rich text.
Raises:
ValueError:
The provided close type is not a valid value.
PermissionError:
The user does not have permission to close the review request.
TypeError:
Keyword arguments were supplied to the function.
.. versionchanged:: 3.0
The ``type`` argument is deprecated: ``close_type`` should be used
instead.
This method raises :py:exc:`ValueError` instead of
:py:exc:`AttributeError` when the ``close_type`` has an incorrect
value.
"""
if close_type is None:
try:
close_type = kwargs.pop('type')
except KeyError:
raise AttributeError('close_type must be provided')
warnings.warn(
'The "type" argument was deprecated in Review Board 3.0 and '
'will be removed in a future version. Use "close_type" '
'instead.'
)
if kwargs:
raise TypeError('close() does not accept keyword arguments.')
if (user and not self.is_mutable_by(user) and
not user.has_perm("reviews.can_change_status", self.local_site)):
raise PermissionError
if close_type not in [self.SUBMITTED, self.DISCARDED]:
raise ValueError("%s is not a valid close type" % type)
review_request_closing.send(
sender=type(self),
user=user,
review_request=self,
close_type=close_type,
description=description,
rich_text=rich_text)
draft = get_object_or_none(self.draft)
if self.status != close_type:
if (draft is not None and
not self.public and close_type == self.DISCARDED):
# Copy over the draft information if this is a private discard.
draft.copy_fields_to_request(self)
# TODO: Use the user's default for rich_text.
changedesc = ChangeDescription(public=True,
text=description or "",
rich_text=rich_text or False,
user=user or self.submitter)
status_field = get_review_request_field('status')(self)
status_field.record_change_entry(changedesc, self.status,
close_type)
changedesc.save()
self.changedescs.add(changedesc)
if close_type == self.SUBMITTED:
if not self.public:
raise PublishError("The draft must be public first.")
else:
self.commit_id = None
self.status = close_type
self.save(update_counts=True)
review_request_closed.send(
sender=type(self),
user=user,
review_request=self,
close_type=close_type,
description=description,
rich_text=rich_text)
else:
# Update submission description.
changedesc = self.changedescs.filter(public=True).latest()
changedesc.timestamp = timezone.now()
changedesc.text = description or ""
changedesc.rich_text = rich_text
changedesc.save()
# Needed to renew last-update.
self.save()
# Delete the associated draft review request.
if draft is not None:
draft.delete() | [
"def",
"close",
"(",
"self",
",",
"close_type",
"=",
"None",
",",
"user",
"=",
"None",
",",
"description",
"=",
"None",
",",
"rich_text",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"close_type",
"is",
"None",
":",
"try",
":",
"close_type"... | https://github.com/reviewboard/reviewboard/blob/7395902e4c181bcd1d633f61105012ffb1d18e1b/reviewboard/reviews/models/review_request.py#L951-L1068 | ||
JiYou/openstack | 8607dd488bde0905044b303eb6e52bdea6806923 | packages/source/ceilometer/tools/notificationclient.py | python | monitor_messages | (connection, topic) | Listen to notification.info messages and print them. | Listen to notification.info messages and print them. | [
"Listen",
"to",
"notification",
".",
"info",
"messages",
"and",
"print",
"them",
"."
] | def monitor_messages(connection, topic):
"""Listen to notification.info messages and print them."""
def process_event(msg):
body = msg['args']['data']
if 'resource_id' in body:
print ('%s: %s/%-15s: %s' %
(body.get('timestamp'),
body.get('resource_id'),
body.get('event_type'),
body.get('counter_volume'),
))
else:
print ('%s: %s' %
(body.get('timestamp'),
body.get('event_type'),
))
connection.declare_topic_consumer(topic, process_event)
try:
connection.consume()
except KeyboardInterrupt:
pass | [
"def",
"monitor_messages",
"(",
"connection",
",",
"topic",
")",
":",
"def",
"process_event",
"(",
"msg",
")",
":",
"body",
"=",
"msg",
"[",
"'args'",
"]",
"[",
"'data'",
"]",
"if",
"'resource_id'",
"in",
"body",
":",
"print",
"(",
"'%s: %s/%-15s: %s'",
... | https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/ceilometer/tools/notificationclient.py#L53-L74 | ||
robotframework/RIDE | 6e8a50774ff33dead3a2757a11b0b4418ab205c0 | src/robotide/lib/robot/libraries/BuiltIn.py | python | _Misc.evaluate | (self, expression, modules=None, namespace=None) | Evaluates the given expression in Python and returns the results.
``expression`` is evaluated in Python as explained in `Evaluating
expressions`.
``modules`` argument can be used to specify a comma separated
list of Python modules to be imported and added to the evaluation
namespace.
``namespace`` argument can be used to pass a custom evaluation
namespace as a dictionary. Possible ``modules`` are added to this
namespace.
Variables used like ``${variable}`` are replaced in the expression
before evaluation. Variables are also available in the evaluation
namespace and can be accessed using special syntax ``$variable``.
This is a new feature in Robot Framework 2.9 and it is explained more
thoroughly in `Evaluating expressions`.
Examples (expecting ``${result}`` is 3.14):
| ${status} = | Evaluate | 0 < ${result} < 10 | # Would also work with string '3.14' |
| ${status} = | Evaluate | 0 < $result < 10 | # Using variable itself, not string representation |
| ${random} = | Evaluate | random.randint(0, sys.maxint) | modules=random, sys |
| ${ns} = | Create Dictionary | x=${4} | y=${2} |
| ${result} = | Evaluate | x*10 + y | namespace=${ns} |
=>
| ${status} = True
| ${random} = <random integer>
| ${result} = 42 | Evaluates the given expression in Python and returns the results. | [
"Evaluates",
"the",
"given",
"expression",
"in",
"Python",
"and",
"returns",
"the",
"results",
"."
] | def evaluate(self, expression, modules=None, namespace=None):
"""Evaluates the given expression in Python and returns the results.
``expression`` is evaluated in Python as explained in `Evaluating
expressions`.
``modules`` argument can be used to specify a comma separated
list of Python modules to be imported and added to the evaluation
namespace.
``namespace`` argument can be used to pass a custom evaluation
namespace as a dictionary. Possible ``modules`` are added to this
namespace.
Variables used like ``${variable}`` are replaced in the expression
before evaluation. Variables are also available in the evaluation
namespace and can be accessed using special syntax ``$variable``.
This is a new feature in Robot Framework 2.9 and it is explained more
thoroughly in `Evaluating expressions`.
Examples (expecting ``${result}`` is 3.14):
| ${status} = | Evaluate | 0 < ${result} < 10 | # Would also work with string '3.14' |
| ${status} = | Evaluate | 0 < $result < 10 | # Using variable itself, not string representation |
| ${random} = | Evaluate | random.randint(0, sys.maxint) | modules=random, sys |
| ${ns} = | Create Dictionary | x=${4} | y=${2} |
| ${result} = | Evaluate | x*10 + y | namespace=${ns} |
=>
| ${status} = True
| ${random} = <random integer>
| ${result} = 42
"""
if is_string(expression) and '$' in expression:
expression, variables = self._handle_variables_in_expression(expression)
else:
variables = {}
namespace = self._create_evaluation_namespace(namespace, modules)
try:
if not is_string(expression):
raise TypeError("Expression must be string, got %s."
% type_name(expression))
if not expression:
raise ValueError("Expression cannot be empty.")
return eval(expression, namespace, variables)
except:
raise RuntimeError("Evaluating expression '%s' failed: %s"
% (expression, get_error_message())) | [
"def",
"evaluate",
"(",
"self",
",",
"expression",
",",
"modules",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"if",
"is_string",
"(",
"expression",
")",
"and",
"'$'",
"in",
"expression",
":",
"expression",
",",
"variables",
"=",
"self",
".",
... | https://github.com/robotframework/RIDE/blob/6e8a50774ff33dead3a2757a11b0b4418ab205c0/src/robotide/lib/robot/libraries/BuiltIn.py#L2958-L3003 | ||
hzlzh/AlfredWorkflow.com | 7055f14f6922c80ea5943839eb0caff11ae57255 | Sources/Workflows/alfred-pushbullet/lib/requests/packages/urllib3/connectionpool.py | python | HTTPConnectionPool._make_request | (self, conn, method, url, timeout=_Default,
**httplib_request_kw) | return httplib_response | Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same timeout value for
the socket connect and the socket read, or an instance of
:class:`urllib3.util.Timeout`, which gives you more fine-grained
control over your timeouts. | Perform a request on a given urllib connection object taken from our
pool. | [
"Perform",
"a",
"request",
"on",
"a",
"given",
"urllib",
"connection",
"object",
"taken",
"from",
"our",
"pool",
"."
] | def _make_request(self, conn, method, url, timeout=_Default,
**httplib_request_kw):
"""
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same timeout value for
the socket connect and the socket read, or an instance of
:class:`urllib3.util.Timeout`, which gives you more fine-grained
control over your timeouts.
"""
self.num_requests += 1
timeout_obj = self._get_timeout(timeout)
timeout_obj.start_connect()
conn.timeout = timeout_obj.connect_timeout
# Trigger any extra validation we need to do.
try:
self._validate_conn(conn)
except (SocketTimeout, BaseSSLError) as e:
# Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
raise
# conn.request() calls httplib.*.request, not the method in
# urllib3.request. It also calls makefile (recv) on the socket.
conn.request(method, url, **httplib_request_kw)
# Reset the timeout for the recv() on the socket
read_timeout = timeout_obj.read_timeout
# App Engine doesn't have a sock attr
if getattr(conn, 'sock', None):
# In Python 3 socket.py will catch EAGAIN and return None when you
# try and read into the file pointer created by http.client, which
# instead raises a BadStatusLine exception. Instead of catching
# the exception and assuming all BadStatusLine exceptions are read
# timeouts, check for a zero timeout before making the request.
if read_timeout == 0:
raise ReadTimeoutError(
self, url, "Read timed out. (read timeout=%s)" % read_timeout)
if read_timeout is Timeout.DEFAULT_TIMEOUT:
conn.sock.settimeout(socket.getdefaulttimeout())
else: # None or a value
conn.sock.settimeout(read_timeout)
# Receive the response from the server
try:
try: # Python 2.7, use buffering of HTTP responses
httplib_response = conn.getresponse(buffering=True)
except TypeError: # Python 2.6 and older
httplib_response = conn.getresponse()
except (SocketTimeout, BaseSSLError, SocketError) as e:
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
raise
# AppEngine doesn't have a version attr.
http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,
httplib_response.status,
httplib_response.length))
try:
assert_header_parsing(httplib_response.msg)
except HeaderParsingError as hpe: # Platform-specific: Python 3
log.warning(
'Failed to parse headers (url=%s): %s',
self._absolute_url(url), hpe, exc_info=True)
return httplib_response | [
"def",
"_make_request",
"(",
"self",
",",
"conn",
",",
"method",
",",
"url",
",",
"timeout",
"=",
"_Default",
",",
"*",
"*",
"httplib_request_kw",
")",
":",
"self",
".",
"num_requests",
"+=",
"1",
"timeout_obj",
"=",
"self",
".",
"_get_timeout",
"(",
"ti... | https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/alfred-pushbullet/lib/requests/packages/urllib3/connectionpool.py#L321-L396 | |
PaddlePaddle/PaddleHub | 107ee7e1a49d15e9c94da3956475d88a53fc165f | paddlehub/module/cv_module.py | python | ImageColorizeModule.run_cmd | (self, argvs: list) | return results | Run as a command. | Run as a command. | [
"Run",
"as",
"a",
"command",
"."
] | def run_cmd(self, argvs: list):
"""
Run as a command.
"""
self.parser = argparse.ArgumentParser(
description="Run the {} module.".format(self.name),
prog='hub run {}'.format(self.name),
usage='%(prog)s',
add_help=True)
self.arg_input_group = self.parser.add_argument_group(title="Input options", description="Input data. Required")
self.arg_config_group = self.parser.add_argument_group(
title="Config options", description="Run configuration for controlling module behavior, not required.")
self.add_module_config_arg()
self.add_module_input_arg()
args = self.parser.parse_args(argvs)
results = self.predict(images=[args.input_path], visualization=args.visualization, save_path=args.output_dir)
return results | [
"def",
"run_cmd",
"(",
"self",
",",
"argvs",
":",
"list",
")",
":",
"self",
".",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Run the {} module.\"",
".",
"format",
"(",
"self",
".",
"name",
")",
",",
"prog",
"=",
"'hub ru... | https://github.com/PaddlePaddle/PaddleHub/blob/107ee7e1a49d15e9c94da3956475d88a53fc165f/paddlehub/module/cv_module.py#L294-L311 | |
pjkundert/cpppo | 4c217b6c06b88bede3888cc5ea2731f271a95086 | automata.py | python | remembering.__init__ | ( self, *args, **kwds ) | [] | def __init__( self, *args, **kwds ):
super( remembering, self ).__init__( *args, **kwds )
self.memory = [] | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"super",
"(",
"remembering",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
"self",
".",
"memory",
"=",
"[",
"]"
] | https://github.com/pjkundert/cpppo/blob/4c217b6c06b88bede3888cc5ea2731f271a95086/automata.py#L240-L242 | ||||
grnet/synnefo | d06ec8c7871092131cdaabf6b03ed0b504c93e43 | snf-astakos-app/astakos/im/util.py | python | restrict_reverse | (*args, **kwargs) | return restrict_next(url, domain=domain) | Like reverse, with an additional restrict_next call to the reverse result. | Like reverse, with an additional restrict_next call to the reverse result. | [
"Like",
"reverse",
"with",
"an",
"additional",
"restrict_next",
"call",
"to",
"the",
"reverse",
"result",
"."
] | def restrict_reverse(*args, **kwargs):
"""
Like reverse, with an additional restrict_next call to the reverse result.
"""
domain = kwargs.pop('restrict_domain', settings.COOKIE_DOMAIN)
url = reverse(*args, **kwargs)
return restrict_next(url, domain=domain) | [
"def",
"restrict_reverse",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"domain",
"=",
"kwargs",
".",
"pop",
"(",
"'restrict_domain'",
",",
"settings",
".",
"COOKIE_DOMAIN",
")",
"url",
"=",
"reverse",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",... | https://github.com/grnet/synnefo/blob/d06ec8c7871092131cdaabf6b03ed0b504c93e43/snf-astakos-app/astakos/im/util.py#L168-L174 | |
21dotco/two1-python | 4e833300fd5a58363e3104ed4c097631e5d296d3 | two1/bitcoin/utils.py | python | pack_u32 | (i) | return struct.pack('<I', i) | Serializes a 32-bit integer into little-endian form.
Args:
i (int): integer to be serialized.
Returns:
b (bytes): 4 bytes containing the little-endian serialization of i. | Serializes a 32-bit integer into little-endian form. | [
"Serializes",
"a",
"32",
"-",
"bit",
"integer",
"into",
"little",
"-",
"endian",
"form",
"."
] | def pack_u32(i):
""" Serializes a 32-bit integer into little-endian form.
Args:
i (int): integer to be serialized.
Returns:
b (bytes): 4 bytes containing the little-endian serialization of i.
"""
return struct.pack('<I', i) | [
"def",
"pack_u32",
"(",
"i",
")",
":",
"return",
"struct",
".",
"pack",
"(",
"'<I'",
",",
"i",
")"
] | https://github.com/21dotco/two1-python/blob/4e833300fd5a58363e3104ed4c097631e5d296d3/two1/bitcoin/utils.py#L135-L144 | |
LonamiWebs/Telethon | f9643bf7376a5953da2050a5361c9b465f7ee7d9 | telethon_examples/gui.py | python | App.send_message | (self, event=None) | Sends a message. Does nothing if the client is not connected. | Sends a message. Does nothing if the client is not connected. | [
"Sends",
"a",
"message",
".",
"Does",
"nothing",
"if",
"the",
"client",
"is",
"not",
"connected",
"."
] | async def send_message(self, event=None):
"""
Sends a message. Does nothing if the client is not connected.
"""
if not self.cl.is_connected():
return
# The user needs to configure a chat where the message should be sent.
#
# If the chat ID does not exist, it was not valid and the user must
# configure one; hint them by changing the background to red.
if not self.chat_id:
self.chat.configure(bg='red')
self.chat.focus()
return
# Get the message, clear the text field and focus it again
text = self.message.get().strip()
self.message.delete(0, tkinter.END)
self.message.focus()
if not text:
return
# NOTE: This part is optional but supports editing messages
# You can remove it if you find it too complicated.
#
# Check if the edit matches any text
m = EDIT.match(text)
if m:
find = re.compile(m.group(1).lstrip())
# Cannot reversed(enumerate(...)), use index
for i in reversed(range(len(self.sent_text))):
msg_id, msg_text = self.sent_text[i]
if find.search(msg_text):
# Found text to replace, so replace it and edit
new = find.sub(m.group(2), msg_text)
self.sent_text[i] = (msg_id, new)
await self.cl.edit_message(self.chat_id, msg_id, new)
# Notify that a replacement was made
self.log.insert(tkinter.END, '(message edited: {} -> {})\n'
.format(msg_text, new))
self.log.yview(tkinter.END)
return
# Check if we want to delete the message
m = DELETE.match(text)
if m:
try:
delete = self.message_ids.pop(-int(m.group(1)))
except IndexError:
pass
else:
await self.cl.delete_messages(self.chat_id, delete)
# Notify that a message was deleted
self.log.insert(tkinter.END, '(message deleted)\n')
self.log.yview(tkinter.END)
return
# Check if we want to reply to some message
reply_to = None
m = REPLY.match(text)
if m:
text = m.group(2)
try:
reply_to = self.message_ids[-int(m.group(1))]
except IndexError:
pass
# NOTE: This part is no longer optional. It sends the message.
# Send the message text and get back the sent message object
message = await self.cl.send_message(self.chat_id, text,
reply_to=reply_to)
# Save the sent message ID and text to allow edits
self.sent_text.append((message.id, text))
# Process the sent message as if it were an event
await self.on_message(message) | [
"async",
"def",
"send_message",
"(",
"self",
",",
"event",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"cl",
".",
"is_connected",
"(",
")",
":",
"return",
"# The user needs to configure a chat where the message should be sent.",
"#",
"# If the chat ID does not ex... | https://github.com/LonamiWebs/Telethon/blob/f9643bf7376a5953da2050a5361c9b465f7ee7d9/telethon_examples/gui.py#L227-L305 | ||
cloudmarker/cloudmarker | 0dd2daadfa0203b3d1062e5067b14e4e0f189697 | cloudmarker/events/azlogprofileretentionevent.py | python | AzLogProfileRetentionEvent.eval | (self, record) | Evaluate Azure log profiles for retention policy.
Arguments:
record (dict): An Azure log profile record.
Yields:
dict: An event record representing an Azure log profile
with retention set to less than the required days. | Evaluate Azure log profiles for retention policy. | [
"Evaluate",
"Azure",
"log",
"profiles",
"for",
"retention",
"policy",
"."
] | def eval(self, record):
"""Evaluate Azure log profiles for retention policy.
Arguments:
record (dict): An Azure log profile record.
Yields:
dict: An event record representing an Azure log profile
with retention set to less than the required days.
"""
com = record.get('com', {})
if com is None:
return
if com.get('cloud_type') != 'azure':
return
if com.get('record_type') != 'log_profile':
return
ext = record.get('ext', {})
if ext is None:
return
if ext['retention_enabled']:
if ext['retention_days'] < self._min_retention_days:
yield from _get_log_profile_retention_event(
com, ext, self._min_retention_days)
else:
if ext['retention_days'] != 0:
yield from _get_log_profile_retention_event(
com, ext, self._min_retention_days) | [
"def",
"eval",
"(",
"self",
",",
"record",
")",
":",
"com",
"=",
"record",
".",
"get",
"(",
"'com'",
",",
"{",
"}",
")",
"if",
"com",
"is",
"None",
":",
"return",
"if",
"com",
".",
"get",
"(",
"'cloud_type'",
")",
"!=",
"'azure'",
":",
"return",
... | https://github.com/cloudmarker/cloudmarker/blob/0dd2daadfa0203b3d1062e5067b14e4e0f189697/cloudmarker/events/azlogprofileretentionevent.py#L32-L64 | ||
IJDykeman/wangTiles | 7c1ee2095ebdf7f72bce07d94c6484915d5cae8b | experimental_code/venv/lib/python2.7/site-packages/setuptools/dist.py | python | Distribution._exclude_misc | (self,name,value) | Handle 'exclude()' for list/tuple attrs without a special handler | Handle 'exclude()' for list/tuple attrs without a special handler | [
"Handle",
"exclude",
"()",
"for",
"list",
"/",
"tuple",
"attrs",
"without",
"a",
"special",
"handler"
] | def _exclude_misc(self,name,value):
"""Handle 'exclude()' for list/tuple attrs without a special handler"""
if not isinstance(value,sequence):
raise DistutilsSetupError(
"%s: setting must be a list or tuple (%r)" % (name, value)
)
try:
old = getattr(self,name)
except AttributeError:
raise DistutilsSetupError(
"%s: No such distribution setting" % name
)
if old is not None and not isinstance(old,sequence):
raise DistutilsSetupError(
name+": this setting cannot be changed via include/exclude"
)
elif old:
setattr(self,name,[item for item in old if item not in value]) | [
"def",
"_exclude_misc",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"sequence",
")",
":",
"raise",
"DistutilsSetupError",
"(",
"\"%s: setting must be a list or tuple (%r)\"",
"%",
"(",
"name",
",",
"value",
"... | https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/venv/lib/python2.7/site-packages/setuptools/dist.py#L513-L530 | ||
IronLanguages/ironpython3 | 7a7bb2a872eeab0d1009fc8a6e24dca43f65b693 | Src/StdLib/Lib/xml/dom/minidom.py | python | Comment.writexml | (self, writer, indent="", addindent="", newl="") | [] | def writexml(self, writer, indent="", addindent="", newl=""):
if "--" in self.data:
raise ValueError("'--' is not allowed in a comment node")
writer.write("%s<!--%s-->%s" % (indent, self.data, newl)) | [
"def",
"writexml",
"(",
"self",
",",
"writer",
",",
"indent",
"=",
"\"\"",
",",
"addindent",
"=",
"\"\"",
",",
"newl",
"=",
"\"\"",
")",
":",
"if",
"\"--\"",
"in",
"self",
".",
"data",
":",
"raise",
"ValueError",
"(",
"\"'--' is not allowed in a comment no... | https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/xml/dom/minidom.py#L1184-L1187 | ||||
huggingface/transformers | 623b4f7c63f60cce917677ee704d6c93ee960b4b | examples/research_projects/lxmert/utils.py | python | img_tensorize | (im, input_format="RGB") | return img | [] | def img_tensorize(im, input_format="RGB"):
assert isinstance(im, str)
if os.path.isfile(im):
img = cv2.imread(im)
else:
img = get_image_from_url(im)
assert img is not None, f"could not connect to: {im}"
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
if input_format == "RGB":
img = img[:, :, ::-1]
return img | [
"def",
"img_tensorize",
"(",
"im",
",",
"input_format",
"=",
"\"RGB\"",
")",
":",
"assert",
"isinstance",
"(",
"im",
",",
"str",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"im",
")",
":",
"img",
"=",
"cv2",
".",
"imread",
"(",
"im",
")",
"... | https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/examples/research_projects/lxmert/utils.py#L545-L555 | |||
NervanaSystems/ngraph-python | ac032c83c7152b615a9ad129d54d350f9d6a2986 | ngraph/frontends/common/utils.py | python | make_poolparams | (op, pool_shape, strides, padding) | return poolparams | Make the poolparams dictionary to be used by core ngraph
Arguments:
op (str): One of the supported pooling op types. Currently ["avg", "max"].
pool_shape (dict): int filter shape with keys of "C", "D", "H", and "W"
strides (dict): int strides with keys of "C", "D", "H", and "W"
padding: int padding with keys of "C", "D", "H", and "W"
Returns:
Properly formatted poolparams dictionary | Make the poolparams dictionary to be used by core ngraph | [
"Make",
"the",
"poolparams",
"dictionary",
"to",
"be",
"used",
"by",
"core",
"ngraph"
] | def make_poolparams(op, pool_shape, strides, padding):
"""
Make the poolparams dictionary to be used by core ngraph
Arguments:
op (str): One of the supported pooling op types. Currently ["avg", "max"].
pool_shape (dict): int filter shape with keys of "C", "D", "H", and "W"
strides (dict): int strides with keys of "C", "D", "H", and "W"
padding: int padding with keys of "C", "D", "H", and "W"
Returns:
Properly formatted poolparams dictionary
"""
poolparams = dict()
poolparams["op"] = op
for name, value in zip("JTRS", [pool_shape[nm] for nm in "CDHW"]):
poolparams[name] = value
for name in "CDHW":
for prefix, prop in zip(("str", "pad"), (strides, padding)):
poolparams["{}_{}".format(prefix, name.lower())] = prop[name]
return poolparams | [
"def",
"make_poolparams",
"(",
"op",
",",
"pool_shape",
",",
"strides",
",",
"padding",
")",
":",
"poolparams",
"=",
"dict",
"(",
")",
"poolparams",
"[",
"\"op\"",
"]",
"=",
"op",
"for",
"name",
",",
"value",
"in",
"zip",
"(",
"\"JTRS\"",
",",
"[",
"... | https://github.com/NervanaSystems/ngraph-python/blob/ac032c83c7152b615a9ad129d54d350f9d6a2986/ngraph/frontends/common/utils.py#L240-L263 | |
cesc-park/attend2u | 2154219558e9ca4dc781041aaea74d2b0607bb27 | scripts/vgg_preprocessing.py | python | _central_crop | (image_list, crop_height, crop_width) | return outputs | Performs central crops of the given image list.
Args:
image_list: a list of image tensors of the same dimension but possibly
varying channel.
crop_height: the height of the image following the crop.
crop_width: the width of the image following the crop.
Returns:
the list of cropped images. | Performs central crops of the given image list. | [
"Performs",
"central",
"crops",
"of",
"the",
"given",
"image",
"list",
"."
] | def _central_crop(image_list, crop_height, crop_width):
"""Performs central crops of the given image list.
Args:
image_list: a list of image tensors of the same dimension but possibly
varying channel.
crop_height: the height of the image following the crop.
crop_width: the width of the image following the crop.
Returns:
the list of cropped images.
"""
outputs = []
for image in image_list:
image_height = tf.shape(image)[0]
image_width = tf.shape(image)[1]
offset_height = (image_height - crop_height) / 2
offset_width = (image_width - crop_width) / 2
outputs.append(_crop(image, offset_height, offset_width,
crop_height, crop_width))
return outputs | [
"def",
"_central_crop",
"(",
"image_list",
",",
"crop_height",
",",
"crop_width",
")",
":",
"outputs",
"=",
"[",
"]",
"for",
"image",
"in",
"image_list",
":",
"image_height",
"=",
"tf",
".",
"shape",
"(",
"image",
")",
"[",
"0",
"]",
"image_width",
"=",
... | https://github.com/cesc-park/attend2u/blob/2154219558e9ca4dc781041aaea74d2b0607bb27/scripts/vgg_preprocessing.py#L178-L200 | |
pycollada/pycollada | 5b2d53333f03047b0fdfc25e394f8b77b57b62fc | collada/material.py | python | Map.__init__ | (self, sampler, texcoord, xmlnode=None) | Create a map instance to a sampler using a texcoord channel.
:param collada.material.Sampler2D sampler:
A sampler object to map
:param str texcoord:
Texture coordinate channel symbol to use
:param xmlnode:
If loaded from xml, the xml node | Create a map instance to a sampler using a texcoord channel. | [
"Create",
"a",
"map",
"instance",
"to",
"a",
"sampler",
"using",
"a",
"texcoord",
"channel",
"."
] | def __init__(self, sampler, texcoord, xmlnode=None):
"""Create a map instance to a sampler using a texcoord channel.
:param collada.material.Sampler2D sampler:
A sampler object to map
:param str texcoord:
Texture coordinate channel symbol to use
:param xmlnode:
If loaded from xml, the xml node
"""
self.sampler = sampler
""":class:`collada.material.Sampler2D` object to map"""
self.texcoord = texcoord
"""Texture coordinate channel symbol to use"""
if xmlnode != None:
self.xmlnode = xmlnode
"""ElementTree representation of the map"""
else:
self.xmlnode = E.texture(texture=self.sampler.id, texcoord=self.texcoord) | [
"def",
"__init__",
"(",
"self",
",",
"sampler",
",",
"texcoord",
",",
"xmlnode",
"=",
"None",
")",
":",
"self",
".",
"sampler",
"=",
"sampler",
"\"\"\":class:`collada.material.Sampler2D` object to map\"\"\"",
"self",
".",
"texcoord",
"=",
"texcoord",
"\"\"\"Texture ... | https://github.com/pycollada/pycollada/blob/5b2d53333f03047b0fdfc25e394f8b77b57b62fc/collada/material.py#L349-L368 | ||
coherence-project/Coherence | 88016204c7778bf0d3ad1ae331b4d8fd725dd2af | coherence/backends/appletrailers_storage.py | python | AppleTrailersStore._parse_into_trailer | (self, item) | info = item.find('info')
for attr in ('title', 'runtime', 'rating', 'studio', 'postdate',
'releasedate', 'copyright', 'director', 'description'):
setattr(trailer, attr, info.find(attr).text) | info = item.find('info') | [
"info",
"=",
"item",
".",
"find",
"(",
"info",
")"
] | def _parse_into_trailer(self, item):
"""
info = item.find('info')
for attr in ('title', 'runtime', 'rating', 'studio', 'postdate',
'releasedate', 'copyright', 'director', 'description'):
setattr(trailer, attr, info.find(attr).text)
"""
data = {}
data['id'] = item.get('id')
data['name'] = item.find('./info/title').text
data['cover'] = item.find('./poster/location').text
data['url'] = item.find('./preview/large').text
trailer = Trailer(ROOT_ID, self.urlbase, **data)
duration = None
try:
hours = 0
minutes = 0
seconds = 0
duration = item.find('./info/runtime').text
try:
hours, minutes, seconds = duration.split(':')
except ValueError:
try:
minutes, seconds = duration.split(':')
except ValueError:
seconds = duration
duration = "%d:%02d:%02d" % (int(hours), int(minutes), int(seconds))
except:
pass
try:
trailer.item.director = item.find('./info/director').text
except:
pass
try:
trailer.item.description = item.find('./info/description').text
except:
pass
res = DIDLLite.Resource(trailer.get_path(), 'http-get:*:video/quicktime:*')
res.duration = duration
try:
res.size = item.find('./preview/large').get('filesize', None)
except:
pass
trailer.item.res.append(res)
if self.server.coherence.config.get('transcoding', 'no') == 'yes':
dlna_pn = 'DLNA.ORG_PN=AVC_TS_BL_CIF15_AAC'
dlna_tags = DIDLLite.simple_dlna_tags[:]
dlna_tags[2] = 'DLNA.ORG_CI=1'
url = self.urlbase + str(trailer.id) + '?transcoded=mp4'
new_res = DIDLLite.Resource(url,
'http-get:*:%s:%s' % ('video/mp4', ';'.join([dlna_pn] + dlna_tags)))
new_res.size = None
res.duration = duration
trailer.item.res.append(new_res)
dlna_pn = 'DLNA.ORG_PN=JPEG_TN'
dlna_tags = DIDLLite.simple_dlna_tags[:]
dlna_tags[2] = 'DLNA.ORG_CI=1'
dlna_tags[3] = 'DLNA.ORG_FLAGS=00f00000000000000000000000000000'
url = self.urlbase + str(trailer.id) + '?attachment=poster&transcoded=thumb&type=jpeg'
new_res = DIDLLite.Resource(url,
'http-get:*:%s:%s' % ('image/jpeg', ';'.join([dlna_pn] + dlna_tags)))
new_res.size = None
#new_res.resolution = "160x160"
trailer.item.res.append(new_res)
if not hasattr(trailer.item, 'attachments'):
trailer.item.attachments = {}
trailer.item.attachments['poster'] = data['cover']
self.trailers[trailer.id] = trailer | [
"def",
"_parse_into_trailer",
"(",
"self",
",",
"item",
")",
":",
"data",
"=",
"{",
"}",
"data",
"[",
"'id'",
"]",
"=",
"item",
".",
"get",
"(",
"'id'",
")",
"data",
"[",
"'name'",
"]",
"=",
"item",
".",
"find",
"(",
"'./info/title'",
")",
".",
"... | https://github.com/coherence-project/Coherence/blob/88016204c7778bf0d3ad1ae331b4d8fd725dd2af/coherence/backends/appletrailers_storage.py#L137-L213 | ||
amzn/metalearn-leap | 9d6fa0c1c27fa7812cb9510ab0b23d5f25f575f0 | src/maml/maml/optim.py | python | Adam.__init__ | (self, *args, detach=False, **kwargs) | [] | def __init__(self, *args, detach=False, **kwargs):
self.detach = detach
super(Adam, self).__init__(*args, **kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"detach",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"detach",
"=",
"detach",
"super",
"(",
"Adam",
",",
"self",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"k... | https://github.com/amzn/metalearn-leap/blob/9d6fa0c1c27fa7812cb9510ab0b23d5f25f575f0/src/maml/maml/optim.py#L108-L110 | ||||
dulwich/dulwich | 1f66817d712e3563ce1ff53b1218491a2eae39da | dulwich/server.py | python | main | (argv=sys.argv) | Entry point for starting a TCP git server. | Entry point for starting a TCP git server. | [
"Entry",
"point",
"for",
"starting",
"a",
"TCP",
"git",
"server",
"."
] | def main(argv=sys.argv):
"""Entry point for starting a TCP git server."""
import optparse
parser = optparse.OptionParser()
parser.add_option(
"-l",
"--listen_address",
dest="listen_address",
default="localhost",
help="Binding IP address.",
)
parser.add_option(
"-p",
"--port",
dest="port",
type=int,
default=TCP_GIT_PORT,
help="Binding TCP port.",
)
options, args = parser.parse_args(argv)
log_utils.default_logging_config()
if len(args) > 1:
gitdir = args[1]
else:
gitdir = "."
# TODO(jelmer): Support git-daemon-export-ok and --export-all.
backend = FileSystemBackend(gitdir)
server = TCPGitServer(backend, options.listen_address, options.port)
server.serve_forever() | [
"def",
"main",
"(",
"argv",
"=",
"sys",
".",
"argv",
")",
":",
"import",
"optparse",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
")",
"parser",
".",
"add_option",
"(",
"\"-l\"",
",",
"\"--listen_address\"",
",",
"dest",
"=",
"\"listen_address\"",
... | https://github.com/dulwich/dulwich/blob/1f66817d712e3563ce1ff53b1218491a2eae39da/dulwich/server.py#L1186-L1216 | ||
PyHDI/veriloggen | 2382d200deabf59cfcfd741f5eba371010aaf2bb | veriloggen/thread/ttypes.py | python | intrinsic | (fsm, func, *args, **kwargs) | function call as an intrinsic | function call as an intrinsic | [
"function",
"call",
"as",
"an",
"intrinsic"
] | def intrinsic(fsm, func, *args, **kwargs):
""" function call as an intrinsic """
func(fsm, *args, **kwargs) | [
"def",
"intrinsic",
"(",
"fsm",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"(",
"fsm",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | https://github.com/PyHDI/veriloggen/blob/2382d200deabf59cfcfd741f5eba371010aaf2bb/veriloggen/thread/ttypes.py#L19-L21 | ||
geopython/OWSLib | 414375413c9e2bab33a2d09608ab209875ce6daf | owslib/catalogue/csw3.py | python | CatalogueServiceWeb.harvest | (self, source, resourcetype, resourceformat=None, harvestinterval=None, responsehandler=None) | Construct and process a Harvest request
Parameters
----------
- source: a URI to harvest
- resourcetype: namespace identifying the type of resource
- resourceformat: MIME type of the resource
- harvestinterval: frequency of harvesting, in ISO8601
- responsehandler: endpoint that CSW should responsd to with response | [] | def harvest(self, source, resourcetype, resourceformat=None, harvestinterval=None, responsehandler=None):
"""
Construct and process a Harvest request
Parameters
----------
- source: a URI to harvest
- resourcetype: namespace identifying the type of resource
- resourceformat: MIME type of the resource
- harvestinterval: frequency of harvesting, in ISO8601
- responsehandler: endpoint that CSW should responsd to with response
"""
# construct request
node0 = self._setrootelement('csw30:Harvest')
node0.set('version', self.version)
node0.set('service', self.service)
node0.set(util.nspath_eval('xsi:schemaLocation', namespaces), schema_location)
etree.SubElement(node0, util.nspath_eval('csw30:Source', namespaces)).text = source
etree.SubElement(node0, util.nspath_eval('csw30:ResourceType', namespaces)).text = resourcetype
if resourceformat is not None:
etree.SubElement(node0, util.nspath_eval('csw30:ResourceFormat', namespaces)).text = resourceformat
if harvestinterval is not None:
etree.SubElement(node0, util.nspath_eval('csw30:HarvestInterval', namespaces)).text = harvestinterval
if responsehandler is not None:
etree.SubElement(node0, util.nspath_eval('csw30:ResponseHandler', namespaces)).text = responsehandler
self.request = node0
self._invoke()
self.results = {}
if self.exceptionreport is None:
val = self._exml.find(util.nspath_eval('csw30:Acknowledgement', namespaces))
if util.testXMLValue(val) is not None:
ts = val.attrib.get('timeStamp')
self.timestamp = util.testXMLValue(ts, True)
id = val.find(util.nspath_eval('csw30:RequestId', namespaces))
self.id = util.testXMLValue(id)
else:
self._parsetransactionsummary()
self._parseinsertresult() | [
"def",
"harvest",
"(",
"self",
",",
"source",
",",
"resourcetype",
",",
"resourceformat",
"=",
"None",
",",
"harvestinterval",
"=",
"None",
",",
"responsehandler",
"=",
"None",
")",
":",
"# construct request",
"node0",
"=",
"self",
".",
"_setrootelement",
"(",... | https://github.com/geopython/OWSLib/blob/414375413c9e2bab33a2d09608ab209875ce6daf/owslib/catalogue/csw3.py#L373-L417 | |||
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/werkzeug/http.py | python | http_date | (timestamp=None) | return _dump_date(timestamp, ' ') | Formats the time to match the RFC1123 date format.
Accepts a floating point number expressed in seconds since the epoch in, a
datetime object or a timetuple. All times in UTC. The :func:`parse_date`
function can be used to parse such a date.
Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
:param timestamp: If provided that date is used, otherwise the current. | Formats the time to match the RFC1123 date format. | [
"Formats",
"the",
"time",
"to",
"match",
"the",
"RFC1123",
"date",
"format",
"."
] | def http_date(timestamp=None):
"""Formats the time to match the RFC1123 date format.
Accepts a floating point number expressed in seconds since the epoch in, a
datetime object or a timetuple. All times in UTC. The :func:`parse_date`
function can be used to parse such a date.
Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
:param timestamp: If provided that date is used, otherwise the current.
"""
return _dump_date(timestamp, ' ') | [
"def",
"http_date",
"(",
"timestamp",
"=",
"None",
")",
":",
"return",
"_dump_date",
"(",
"timestamp",
",",
"' '",
")"
] | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/werkzeug/http.py#L733-L744 | |
theotherp/nzbhydra | 4b03d7f769384b97dfc60dade4806c0fc987514e | libs/passlib/handlers/mssql.py | python | _parse_mssql | (hash, csize, bsize, handler) | common parser for mssql 2000/2005; returns 4 byte salt + checksum | common parser for mssql 2000/2005; returns 4 byte salt + checksum | [
"common",
"parser",
"for",
"mssql",
"2000",
"/",
"2005",
";",
"returns",
"4",
"byte",
"salt",
"+",
"checksum"
] | def _parse_mssql(hash, csize, bsize, handler):
"""common parser for mssql 2000/2005; returns 4 byte salt + checksum"""
if isinstance(hash, unicode):
if len(hash) == csize and hash.startswith(UIDENT):
try:
return unhexlify(hash[6:].encode("utf-8"))
except TypeError: # throw when bad char found
pass
elif isinstance(hash, bytes):
# assumes ascii-compat encoding
assert isinstance(hash, bytes)
if len(hash) == csize and hash.startswith(BIDENT):
try:
return unhexlify(hash[6:])
except TypeError: # throw when bad char found
pass
##elif len(hash) == bsize and hash.startswith(BIDENT2): # raw bytes
## return hash[2:]
else:
raise uh.exc.ExpectedStringError(hash, "hash")
raise uh.exc.InvalidHashError(handler) | [
"def",
"_parse_mssql",
"(",
"hash",
",",
"csize",
",",
"bsize",
",",
"handler",
")",
":",
"if",
"isinstance",
"(",
"hash",
",",
"unicode",
")",
":",
"if",
"len",
"(",
"hash",
")",
"==",
"csize",
"and",
"hash",
".",
"startswith",
"(",
"UIDENT",
")",
... | https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/passlib/handlers/mssql.py#L80-L100 | ||
Azure/azure-devops-cli-extension | 11334cd55806bef0b99c3bee5a438eed71e44037 | azure-devops/azext_devops/devops_sdk/v5_0/policy/policy_client.py | python | PolicyClient.get_policy_type | (self, project, type_id) | return self._deserialize('PolicyType', response) | GetPolicyType.
Retrieve a specific policy type by ID.
:param str project: Project ID or project name
:param str type_id: The policy ID.
:rtype: :class:`<PolicyType> <azure.devops.v5_0.policy.models.PolicyType>` | GetPolicyType.
Retrieve a specific policy type by ID.
:param str project: Project ID or project name
:param str type_id: The policy ID.
:rtype: :class:`<PolicyType> <azure.devops.v5_0.policy.models.PolicyType>` | [
"GetPolicyType",
".",
"Retrieve",
"a",
"specific",
"policy",
"type",
"by",
"ID",
".",
":",
"param",
"str",
"project",
":",
"Project",
"ID",
"or",
"project",
"name",
":",
"param",
"str",
"type_id",
":",
"The",
"policy",
"ID",
".",
":",
"rtype",
":",
":"... | def get_policy_type(self, project, type_id):
"""GetPolicyType.
Retrieve a specific policy type by ID.
:param str project: Project ID or project name
:param str type_id: The policy ID.
:rtype: :class:`<PolicyType> <azure.devops.v5_0.policy.models.PolicyType>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if type_id is not None:
route_values['typeId'] = self._serialize.url('type_id', type_id, 'str')
response = self._send(http_method='GET',
location_id='44096322-2d3d-466a-bb30-d1b7de69f61f',
version='5.0',
route_values=route_values)
return self._deserialize('PolicyType', response) | [
"def",
"get_policy_type",
"(",
"self",
",",
"project",
",",
"type_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'project'"... | https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v5_0/policy/policy_client.py#L239-L255 | |
OpenEndedGroup/Field | 4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c | Contents/lib/python/subprocess.py | python | list2cmdline | (seq) | return ''.join(result) | Translate a sequence of arguments into a command line
string, using the same rules as the MS C runtime:
1) Arguments are delimited by white space, which is either a
space or a tab.
2) A string surrounded by double quotation marks is
interpreted as a single argument, regardless of white space
or pipe characters contained within. A quoted string can be
embedded in an argument.
3) A double quotation mark preceded by a backslash is
interpreted as a literal double quotation mark.
4) Backslashes are interpreted literally, unless they
immediately precede a double quotation mark.
5) If backslashes immediately precede a double quotation mark,
every pair of backslashes is interpreted as a literal
backslash. If the number of backslashes is odd, the last
backslash escapes the next double quotation mark as
described in rule 3. | Translate a sequence of arguments into a command line
string, using the same rules as the MS C runtime: | [
"Translate",
"a",
"sequence",
"of",
"arguments",
"into",
"a",
"command",
"line",
"string",
"using",
"the",
"same",
"rules",
"as",
"the",
"MS",
"C",
"runtime",
":"
] | def list2cmdline(seq):
"""
Translate a sequence of arguments into a command line
string, using the same rules as the MS C runtime:
1) Arguments are delimited by white space, which is either a
space or a tab.
2) A string surrounded by double quotation marks is
interpreted as a single argument, regardless of white space
or pipe characters contained within. A quoted string can be
embedded in an argument.
3) A double quotation mark preceded by a backslash is
interpreted as a literal double quotation mark.
4) Backslashes are interpreted literally, unless they
immediately precede a double quotation mark.
5) If backslashes immediately precede a double quotation mark,
every pair of backslashes is interpreted as a literal
backslash. If the number of backslashes is odd, the last
backslash escapes the next double quotation mark as
described in rule 3.
"""
# See
# http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
result = []
needquote = False
for arg in seq:
bs_buf = []
# Add a space to separate this argument from the others
if result:
result.append(' ')
needquote = (" " in arg) or ("\t" in arg) or ("|" in arg) or not arg
if needquote:
result.append('"')
for c in arg:
if c == '\\':
# Don't know if we need to double yet.
bs_buf.append(c)
elif c == '"':
# Double backslashes.
result.append('\\' * len(bs_buf)*2)
bs_buf = []
result.append('\\"')
else:
# Normal char
if bs_buf:
result.extend(bs_buf)
bs_buf = []
result.append(c)
# Add remaining backslashes, if any.
if bs_buf:
result.extend(bs_buf)
if needquote:
result.extend(bs_buf)
result.append('"')
return ''.join(result) | [
"def",
"list2cmdline",
"(",
"seq",
")",
":",
"# See",
"# http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp",
"result",
"=",
"[",
"]",
"needquote",
"=",
"False",
"for",
"arg",
"in",
"seq",
":",
"bs_buf",
"=",
"[",
"]",
"# Add a space to separate this arg... | https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/subprocess.py#L478-L543 | |
uranusjr/django-tutorial-for-programmers | 9301a5428f04148e3e40b3b57b90f36f7d198fdd | lunch/lunch/stores/models.py | python | Store.get_absolute_url | (self) | return reverse('store_detail', kwargs={'pk': self.pk}) | [] | def get_absolute_url(self):
return reverse('store_detail', kwargs={'pk': self.pk}) | [
"def",
"get_absolute_url",
"(",
"self",
")",
":",
"return",
"reverse",
"(",
"'store_detail'",
",",
"kwargs",
"=",
"{",
"'pk'",
":",
"self",
".",
"pk",
"}",
")"
] | https://github.com/uranusjr/django-tutorial-for-programmers/blob/9301a5428f04148e3e40b3b57b90f36f7d198fdd/lunch/lunch/stores/models.py#L27-L28 | |||
mit-han-lab/gan-compression | d25dfb871e6cd2923d8a745f247d0c72945faf4b | utils/html.py | python | HTML.add_header | (self, text) | Insert a header to the HTML file
Parameters:
text (str) -- the header text | Insert a header to the HTML file | [
"Insert",
"a",
"header",
"to",
"the",
"HTML",
"file"
] | def add_header(self, text):
"""Insert a header to the HTML file
Parameters:
text (str) -- the header text
"""
with self.doc:
h3(text) | [
"def",
"add_header",
"(",
"self",
",",
"text",
")",
":",
"with",
"self",
".",
"doc",
":",
"h3",
"(",
"text",
")"
] | https://github.com/mit-han-lab/gan-compression/blob/d25dfb871e6cd2923d8a745f247d0c72945faf4b/utils/html.py#L39-L46 | ||
eirannejad/pyRevit | 49c0b7eb54eb343458ce1365425e6552d0c47d44 | site-packages/natsort/natsort.py | python | index_natsorted | (seq, key=None, reverse=False, alg=ns.DEFAULT) | return [x for x, _ in index_seq_pair] | Determine the list of the indexes used to sort the input sequence.
Sorts a sequence naturally, but returns a list of sorted the
indexes and not the sorted list itself. This list of indexes
can be used to sort multiple lists by the sorted order of the
given sequence.
Parameters
----------
seq : iterable
The input to sort.
key : callable, optional
A key used to determine how to sort each element of the sequence.
It is **not** applied recursively.
It should accept a single argument and return a single value.
reverse : {{True, False}}, optional
Return the list in reversed sorted order. The default is
`False`.
alg : ns enum, optional
This option is used to control which algorithm `natsort`
uses when sorting. For details into these options, please see
the :class:`ns` class documentation. The default is `ns.INT`.
Returns
-------
out : tuple
The ordered indexes of the input.
See Also
--------
natsorted
order_by_index
Examples
--------
Use index_natsorted if you want to sort multiple lists by the
sorted order of one list::
>>> a = ['num3', 'num5', 'num2']
>>> b = ['foo', 'bar', 'baz']
>>> index = index_natsorted(a)
>>> index
[2, 0, 1]
>>> # Sort both lists by the sort order of a
>>> order_by_index(a, index)
[{u}'num2', {u}'num3', {u}'num5']
>>> order_by_index(b, index)
[{u}'baz', {u}'foo', {u}'bar'] | Determine the list of the indexes used to sort the input sequence. | [
"Determine",
"the",
"list",
"of",
"the",
"indexes",
"used",
"to",
"sort",
"the",
"input",
"sequence",
"."
] | def index_natsorted(seq, key=None, reverse=False, alg=ns.DEFAULT):
"""
Determine the list of the indexes used to sort the input sequence.
Sorts a sequence naturally, but returns a list of sorted the
indexes and not the sorted list itself. This list of indexes
can be used to sort multiple lists by the sorted order of the
given sequence.
Parameters
----------
seq : iterable
The input to sort.
key : callable, optional
A key used to determine how to sort each element of the sequence.
It is **not** applied recursively.
It should accept a single argument and return a single value.
reverse : {{True, False}}, optional
Return the list in reversed sorted order. The default is
`False`.
alg : ns enum, optional
This option is used to control which algorithm `natsort`
uses when sorting. For details into these options, please see
the :class:`ns` class documentation. The default is `ns.INT`.
Returns
-------
out : tuple
The ordered indexes of the input.
See Also
--------
natsorted
order_by_index
Examples
--------
Use index_natsorted if you want to sort multiple lists by the
sorted order of one list::
>>> a = ['num3', 'num5', 'num2']
>>> b = ['foo', 'bar', 'baz']
>>> index = index_natsorted(a)
>>> index
[2, 0, 1]
>>> # Sort both lists by the sort order of a
>>> order_by_index(a, index)
[{u}'num2', {u}'num3', {u}'num5']
>>> order_by_index(b, index)
[{u}'baz', {u}'foo', {u}'bar']
"""
if key is None:
newkey = itemgetter(1)
else:
def newkey(x):
return key(itemgetter(1)(x))
# Pair the index and sequence together, then sort by element
index_seq_pair = [[x, y] for x, y in enumerate(seq)]
index_seq_pair.sort(reverse=reverse, key=natsort_keygen(newkey, alg))
return [x for x, _ in index_seq_pair] | [
"def",
"index_natsorted",
"(",
"seq",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
",",
"alg",
"=",
"ns",
".",
"DEFAULT",
")",
":",
"if",
"key",
"is",
"None",
":",
"newkey",
"=",
"itemgetter",
"(",
"1",
")",
"else",
":",
"def",
"newkey",
... | https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/natsort/natsort.py#L380-L446 | |
klb3713/sentence2vec | e38a4f5ad431ff8e5ae8015040a5da551be3b72e | utils.py | python | pyro_daemon | (name, obj, random_suffix=False, ip=None, port=None) | Register object with name server (starting the name server if not running
yet) and block until the daemon is terminated. The object is registered under
`name`, or `name`+ some random suffix if `random_suffix` is set. | Register object with name server (starting the name server if not running
yet) and block until the daemon is terminated. The object is registered under
`name`, or `name`+ some random suffix if `random_suffix` is set. | [
"Register",
"object",
"with",
"name",
"server",
"(",
"starting",
"the",
"name",
"server",
"if",
"not",
"running",
"yet",
")",
"and",
"block",
"until",
"the",
"daemon",
"is",
"terminated",
".",
"The",
"object",
"is",
"registered",
"under",
"name",
"or",
"na... | def pyro_daemon(name, obj, random_suffix=False, ip=None, port=None):
"""
Register object with name server (starting the name server if not running
yet) and block until the daemon is terminated. The object is registered under
`name`, or `name`+ some random suffix if `random_suffix` is set.
"""
if random_suffix:
name += '.' + hex(random.randint(0, 0xffffff))[2:]
import Pyro4
with getNS() as ns:
with Pyro4.Daemon(ip or get_my_ip(), port or 0) as daemon:
# register server for remote access
uri = daemon.register(obj, name)
ns.remove(name)
ns.register(name, uri)
logger.info("%s registered with nameserver (URI '%s')" % (name, uri))
daemon.requestLoop() | [
"def",
"pyro_daemon",
"(",
"name",
",",
"obj",
",",
"random_suffix",
"=",
"False",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"random_suffix",
":",
"name",
"+=",
"'.'",
"+",
"hex",
"(",
"random",
".",
"randint",
"(",
"0",
","... | https://github.com/klb3713/sentence2vec/blob/e38a4f5ad431ff8e5ae8015040a5da551be3b72e/utils.py#L740-L757 | ||
cagbal/ros_people_object_detection_tensorflow | 982ffd4a54b8059638f5cd4aa167299c7fc9e61f | src/object_detection/utils/ops.py | python | normalize_to_target | (inputs,
target_norm_value,
dim,
epsilon=1e-7,
trainable=True,
scope='NormalizeToTarget',
summarize=True) | L2 normalizes the inputs across the specified dimension to a target norm.
This op implements the L2 Normalization layer introduced in
Liu, Wei, et al. "SSD: Single Shot MultiBox Detector."
and Liu, Wei, Andrew Rabinovich, and Alexander C. Berg.
"Parsenet: Looking wider to see better." and is useful for bringing
activations from multiple layers in a convnet to a standard scale.
Note that the rank of `inputs` must be known and the dimension to which
normalization is to be applied should be statically defined.
TODO(jonathanhuang): Add option to scale by L2 norm of the entire input.
Args:
inputs: A `Tensor` of arbitrary size.
target_norm_value: A float value that specifies an initial target norm or
a list of floats (whose length must be equal to the depth along the
dimension to be normalized) specifying a per-dimension multiplier
after normalization.
dim: The dimension along which the input is normalized.
epsilon: A small value to add to the inputs to avoid dividing by zero.
trainable: Whether the norm is trainable or not
scope: Optional scope for variable_scope.
summarize: Whether or not to add a tensorflow summary for the op.
Returns:
The input tensor normalized to the specified target norm.
Raises:
ValueError: If dim is smaller than the number of dimensions in 'inputs'.
ValueError: If target_norm_value is not a float or a list of floats with
length equal to the depth along the dimension to be normalized. | L2 normalizes the inputs across the specified dimension to a target norm. | [
"L2",
"normalizes",
"the",
"inputs",
"across",
"the",
"specified",
"dimension",
"to",
"a",
"target",
"norm",
"."
] | def normalize_to_target(inputs,
target_norm_value,
dim,
epsilon=1e-7,
trainable=True,
scope='NormalizeToTarget',
summarize=True):
"""L2 normalizes the inputs across the specified dimension to a target norm.
This op implements the L2 Normalization layer introduced in
Liu, Wei, et al. "SSD: Single Shot MultiBox Detector."
and Liu, Wei, Andrew Rabinovich, and Alexander C. Berg.
"Parsenet: Looking wider to see better." and is useful for bringing
activations from multiple layers in a convnet to a standard scale.
Note that the rank of `inputs` must be known and the dimension to which
normalization is to be applied should be statically defined.
TODO(jonathanhuang): Add option to scale by L2 norm of the entire input.
Args:
inputs: A `Tensor` of arbitrary size.
target_norm_value: A float value that specifies an initial target norm or
a list of floats (whose length must be equal to the depth along the
dimension to be normalized) specifying a per-dimension multiplier
after normalization.
dim: The dimension along which the input is normalized.
epsilon: A small value to add to the inputs to avoid dividing by zero.
trainable: Whether the norm is trainable or not
scope: Optional scope for variable_scope.
summarize: Whether or not to add a tensorflow summary for the op.
Returns:
The input tensor normalized to the specified target norm.
Raises:
ValueError: If dim is smaller than the number of dimensions in 'inputs'.
ValueError: If target_norm_value is not a float or a list of floats with
length equal to the depth along the dimension to be normalized.
"""
with tf.variable_scope(scope, 'NormalizeToTarget', [inputs]):
if not inputs.get_shape():
raise ValueError('The input rank must be known.')
input_shape = inputs.get_shape().as_list()
input_rank = len(input_shape)
if dim < 0 or dim >= input_rank:
raise ValueError(
'dim must be non-negative but smaller than the input rank.')
if not input_shape[dim]:
raise ValueError('input shape should be statically defined along '
'the specified dimension.')
depth = input_shape[dim]
if not (isinstance(target_norm_value, float) or
(isinstance(target_norm_value, list) and
len(target_norm_value) == depth) and
all([isinstance(val, float) for val in target_norm_value])):
raise ValueError('target_norm_value must be a float or a list of floats '
'with length equal to the depth along the dimension to '
'be normalized.')
if isinstance(target_norm_value, float):
initial_norm = depth * [target_norm_value]
else:
initial_norm = target_norm_value
target_norm = tf.contrib.framework.model_variable(
name='weights', dtype=tf.float32,
initializer=tf.constant(initial_norm, dtype=tf.float32),
trainable=trainable)
if summarize:
mean = tf.reduce_mean(target_norm)
mean = tf.Print(mean, ['NormalizeToTarget:', mean])
tf.summary.scalar(tf.get_variable_scope().name, mean)
lengths = epsilon + tf.sqrt(tf.reduce_sum(tf.square(inputs), dim, True))
mult_shape = input_rank*[1]
mult_shape[dim] = depth
return tf.reshape(target_norm, mult_shape) * tf.truediv(inputs, lengths) | [
"def",
"normalize_to_target",
"(",
"inputs",
",",
"target_norm_value",
",",
"dim",
",",
"epsilon",
"=",
"1e-7",
",",
"trainable",
"=",
"True",
",",
"scope",
"=",
"'NormalizeToTarget'",
",",
"summarize",
"=",
"True",
")",
":",
"with",
"tf",
".",
"variable_sco... | https://github.com/cagbal/ros_people_object_detection_tensorflow/blob/982ffd4a54b8059638f5cd4aa167299c7fc9e61f/src/object_detection/utils/ops.py#L459-L533 | ||
tomplus/kubernetes_asyncio | f028cc793e3a2c519be6a52a49fb77ff0b014c9b | kubernetes_asyncio/client/api/core_v1_api.py | python | CoreV1Api.replace_persistent_volume_status | (self, name, body, **kwargs) | return self.replace_persistent_volume_status_with_http_info(name, body, **kwargs) | replace_persistent_volume_status # noqa: E501
replace status of the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_persistent_volume_status(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param V1PersistentVolume body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread. | replace_persistent_volume_status # noqa: E501 | [
"replace_persistent_volume_status",
"#",
"noqa",
":",
"E501"
] | def replace_persistent_volume_status(self, name, body, **kwargs): # noqa: E501
"""replace_persistent_volume_status # noqa: E501
replace status of the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_persistent_volume_status(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str name: name of the PersistentVolume (required)
:param V1PersistentVolume body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.replace_persistent_volume_status_with_http_info(name, body, **kwargs) | [
"def",
"replace_persistent_volume_status",
"(",
"self",
",",
"name",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"return",
"self",
".",
"replace_persistent_volume_status_with_http_info",
... | https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/api/core_v1_api.py#L28707-L28734 | |
mme/vergeml | 3dc30ba4e0f3d038743b6d468860cbcf3681acc6 | vergeml/option.py | python | Option.transform_value | (self, value) | [] | def transform_value(self, value):
if self.transform:
return self.transform(value)
else:
return value | [
"def",
"transform_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"transform",
":",
"return",
"self",
".",
"transform",
"(",
"value",
")",
"else",
":",
"return",
"value"
] | https://github.com/mme/vergeml/blob/3dc30ba4e0f3d038743b6d468860cbcf3681acc6/vergeml/option.py#L316-L320 | ||||
Tautulli/Tautulli | 2410eb33805aaac4bd1c5dad0f71e4f15afaf742 | lib/mako/ext/linguaplugin.py | python | LinguaMakoExtractor.process_python | (self, code, code_lineno, translator_strings) | [] | def process_python(self, code, code_lineno, translator_strings):
source = code.getvalue().strip()
if source.endswith(compat.b(":")):
if source in (
compat.b("try:"),
compat.b("else:"),
) or source.startswith(compat.b("except")):
source = compat.b("") # Ignore try/except and else
elif source.startswith(compat.b("elif")):
source = source[2:] # Replace "elif" with "if"
source += compat.b("pass")
code = io.BytesIO(source)
for msg in self.python_extractor(
self.filename, self.options, code, code_lineno - 1
):
if translator_strings:
msg = Message(
msg.msgctxt,
msg.msgid,
msg.msgid_plural,
msg.flags,
compat.u(" ").join(translator_strings + [msg.comment]),
msg.tcomment,
msg.location,
)
yield msg | [
"def",
"process_python",
"(",
"self",
",",
"code",
",",
"code_lineno",
",",
"translator_strings",
")",
":",
"source",
"=",
"code",
".",
"getvalue",
"(",
")",
".",
"strip",
"(",
")",
"if",
"source",
".",
"endswith",
"(",
"compat",
".",
"b",
"(",
"\":\""... | https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/mako/ext/linguaplugin.py#L40-L65 | ||||
qutip/qutip | 52d01da181a21b810c3407812c670f35fdc647e8 | qutip/bloch3d.py | python | Bloch3d.save | (self, name=None, format='png', dirc=None) | Saves Bloch sphere to file of type ``format`` in directory ``dirc``.
Parameters
----------
name : str
Name of saved image. Must include path and format as well.
i.e. '/Users/Paul/Desktop/bloch.png'
This overrides the 'format' and 'dirc' arguments.
format : str
Format of output image. Default is 'png'.
dirc : str
Directory for output images. Defaults to current working directory.
Returns
-------
File containing plot of Bloch sphere. | Saves Bloch sphere to file of type ``format`` in directory ``dirc``. | [
"Saves",
"Bloch",
"sphere",
"to",
"file",
"of",
"type",
"format",
"in",
"directory",
"dirc",
"."
] | def save(self, name=None, format='png', dirc=None):
"""Saves Bloch sphere to file of type ``format`` in directory ``dirc``.
Parameters
----------
name : str
Name of saved image. Must include path and format as well.
i.e. '/Users/Paul/Desktop/bloch.png'
This overrides the 'format' and 'dirc' arguments.
format : str
Format of output image. Default is 'png'.
dirc : str
Directory for output images. Defaults to current working directory.
Returns
-------
File containing plot of Bloch sphere.
"""
from mayavi import mlab
import os
self.make_sphere()
mlab.view(azimuth=self.view[0], elevation=self.view[1], distance=5)
if dirc:
if not os.path.isdir(os.getcwd() + "/" + str(dirc)):
os.makedirs(os.getcwd() + "/" + str(dirc))
if name is None:
if dirc:
mlab.savefig(os.getcwd() + "/" + str(dirc) + '/bloch_' +
str(self.savenum) + '.' + format)
else:
mlab.savefig(os.getcwd() + '/bloch_' + str(self.savenum) +
'.' + format)
else:
mlab.savefig(name)
self.savenum += 1
if self.fig:
mlab.close(self.fig) | [
"def",
"save",
"(",
"self",
",",
"name",
"=",
"None",
",",
"format",
"=",
"'png'",
",",
"dirc",
"=",
"None",
")",
":",
"from",
"mayavi",
"import",
"mlab",
"import",
"os",
"self",
".",
"make_sphere",
"(",
")",
"mlab",
".",
"view",
"(",
"azimuth",
"=... | https://github.com/qutip/qutip/blob/52d01da181a21b810c3407812c670f35fdc647e8/qutip/bloch3d.py#L468-L505 | ||
TencentCloud/tencentcloud-sdk-python | 3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2 | tencentcloud/mps/v20190612/models.py | python | ExpressionConfigInfo.__init__ | (self) | r"""
:param Switch: 表情识别任务开关,可选值:
<li>ON:开启;</li>
<li>OFF:关闭。</li>
:type Switch: str | r"""
:param Switch: 表情识别任务开关,可选值:
<li>ON:开启;</li>
<li>OFF:关闭。</li>
:type Switch: str | [
"r",
":",
"param",
"Switch",
":",
"表情识别任务开关,可选值:",
"<li",
">",
"ON:开启;<",
"/",
"li",
">",
"<li",
">",
"OFF:关闭。<",
"/",
"li",
">",
":",
"type",
"Switch",
":",
"str"
] | def __init__(self):
r"""
:param Switch: 表情识别任务开关,可选值:
<li>ON:开启;</li>
<li>OFF:关闭。</li>
:type Switch: str
"""
self.Switch = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"Switch",
"=",
"None"
] | https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/mps/v20190612/models.py#L7163-L7170 | ||
MultiAgentLearning/playground | 8c06a21da5758b570b708e9dd3337e1fa1e67e71 | pommerman/configs.py | python | team_competition_fast_env | () | return locals() | Start up a Team config with the competition settings. | Start up a Team config with the competition settings. | [
"Start",
"up",
"a",
"Team",
"config",
"with",
"the",
"competition",
"settings",
"."
] | def team_competition_fast_env():
"""Start up a Team config with the competition settings."""
env = envs.v0.Pomme
game_type = constants.GameType.Team
env_entry_point = 'pommerman.envs.v0:Pomme'
env_id = 'PommeTeamCompetitionFast-v0'
env_kwargs = {
'game_type': game_type,
'board_size': constants.BOARD_SIZE,
'num_rigid': constants.NUM_RIGID,
'num_wood': constants.NUM_WOOD,
'num_items': constants.NUM_ITEMS,
'max_steps': constants.MAX_STEPS,
'render_fps': 1000,
'agent_view_size': constants.AGENT_VIEW_SIZE,
'is_partially_observable': True,
'env': env_entry_point,
}
agent = characters.Bomber
return locals() | [
"def",
"team_competition_fast_env",
"(",
")",
":",
"env",
"=",
"envs",
".",
"v0",
".",
"Pomme",
"game_type",
"=",
"constants",
".",
"GameType",
".",
"Team",
"env_entry_point",
"=",
"'pommerman.envs.v0:Pomme'",
"env_id",
"=",
"'PommeTeamCompetitionFast-v0'",
"env_kwa... | https://github.com/MultiAgentLearning/playground/blob/8c06a21da5758b570b708e9dd3337e1fa1e67e71/pommerman/configs.py#L102-L121 | |
gcollazo/BrowserRefresh-Sublime | daee0eda6480c07f8636ed24e5c555d24e088886 | win/pywinauto/controls/Accessability HwndWrapper.py | python | HwndWrapper.Parent | (self) | return self._cache["parent"] | Return the parent of this control
Note that the parent of a control is not necesarily a dialog or
other main window. A group box may be the parent of some radio
buttons for example.
To get the main (or top level) window then use
HwndWrapper.TopLevelParent(). | Return the parent of this control | [
"Return",
"the",
"parent",
"of",
"this",
"control"
] | def Parent(self):
"""Return the parent of this control
Note that the parent of a control is not necesarily a dialog or
other main window. A group box may be the parent of some radio
buttons for example.
To get the main (or top level) window then use
HwndWrapper.TopLevelParent().
"""
if "parent" not in self._cache:
parent_hwnd = handleprops.parent(self)
if parent_hwnd:
#return WrapHandle(parent_hwnd)
self._cache["parent"] = HwndWrapper(parent_hwnd)
else:
self._cache["parent"] = None
return self._cache["parent"] | [
"def",
"Parent",
"(",
"self",
")",
":",
"if",
"\"parent\"",
"not",
"in",
"self",
".",
"_cache",
":",
"parent_hwnd",
"=",
"handleprops",
".",
"parent",
"(",
"self",
")",
"if",
"parent_hwnd",
":",
"#return WrapHandle(parent_hwnd)",
"self",
".",
"_cache",
"[",
... | https://github.com/gcollazo/BrowserRefresh-Sublime/blob/daee0eda6480c07f8636ed24e5c555d24e088886/win/pywinauto/controls/Accessability HwndWrapper.py#L517-L539 | |
getlogbook/logbook | 3e0badb395ed8d0038d02996d38aa0505441327e | logbook/compat.py | python | LoggingHandler.convert_time | (self, dt) | return seconds | Converts a datetime object into a timestamp. | Converts a datetime object into a timestamp. | [
"Converts",
"a",
"datetime",
"object",
"into",
"a",
"timestamp",
"."
] | def convert_time(self, dt):
"""Converts a datetime object into a timestamp."""
year, month, day, hour, minute, second = dt.utctimetuple()[:6]
days = date(year, month, 1).toordinal() - _epoch_ord + day - 1
hours = days * 24 + hour
minutes = hours * 60 + minute
seconds = minutes * 60 + second
return seconds | [
"def",
"convert_time",
"(",
"self",
",",
"dt",
")",
":",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"minute",
",",
"second",
"=",
"dt",
".",
"utctimetuple",
"(",
")",
"[",
":",
"6",
"]",
"days",
"=",
"date",
"(",
"year",
",",
"month",
... | https://github.com/getlogbook/logbook/blob/3e0badb395ed8d0038d02996d38aa0505441327e/logbook/compat.py#L194-L201 | |
araffin/robotics-rl-srl | eae7c1ab310c79662f6e68c0d255e08641037ffa | environments/robobo_gym/robobo_env.py | python | RoboboEnv.render | (self, mode='rgb_array') | return self.observation | :param mode: (str)
:return: (numpy array) BGR image | :param mode: (str)
:return: (numpy array) BGR image | [
":",
"param",
"mode",
":",
"(",
"str",
")",
":",
"return",
":",
"(",
"numpy",
"array",
")",
"BGR",
"image"
] | def render(self, mode='rgb_array'):
"""
:param mode: (str)
:return: (numpy array) BGR image
"""
if mode != "rgb_array":
print('render in human mode not yet supported')
return np.array([])
if self._renders:
plt.ion() # needed for interactive update
if self.image_plot is None:
plt.figure('Robobo RL')
self.image_plot = plt.imshow(bgr2rgb(self.observation), cmap='gray')
self.image_plot.axes.grid(False)
else:
self.image_plot.set_data(bgr2rgb(self.observation))
plt.draw()
# Wait a bit, so that plot is visible
plt.pause(0.0001)
return self.observation | [
"def",
"render",
"(",
"self",
",",
"mode",
"=",
"'rgb_array'",
")",
":",
"if",
"mode",
"!=",
"\"rgb_array\"",
":",
"print",
"(",
"'render in human mode not yet supported'",
")",
"return",
"np",
".",
"array",
"(",
"[",
"]",
")",
"if",
"self",
".",
"_renders... | https://github.com/araffin/robotics-rl-srl/blob/eae7c1ab310c79662f6e68c0d255e08641037ffa/environments/robobo_gym/robobo_env.py#L241-L261 | |
ogroth/tf-gqn | 8a517f0142b06f766f0cfd576b7ecdf16e92eab7 | gqn/gqn_draw.py | python | GQNLSTMCell.call | (self, inputs, state, scope=None) | return output, new_state | :param inputs: list of inputs
:param state: cell (c), and hidden (h) states
:param scope:
:return: | :param inputs: list of inputs
:param state: cell (c), and hidden (h) states
:param scope:
:return: | [
":",
"param",
"inputs",
":",
"list",
"of",
"inputs",
":",
"param",
"state",
":",
"cell",
"(",
"c",
")",
"and",
"hidden",
"(",
"h",
")",
"states",
":",
"param",
"scope",
":",
":",
"return",
":"
] | def call(self, inputs, state, scope=None):
"""
:param inputs: list of inputs
:param state: cell (c), and hidden (h) states
:param scope:
:return:
"""
cell_state, hidden_state = state
inputs[self._hidden_state_name] = hidden_state
with tf.name_scope("InputConv"):
new_hidden = self._conv(inputs)
gates = tf.split(value=new_hidden, num_or_size_splits=4, axis=-1)
input_gate, new_input, forget_gate, output_gate = gates
with tf.name_scope("Forget"):
new_cell = tf.nn.sigmoid(forget_gate + self._forget_bias) * cell_state
with tf.name_scope("Update"):
new_cell += tf.nn.sigmoid(input_gate) * tf.nn.tanh(new_input)
with tf.name_scope("Output"):
output = tf.nn.tanh(new_cell) * tf.nn.sigmoid(output_gate)
new_state = tf.contrib.rnn.LSTMStateTuple(new_cell, output)
return output, new_state | [
"def",
"call",
"(",
"self",
",",
"inputs",
",",
"state",
",",
"scope",
"=",
"None",
")",
":",
"cell_state",
",",
"hidden_state",
"=",
"state",
"inputs",
"[",
"self",
".",
"_hidden_state_name",
"]",
"=",
"hidden_state",
"with",
"tf",
".",
"name_scope",
"(... | https://github.com/ogroth/tf-gqn/blob/8a517f0142b06f766f0cfd576b7ecdf16e92eab7/gqn/gqn_draw.py#L89-L117 | |
Ultimaker/Cura | a1622c77ea7259ecb956acd6de07b7d34b7ac52b | cura/Scene/ConvexHullNode.py | python | ConvexHullNode.__init__ | (self, node: SceneNode, hull: Optional[Polygon], thickness: float, parent: Optional[SceneNode] = None) | Convex hull node is a special type of scene node that is used to display an area, to indicate the
location an object uses on the buildplate. This area (or area's in case of one at a time printing) is
then displayed as a transparent shadow. If the adhesion type is set to raft, the area is extruded
to represent the raft as well. | Convex hull node is a special type of scene node that is used to display an area, to indicate the | [
"Convex",
"hull",
"node",
"is",
"a",
"special",
"type",
"of",
"scene",
"node",
"that",
"is",
"used",
"to",
"display",
"an",
"area",
"to",
"indicate",
"the"
] | def __init__(self, node: SceneNode, hull: Optional[Polygon], thickness: float, parent: Optional[SceneNode] = None) -> None:
"""Convex hull node is a special type of scene node that is used to display an area, to indicate the
location an object uses on the buildplate. This area (or area's in case of one at a time printing) is
then displayed as a transparent shadow. If the adhesion type is set to raft, the area is extruded
to represent the raft as well.
"""
super().__init__(parent)
self.setCalculateBoundingBox(False)
self._original_parent = parent
# Color of the drawn convex hull
if not Application.getInstance().getIsHeadLess():
theme = QtApplication.getInstance().getTheme()
if theme:
self._color = Color(*theme.getColor("convex_hull").getRgb())
else:
self._color = Color(0, 0, 0)
else:
self._color = Color(0, 0, 0)
# The y-coordinate of the convex hull mesh. Must not be 0, to prevent z-fighting.
self._mesh_height = 0.1
self._thickness = thickness
# The node this mesh is "watching"
self._node = node
# Area of the head + fans for display as a shadow on the buildplate
self._convex_hull_head_mesh = None # type: Optional[MeshData]
self._node.decoratorsChanged.connect(self._onNodeDecoratorsChanged)
self._onNodeDecoratorsChanged(self._node)
self._hull = hull
if self._hull:
hull_mesh_builder = MeshBuilder()
if self._thickness == 0:
if hull_mesh_builder.addConvexPolygon(
self._hull.getPoints()[::], # bottom layer is reversed
self._mesh_height, color = self._color):
hull_mesh_builder.resetNormals()
hull_mesh = hull_mesh_builder.build()
self.setMeshData(hull_mesh)
else:
if hull_mesh_builder.addConvexPolygonExtrusion(
self._hull.getPoints()[::-1], # bottom layer is reversed
self._mesh_height - thickness, self._mesh_height, color = self._color):
hull_mesh_builder.resetNormals()
hull_mesh = hull_mesh_builder.build()
self.setMeshData(hull_mesh) | [
"def",
"__init__",
"(",
"self",
",",
"node",
":",
"SceneNode",
",",
"hull",
":",
"Optional",
"[",
"Polygon",
"]",
",",
"thickness",
":",
"float",
",",
"parent",
":",
"Optional",
"[",
"SceneNode",
"]",
"=",
"None",
")",
"->",
"None",
":",
"super",
"("... | https://github.com/Ultimaker/Cura/blob/a1622c77ea7259ecb956acd6de07b7d34b7ac52b/cura/Scene/ConvexHullNode.py#L21-L74 | ||
bigmlcom/python | 35f69d2f3121f1b3dde43495cf145d4992796ad5 | bigml/linear.py | python | LinearRegression.predict | (self, input_data, full=False) | return result | Returns the prediction and the confidence intervals
input_data: Input data to be predicted
full: Boolean that controls whether to include the prediction's
attributes. By default, only the prediction is produced. If set
to True, the rest of available information is added in a
dictionary format. The dictionary keys can be:
- prediction: the prediction value
- unused_fields: list of fields in the input data that
are not being used in the model | Returns the prediction and the confidence intervals | [
"Returns",
"the",
"prediction",
"and",
"the",
"confidence",
"intervals"
] | def predict(self, input_data, full=False):
"""Returns the prediction and the confidence intervals
input_data: Input data to be predicted
full: Boolean that controls whether to include the prediction's
attributes. By default, only the prediction is produced. If set
to True, the rest of available information is added in a
dictionary format. The dictionary keys can be:
- prediction: the prediction value
- unused_fields: list of fields in the input data that
are not being used in the model
"""
# Checks and cleans input_data leaving the fields used in the model
unused_fields = []
norm_input_data = self.filter_input_data( \
input_data,
add_unused_fields=full)
if full:
norm_input_data, unused_fields = norm_input_data
# Strips affixes for numeric values and casts to the final field type
cast(norm_input_data, self.fields)
# In case that the training data has no missings, input data shouldn't
check_no_training_missings(norm_input_data, self.model_fields,
self.weight_field,
self.objective_id)
# Computes text and categorical field expansion
unique_terms = self.get_unique_terms(norm_input_data)
# Creates an input vector with the values for all expanded fields.
input_array = self.expand_input(norm_input_data, unique_terms)
compact_input_array = self.expand_input(norm_input_data, unique_terms,
True)
prediction = dot([flatten(self.coefficients)], [input_array])[0][0]
result = {
"prediction": prediction}
if self.xtx_inverse:
result.update({"confidence_bounds": self.confidence_bounds( \
compact_input_array)})
if full:
result.update({"unused_fields": unused_fields})
else:
result = result["prediction"]
return result | [
"def",
"predict",
"(",
"self",
",",
"input_data",
",",
"full",
"=",
"False",
")",
":",
"# Checks and cleans input_data leaving the fields used in the model",
"unused_fields",
"=",
"[",
"]",
"norm_input_data",
"=",
"self",
".",
"filter_input_data",
"(",
"input_data",
"... | https://github.com/bigmlcom/python/blob/35f69d2f3121f1b3dde43495cf145d4992796ad5/bigml/linear.py#L285-L336 | |
tobegit3hub/deep_image_model | 8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e | java_predict_client/src/main/proto/tensorflow/models/embedding/word2vec.py | python | Word2Vec._predict | (self, analogy) | return idx | Predict the top 4 answers for analogy questions. | Predict the top 4 answers for analogy questions. | [
"Predict",
"the",
"top",
"4",
"answers",
"for",
"analogy",
"questions",
"."
] | def _predict(self, analogy):
"""Predict the top 4 answers for analogy questions."""
idx, = self._session.run([self._analogy_pred_idx], {
self._analogy_a: analogy[:, 0],
self._analogy_b: analogy[:, 1],
self._analogy_c: analogy[:, 2]
})
return idx | [
"def",
"_predict",
"(",
"self",
",",
"analogy",
")",
":",
"idx",
",",
"=",
"self",
".",
"_session",
".",
"run",
"(",
"[",
"self",
".",
"_analogy_pred_idx",
"]",
",",
"{",
"self",
".",
"_analogy_a",
":",
"analogy",
"[",
":",
",",
"0",
"]",
",",
"s... | https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/models/embedding/word2vec.py#L434-L441 | |
scikit-learn/scikit-learn | 1d1aadd0711b87d2a11c80aad15df6f8cf156712 | sklearn/covariance/_robust_covariance.py | python | MinCovDet.fit | (self, X, y=None) | return self | Fit a Minimum Covariance Determinant with the FastMCD algorithm.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
self : object
Returns the instance itself. | Fit a Minimum Covariance Determinant with the FastMCD algorithm. | [
"Fit",
"a",
"Minimum",
"Covariance",
"Determinant",
"with",
"the",
"FastMCD",
"algorithm",
"."
] | def fit(self, X, y=None):
"""Fit a Minimum Covariance Determinant with the FastMCD algorithm.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
self : object
Returns the instance itself.
"""
X = self._validate_data(X, ensure_min_samples=2, estimator="MinCovDet")
random_state = check_random_state(self.random_state)
n_samples, n_features = X.shape
# check that the empirical covariance is full rank
if (linalg.svdvals(np.dot(X.T, X)) > 1e-8).sum() != n_features:
warnings.warn(
"The covariance matrix associated to your dataset is not full rank"
)
# compute and store raw estimates
raw_location, raw_covariance, raw_support, raw_dist = fast_mcd(
X,
support_fraction=self.support_fraction,
cov_computation_method=self._nonrobust_covariance,
random_state=random_state,
)
if self.assume_centered:
raw_location = np.zeros(n_features)
raw_covariance = self._nonrobust_covariance(
X[raw_support], assume_centered=True
)
# get precision matrix in an optimized way
precision = linalg.pinvh(raw_covariance)
raw_dist = np.sum(np.dot(X, precision) * X, 1)
self.raw_location_ = raw_location
self.raw_covariance_ = raw_covariance
self.raw_support_ = raw_support
self.location_ = raw_location
self.support_ = raw_support
self.dist_ = raw_dist
# obtain consistency at normal models
self.correct_covariance(X)
# re-weight estimator
self.reweight_covariance(X)
return self | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"X",
"=",
"self",
".",
"_validate_data",
"(",
"X",
",",
"ensure_min_samples",
"=",
"2",
",",
"estimator",
"=",
"\"MinCovDet\"",
")",
"random_state",
"=",
"check_random_state",
"(",
"... | https://github.com/scikit-learn/scikit-learn/blob/1d1aadd0711b87d2a11c80aad15df6f8cf156712/sklearn/covariance/_robust_covariance.py#L716-L767 | |
odlgroup/odl | 0b088df8dc4621c68b9414c3deff9127f4c4f11d | odl/solvers/functional/functional.py | python | FunctionalQuadraticPerturb.convex_conj | (self) | r"""Convex conjugate functional of the functional.
Notes
-----
Given a functional :math:`f`, the convex conjugate of a linearly
perturbed version :math:`f(x) + <y, x>` is given by a translation of
the convex conjugate of :math:`f`:
.. math::
(f + \langle y, \cdot \rangle)^* (x^*) = f^*(x^* - y).
For reference on the identity used, see `[KP2015]`_. Moreover, the
convex conjugate of :math:`f + c` is by definition
.. math::
(f + c)^* (x^*) = f^*(x^*) - c.
References
----------
[KP2015] Komodakis, N, and Pesquet, J-C. *Playing with Duality: An
overview of recent primal-dual approaches for solving large-scale
optimization problems*. IEEE Signal Processing Magazine, 32.6 (2015),
pp 31--54.
.. _[KP2015]: https://arxiv.org/abs/1406.5429 | r"""Convex conjugate functional of the functional. | [
"r",
"Convex",
"conjugate",
"functional",
"of",
"the",
"functional",
"."
] | def convex_conj(self):
r"""Convex conjugate functional of the functional.
Notes
-----
Given a functional :math:`f`, the convex conjugate of a linearly
perturbed version :math:`f(x) + <y, x>` is given by a translation of
the convex conjugate of :math:`f`:
.. math::
(f + \langle y, \cdot \rangle)^* (x^*) = f^*(x^* - y).
For reference on the identity used, see `[KP2015]`_. Moreover, the
convex conjugate of :math:`f + c` is by definition
.. math::
(f + c)^* (x^*) = f^*(x^*) - c.
References
----------
[KP2015] Komodakis, N, and Pesquet, J-C. *Playing with Duality: An
overview of recent primal-dual approaches for solving large-scale
optimization problems*. IEEE Signal Processing Magazine, 32.6 (2015),
pp 31--54.
.. _[KP2015]: https://arxiv.org/abs/1406.5429
"""
if self.quadratic_coeff == 0:
cconj = self.functional.convex_conj.translated(self.linear_term)
if self.constant != 0:
cconj = cconj - self.constant
return cconj
else:
return super(FunctionalQuadraticPerturb, self).convex_conj | [
"def",
"convex_conj",
"(",
"self",
")",
":",
"if",
"self",
".",
"quadratic_coeff",
"==",
"0",
":",
"cconj",
"=",
"self",
".",
"functional",
".",
"convex_conj",
".",
"translated",
"(",
"self",
".",
"linear_term",
")",
"if",
"self",
".",
"constant",
"!=",
... | https://github.com/odlgroup/odl/blob/0b088df8dc4621c68b9414c3deff9127f4c4f11d/odl/solvers/functional/functional.py#L1070-L1104 | ||
chapmanb/cloudbiolinux | f6d0414bdba495944aaccf19ae55ba50b13da892 | cloudbio/custom/bio_nextgen.py | python | install_echo | (env) | ECHO: A reference-free short-read error correction algorithm
http://uc-echo.sourceforge.net/ | ECHO: A reference-free short-read error correction algorithm
http://uc-echo.sourceforge.net/ | [
"ECHO",
":",
"A",
"reference",
"-",
"free",
"short",
"-",
"read",
"error",
"correction",
"algorithm",
"http",
":",
"//",
"uc",
"-",
"echo",
".",
"sourceforge",
".",
"net",
"/"
] | def install_echo(env):
"""ECHO: A reference-free short-read error correction algorithm
http://uc-echo.sourceforge.net/
"""
version = "1_12"
url = "http://downloads.sourceforge.net/project/uc-echo/source%20release/" \
"echo_v{0}.tgz".format(version)
_get_install_local(url, env, _make_copy()) | [
"def",
"install_echo",
"(",
"env",
")",
":",
"version",
"=",
"\"1_12\"",
"url",
"=",
"\"http://downloads.sourceforge.net/project/uc-echo/source%20release/\"",
"\"echo_v{0}.tgz\"",
".",
"format",
"(",
"version",
")",
"_get_install_local",
"(",
"url",
",",
"env",
",",
"... | https://github.com/chapmanb/cloudbiolinux/blob/f6d0414bdba495944aaccf19ae55ba50b13da892/cloudbio/custom/bio_nextgen.py#L377-L384 | ||
weechat/scripts | 99ec0e7eceefabb9efb0f11ec26d45d6e8e84335 | python/mnotify.py | python | notify_dcc_send_start | (match) | Notify on DCC send start. | Notify on DCC send start. | [
"Notify",
"on",
"DCC",
"send",
"start",
"."
] | def notify_dcc_send_start(match):
'Notify on DCC send start.'
if (weechat.config_get_plugin("show_dcc") == "on"
or (weechat.config_get_plugin("show_dcc") == "away"
and STATE['is_away'])):
nick = match.group(1)
file_name = match.group(3)
a_notify(
'DCC',
'Start File Upload',
'Uploading {1} to {0}.'.format(nick, file_name)) | [
"def",
"notify_dcc_send_start",
"(",
"match",
")",
":",
"if",
"(",
"weechat",
".",
"config_get_plugin",
"(",
"\"show_dcc\"",
")",
"==",
"\"on\"",
"or",
"(",
"weechat",
".",
"config_get_plugin",
"(",
"\"show_dcc\"",
")",
"==",
"\"away\"",
"and",
"STATE",
"[",
... | https://github.com/weechat/scripts/blob/99ec0e7eceefabb9efb0f11ec26d45d6e8e84335/python/mnotify.py#L406-L416 | ||
KhronosGroup/NNEF-Tools | c913758ca687dab8cb7b49e8f1556819a2d0ca25 | nnef_tools/io/tf/lite/flatbuffers/FloorDivOptions.py | python | FloorDivOptions.FloorDivOptionsBufferHasIdentifier | (cls, buf, offset, size_prefixed=False) | return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) | [] | def FloorDivOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) | [
"def",
"FloorDivOptionsBufferHasIdentifier",
"(",
"cls",
",",
"buf",
",",
"offset",
",",
"size_prefixed",
"=",
"False",
")",
":",
"return",
"flatbuffers",
".",
"util",
".",
"BufferHasIdentifier",
"(",
"buf",
",",
"offset",
",",
"b\"\\x54\\x46\\x4C\\x33\"",
",",
... | https://github.com/KhronosGroup/NNEF-Tools/blob/c913758ca687dab8cb7b49e8f1556819a2d0ca25/nnef_tools/io/tf/lite/flatbuffers/FloorDivOptions.py#L20-L21 | |||
asteroid-team/asteroid | fae2f7d1d4eb83da741818a5c375267fe8d98847 | asteroid/metrics.py | python | WERTracker.__call__ | (
self,
*,
mix: np.ndarray,
clean: np.ndarray,
estimate: np.ndarray,
sample_rate: int,
wav_id: List[str],
) | return dict(
input_wer=self.wer_from_hsdi(**dict(local_mix_counter)),
clean_wer=self.wer_from_hsdi(**dict(local_clean_counter)),
wer=self.wer_from_hsdi(**dict(local_est_counter)),
) | Compute and store best hypothesis for the mixture and the estimates | Compute and store best hypothesis for the mixture and the estimates | [
"Compute",
"and",
"store",
"best",
"hypothesis",
"for",
"the",
"mixture",
"and",
"the",
"estimates"
] | def __call__(
self,
*,
mix: np.ndarray,
clean: np.ndarray,
estimate: np.ndarray,
sample_rate: int,
wav_id: List[str],
):
"""Compute and store best hypothesis for the mixture and the estimates"""
if sample_rate != self.sample_rate:
mix, clean, estimate = self.resample(
mix, clean, estimate, fs_from=sample_rate, fs_to=self.sample_rate
)
local_mix_counter = Counter()
local_clean_counter = Counter()
local_est_counter = Counter()
# Count the mixture output for each speaker
txt = self.predict_hypothesis(mix)
# Dict to gather transcriptions and IDs
trans_dict = dict(mixture_txt={}, clean={}, estimates={}, truth={})
# Get mixture transcription
trans_dict["mixture_txt"] = txt
# Get ground truth transcription and IDs
for i, tmp_id in enumerate(wav_id):
trans_dict["truth"][f"utt_id_{i}"] = tmp_id
trans_dict["truth"][f"txt_{i}"] = self.trans_dic[tmp_id]
self.true_txt_list.append(dict(utt_id=tmp_id, text=self.trans_dic[tmp_id]))
# Mixture
for tmp_id in wav_id:
out_count = Counter(
self.hsdi(
truth=self.trans_dic[tmp_id], hypothesis=txt, transformation=self.transformation
)
)
self.mix_counter += out_count
local_mix_counter += out_count
self.input_txt_list.append(dict(utt_id=tmp_id, text=txt))
# Average WER for the clean pair
for i, (wav, tmp_id) in enumerate(zip(clean, wav_id)):
txt = self.predict_hypothesis(wav)
out_count = Counter(
self.hsdi(
truth=self.trans_dic[tmp_id], hypothesis=txt, transformation=self.transformation
)
)
self.clean_counter += out_count
local_clean_counter += out_count
self.clean_txt_list.append(dict(utt_id=tmp_id, text=txt))
trans_dict["clean"][f"utt_id_{i}"] = tmp_id
trans_dict["clean"][f"txt_{i}"] = txt
# Average WER for the estimate pair
for i, (est, tmp_id) in enumerate(zip(estimate, wav_id)):
txt = self.predict_hypothesis(est)
out_count = Counter(
self.hsdi(
truth=self.trans_dic[tmp_id], hypothesis=txt, transformation=self.transformation
)
)
self.est_counter += out_count
local_est_counter += out_count
self.output_txt_list.append(dict(utt_id=tmp_id, text=txt))
trans_dict["estimates"][f"utt_id_{i}"] = tmp_id
trans_dict["estimates"][f"txt_{i}"] = txt
self.transcriptions.append(trans_dict)
return dict(
input_wer=self.wer_from_hsdi(**dict(local_mix_counter)),
clean_wer=self.wer_from_hsdi(**dict(local_clean_counter)),
wer=self.wer_from_hsdi(**dict(local_est_counter)),
) | [
"def",
"__call__",
"(",
"self",
",",
"*",
",",
"mix",
":",
"np",
".",
"ndarray",
",",
"clean",
":",
"np",
".",
"ndarray",
",",
"estimate",
":",
"np",
".",
"ndarray",
",",
"sample_rate",
":",
"int",
",",
"wav_id",
":",
"List",
"[",
"str",
"]",
","... | https://github.com/asteroid-team/asteroid/blob/fae2f7d1d4eb83da741818a5c375267fe8d98847/asteroid/metrics.py#L258-L328 | |
cloudera/hue | 23f02102d4547c17c32bd5ea0eb24e9eadd657a4 | desktop/core/ext-py/pysaml2-4.9.0/src/saml2/server.py | python | Server.parse_authn_query | (self, xml_string, binding) | return self._parse_request(xml_string, AuthnQuery,
"authn_query_service", binding) | Parse an authn query
:param xml_string: The AuthnQuery as an XML string
:param binding: Which binding that was used when receiving this query
:return: Query instance | Parse an authn query | [
"Parse",
"an",
"authn",
"query"
] | def parse_authn_query(self, xml_string, binding):
""" Parse an authn query
:param xml_string: The AuthnQuery as an XML string
:param binding: Which binding that was used when receiving this query
:return: Query instance
"""
return self._parse_request(xml_string, AuthnQuery,
"authn_query_service", binding) | [
"def",
"parse_authn_query",
"(",
"self",
",",
"xml_string",
",",
"binding",
")",
":",
"return",
"self",
".",
"_parse_request",
"(",
"xml_string",
",",
"AuthnQuery",
",",
"\"authn_query_service\"",
",",
"binding",
")"
] | https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/pysaml2-4.9.0/src/saml2/server.py#L266-L275 | |
isce-framework/isce2 | 0e5114a8bede3caf1d533d98e44dfe4b983e3f48 | components/isceobj/IsceProc/IsceProc.py | python | IsceProc.average | (self, objdict) | return s / float(N) | Average values in a dict of dict: { k1: { k2: ... } } | Average values in a dict of dict: { k1: { k2: ... } } | [
"Average",
"values",
"in",
"a",
"dict",
"of",
"dict",
":",
"{",
"k1",
":",
"{",
"k2",
":",
"...",
"}",
"}"
] | def average(self, objdict):
"""
Average values in a dict of dict: { k1: { k2: ... } }
"""
N = 0 ##number of values
s = 0 ##sum
vals = objdict.values()
for val in vals:
###val is a dictionary
N += len(val)
s += sum(val.values())
return s / float(N) | [
"def",
"average",
"(",
"self",
",",
"objdict",
")",
":",
"N",
"=",
"0",
"##number of values",
"s",
"=",
"0",
"##sum",
"vals",
"=",
"objdict",
".",
"values",
"(",
")",
"for",
"val",
"in",
"vals",
":",
"###val is a dictionary",
"N",
"+=",
"len",
"(",
"... | https://github.com/isce-framework/isce2/blob/0e5114a8bede3caf1d533d98e44dfe4b983e3f48/components/isceobj/IsceProc/IsceProc.py#L361-L372 | |
napari/napari | dbf4158e801fa7a429de8ef1cdee73bf6d64c61e | napari/layers/utils/layer_utils.py | python | validate_properties | (
properties: Optional[Union[Dict[str, Array], pd.DataFrame]],
expected_len: Optional[int] = None,
) | return {k: np.asarray(v) for k, v in properties.items()} | Validate the type and size of properties and coerce values to numpy arrays.
Parameters
----------
properties : dict[str, Array] or DataFrame
The property values.
expected_len : int
The expected length of each property value array.
Returns
-------
Dict[str, np.ndarray]
The property values. | Validate the type and size of properties and coerce values to numpy arrays.
Parameters
----------
properties : dict[str, Array] or DataFrame
The property values.
expected_len : int
The expected length of each property value array.
Returns
-------
Dict[str, np.ndarray]
The property values. | [
"Validate",
"the",
"type",
"and",
"size",
"of",
"properties",
"and",
"coerce",
"values",
"to",
"numpy",
"arrays",
".",
"Parameters",
"----------",
"properties",
":",
"dict",
"[",
"str",
"Array",
"]",
"or",
"DataFrame",
"The",
"property",
"values",
".",
"expe... | def validate_properties(
properties: Optional[Union[Dict[str, Array], pd.DataFrame]],
expected_len: Optional[int] = None,
) -> Dict[str, np.ndarray]:
"""Validate the type and size of properties and coerce values to numpy arrays.
Parameters
----------
properties : dict[str, Array] or DataFrame
The property values.
expected_len : int
The expected length of each property value array.
Returns
-------
Dict[str, np.ndarray]
The property values.
"""
if properties is None or len(properties) == 0:
return {}
if not isinstance(properties, dict):
properties = dataframe_to_properties(properties)
lens = [len(v) for v in properties.values()]
if expected_len is None:
expected_len = lens[0]
if any(v != expected_len for v in lens):
raise ValueError(
trans._(
"the number of items must be equal for all properties",
deferred=True,
)
)
return {k: np.asarray(v) for k, v in properties.items()} | [
"def",
"validate_properties",
"(",
"properties",
":",
"Optional",
"[",
"Union",
"[",
"Dict",
"[",
"str",
",",
"Array",
"]",
",",
"pd",
".",
"DataFrame",
"]",
"]",
",",
"expected_len",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
")",
"->",
"Di... | https://github.com/napari/napari/blob/dbf4158e801fa7a429de8ef1cdee73bf6d64c61e/napari/layers/utils/layer_utils.py#L377-L410 | |
shawnwun/NNDIAL | 740f6d34594bcdd889080ce60c95384bda7594a2 | utils/bleu.py | python | sentence_bleu_4 | (hyp,refs,weights=[0.25,0.25,0.25,0.25]) | return bleu_hyp | print
print hyp
print refs
print clip_count
print count
print r, c
print bp
print p_ns
print math.exp(s)
print bleu_hyp
raw_input() | print
print hyp
print refs | [
"print",
"print",
"hyp",
"print",
"refs"
] | def sentence_bleu_4(hyp,refs,weights=[0.25,0.25,0.25,0.25]):
# input : single sentence, multiple references
count = [0,0,0,0]
clip_count = [0,0,0,0]
r = 0
c = 0
for i in range(4):
hypcnts = Counter(ngrams(hyp, i+1))
cnt = sum(hypcnts.values())
count[i] += cnt
# compute clipped counts
max_counts = {}
for ref in refs:
refcnts = Counter(ngrams(ref, i+1))
for ng in hypcnts:
max_counts[ng] = max(max_counts.get(ng, 0),refcnts[ng])
clipcnt = dict((ng, min(count, max_counts[ng])) \
for ng, count in hypcnts.items())
clip_count[i] += sum(clipcnt.values())
bestmatch = [1000,1000]
for ref in refs:
if bestmatch[0]==0:
break
diff = abs(len(ref)-len(hyp))
if diff<bestmatch[0]:
bestmatch[0] = diff
bestmatch[1] = len(ref)
r = bestmatch[1]
c = len(hyp)
p0 = 1e-7
bp = math.exp(-abs(1.0-float(r)/float(c+p0)))
p_ns = [float(clip_count[i])/float(count[i]+p0)+p0 for i in range(4)]
s = math.fsum(w*math.log(p_n) for w, p_n in zip(weights, p_ns) if p_n)
bleu_hyp = bp*math.exp(s)
"""
print
print hyp
print refs
print clip_count
print count
print r, c
print bp
print p_ns
print math.exp(s)
print bleu_hyp
raw_input()
"""
return bleu_hyp | [
"def",
"sentence_bleu_4",
"(",
"hyp",
",",
"refs",
",",
"weights",
"=",
"[",
"0.25",
",",
"0.25",
",",
"0.25",
",",
"0.25",
"]",
")",
":",
"# input : single sentence, multiple references",
"count",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
"cli... | https://github.com/shawnwun/NNDIAL/blob/740f6d34594bcdd889080ce60c95384bda7594a2/utils/bleu.py#L12-L65 | |
astropy/photutils | 3caa48e4e4d139976ed7457dc41583fb2c56ba20 | photutils/segmentation/catalog.py | python | SourceCatalog.covar_sigxy | (self) | return self._covariance[:, 0, 1] * u.pix**2 | r"""
The ``(0, 1)`` and ``(1, 0)`` elements of the `covariance`
matrix, representing :math:`\sigma_x \sigma_y`, in units of
pixel**2. | r"""
The ``(0, 1)`` and ``(1, 0)`` elements of the `covariance`
matrix, representing :math:`\sigma_x \sigma_y`, in units of
pixel**2. | [
"r",
"The",
"(",
"0",
"1",
")",
"and",
"(",
"1",
"0",
")",
"elements",
"of",
"the",
"covariance",
"matrix",
"representing",
":",
"math",
":",
"\\",
"sigma_x",
"\\",
"sigma_y",
"in",
"units",
"of",
"pixel",
"**",
"2",
"."
] | def covar_sigxy(self):
r"""
The ``(0, 1)`` and ``(1, 0)`` elements of the `covariance`
matrix, representing :math:`\sigma_x \sigma_y`, in units of
pixel**2.
"""
return self._covariance[:, 0, 1] * u.pix**2 | [
"def",
"covar_sigxy",
"(",
"self",
")",
":",
"return",
"self",
".",
"_covariance",
"[",
":",
",",
"0",
",",
"1",
"]",
"*",
"u",
".",
"pix",
"**",
"2"
] | https://github.com/astropy/photutils/blob/3caa48e4e4d139976ed7457dc41583fb2c56ba20/photutils/segmentation/catalog.py#L1875-L1881 | |
Abjad/abjad | d0646dfbe83db3dc5ab268f76a0950712b87b7fd | abjad/pattern.py | python | Pattern.get_boolean_vector | (self, total_length=None) | return boolean_vector | Gets boolean vector of pattern applied to input sequence with
``total_length``.
.. container:: example
Gets boolean vector of acyclic pattern:
>>> pattern = abjad.Pattern(
... indices=[4, 5, 6, 7],
... )
>>> pattern.get_boolean_vector(4)
[0, 0, 0, 0]
>>> pattern.get_boolean_vector(8)
[0, 0, 0, 0, 1, 1, 1, 1]
>>> pattern.get_boolean_vector(16)
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
Sets total length to length of pattern when ``total_length`` is
none:
>>> pattern.get_boolean_vector()
[0, 0, 0, 0, 1, 1, 1, 1]
.. container:: example
Gets vector of cyclic pattern:
>>> pattern = abjad.Pattern(
... indices=[4, 5, 6, 7],
... period=20,
... )
>>> pattern.get_boolean_vector(4)
[0, 0, 0, 0]
>>> pattern.get_boolean_vector(8)
[0, 0, 0, 0, 1, 1, 1, 1]
>>> pattern.get_boolean_vector(16)
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
Sets total length to length of pattern when ``total_length`` is
none:
>>> pattern.get_boolean_vector()
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
.. container:: example
Gets vector of inverted pattern:
>>> pattern = abjad.Pattern(
... indices=[4, 5, 6, 7],
... period=20,
... )
>>> pattern.get_boolean_vector(4)
[0, 0, 0, 0]
>>> pattern.get_boolean_vector(8)
[0, 0, 0, 0, 1, 1, 1, 1]
>>> pattern.get_boolean_vector(16)
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
Sets total length to length of pattern when ``total_length`` is
none:
>>> pattern.get_boolean_vector()
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
.. container:: example
Two-part pattern with logical OR:
>>> pattern = abjad.Pattern(
... operator='or',
... patterns=[
... abjad.Pattern(
... indices=[0, 1, 2],
... ),
... abjad.Pattern(
... indices=[-3, -2, -1],
... ),
... ],
... )
>>> pattern.get_boolean_vector(4)
[1, 1, 1, 1]
>>> pattern.get_boolean_vector(8)
[1, 1, 1, 0, 0, 1, 1, 1]
>>> pattern.get_boolean_vector(16)
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]
Matches every index that is (one of the first three indices) OR
(one of the last three indices).
.. container:: example
Two-part pattern with mixed periodic and inverted parts:
>>> pattern = abjad.Pattern(
... operator='and',
... patterns=[
... abjad.Pattern(
... indices=[0],
... period=2,
... ),
... abjad.Pattern(
... indices=[-3, -2, -1],
... inverted=True,
... ),
... ],
... )
>>> pattern.get_boolean_vector(4)
[1, 0, 0, 0]
>>> pattern.get_boolean_vector(8)
[1, 0, 1, 0, 1, 0, 0, 0]
>>> pattern.get_boolean_vector(16)
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0]
Matches every index that is (equal to 0 % 2) AND (not one of the
last three indices).
.. container:: example
Cyclic pattern that indexes every fourth and fifth item:
>>> pattern_1 = abjad.Pattern([0], period=4)
>>> pattern_2 = abjad.Pattern([0], period=5)
>>> pattern = pattern_1 | pattern_2
>>> string = abjad.storage(pattern)
>>> print(string)
abjad.Pattern(
operator='or',
patterns=(
abjad.Pattern(
indices=[0],
period=4,
),
abjad.Pattern(
indices=[0],
period=5,
),
),
period=20,
)
>>> pattern.get_boolean_vector(4)
[1, 0, 0, 0]
>>> pattern.get_boolean_vector(8)
[1, 0, 0, 0, 1, 1, 0, 0]
>>> pattern.get_boolean_vector(16)
[1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1]
Sets total length to period of pattern when ``total_length`` is
none:
>>> pattern.period
20
>>> pattern.get_boolean_vector()
[1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0]
>>> pattern.period == len(pattern.get_boolean_vector())
True
Returns list of ones and zeroes. | Gets boolean vector of pattern applied to input sequence with
``total_length``. | [
"Gets",
"boolean",
"vector",
"of",
"pattern",
"applied",
"to",
"input",
"sequence",
"with",
"total_length",
"."
] | def get_boolean_vector(self, total_length=None):
"""
Gets boolean vector of pattern applied to input sequence with
``total_length``.
.. container:: example
Gets boolean vector of acyclic pattern:
>>> pattern = abjad.Pattern(
... indices=[4, 5, 6, 7],
... )
>>> pattern.get_boolean_vector(4)
[0, 0, 0, 0]
>>> pattern.get_boolean_vector(8)
[0, 0, 0, 0, 1, 1, 1, 1]
>>> pattern.get_boolean_vector(16)
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
Sets total length to length of pattern when ``total_length`` is
none:
>>> pattern.get_boolean_vector()
[0, 0, 0, 0, 1, 1, 1, 1]
.. container:: example
Gets vector of cyclic pattern:
>>> pattern = abjad.Pattern(
... indices=[4, 5, 6, 7],
... period=20,
... )
>>> pattern.get_boolean_vector(4)
[0, 0, 0, 0]
>>> pattern.get_boolean_vector(8)
[0, 0, 0, 0, 1, 1, 1, 1]
>>> pattern.get_boolean_vector(16)
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
Sets total length to length of pattern when ``total_length`` is
none:
>>> pattern.get_boolean_vector()
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
.. container:: example
Gets vector of inverted pattern:
>>> pattern = abjad.Pattern(
... indices=[4, 5, 6, 7],
... period=20,
... )
>>> pattern.get_boolean_vector(4)
[0, 0, 0, 0]
>>> pattern.get_boolean_vector(8)
[0, 0, 0, 0, 1, 1, 1, 1]
>>> pattern.get_boolean_vector(16)
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
Sets total length to length of pattern when ``total_length`` is
none:
>>> pattern.get_boolean_vector()
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
.. container:: example
Two-part pattern with logical OR:
>>> pattern = abjad.Pattern(
... operator='or',
... patterns=[
... abjad.Pattern(
... indices=[0, 1, 2],
... ),
... abjad.Pattern(
... indices=[-3, -2, -1],
... ),
... ],
... )
>>> pattern.get_boolean_vector(4)
[1, 1, 1, 1]
>>> pattern.get_boolean_vector(8)
[1, 1, 1, 0, 0, 1, 1, 1]
>>> pattern.get_boolean_vector(16)
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]
Matches every index that is (one of the first three indices) OR
(one of the last three indices).
.. container:: example
Two-part pattern with mixed periodic and inverted parts:
>>> pattern = abjad.Pattern(
... operator='and',
... patterns=[
... abjad.Pattern(
... indices=[0],
... period=2,
... ),
... abjad.Pattern(
... indices=[-3, -2, -1],
... inverted=True,
... ),
... ],
... )
>>> pattern.get_boolean_vector(4)
[1, 0, 0, 0]
>>> pattern.get_boolean_vector(8)
[1, 0, 1, 0, 1, 0, 0, 0]
>>> pattern.get_boolean_vector(16)
[1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0]
Matches every index that is (equal to 0 % 2) AND (not one of the
last three indices).
.. container:: example
Cyclic pattern that indexes every fourth and fifth item:
>>> pattern_1 = abjad.Pattern([0], period=4)
>>> pattern_2 = abjad.Pattern([0], period=5)
>>> pattern = pattern_1 | pattern_2
>>> string = abjad.storage(pattern)
>>> print(string)
abjad.Pattern(
operator='or',
patterns=(
abjad.Pattern(
indices=[0],
period=4,
),
abjad.Pattern(
indices=[0],
period=5,
),
),
period=20,
)
>>> pattern.get_boolean_vector(4)
[1, 0, 0, 0]
>>> pattern.get_boolean_vector(8)
[1, 0, 0, 0, 1, 1, 0, 0]
>>> pattern.get_boolean_vector(16)
[1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1]
Sets total length to period of pattern when ``total_length`` is
none:
>>> pattern.period
20
>>> pattern.get_boolean_vector()
[1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0]
>>> pattern.period == len(pattern.get_boolean_vector())
True
Returns list of ones and zeroes.
"""
total_length = total_length or len(self)
boolean_vector = []
for index in range(total_length):
result = self.matches_index(index, total_length)
boolean_vector.append(int(result))
return boolean_vector | [
"def",
"get_boolean_vector",
"(",
"self",
",",
"total_length",
"=",
"None",
")",
":",
"total_length",
"=",
"total_length",
"or",
"len",
"(",
"self",
")",
"boolean_vector",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"total_length",
")",
":",
"result... | https://github.com/Abjad/abjad/blob/d0646dfbe83db3dc5ab268f76a0950712b87b7fd/abjad/pattern.py#L1247-L1435 | |
awslabs/aws-ec2rescue-linux | 8ecf40e7ea0d2563dac057235803fca2221029d2 | lib/urllib3/filepost.py | python | choose_boundary | () | return boundary | Our embarrassingly-simple replacement for mimetools.choose_boundary. | Our embarrassingly-simple replacement for mimetools.choose_boundary. | [
"Our",
"embarrassingly",
"-",
"simple",
"replacement",
"for",
"mimetools",
".",
"choose_boundary",
"."
] | def choose_boundary():
"""
Our embarrassingly-simple replacement for mimetools.choose_boundary.
"""
boundary = binascii.hexlify(os.urandom(16))
if not six.PY2:
boundary = boundary.decode("ascii")
return boundary | [
"def",
"choose_boundary",
"(",
")",
":",
"boundary",
"=",
"binascii",
".",
"hexlify",
"(",
"os",
".",
"urandom",
"(",
"16",
")",
")",
"if",
"not",
"six",
".",
"PY2",
":",
"boundary",
"=",
"boundary",
".",
"decode",
"(",
"\"ascii\"",
")",
"return",
"b... | https://github.com/awslabs/aws-ec2rescue-linux/blob/8ecf40e7ea0d2563dac057235803fca2221029d2/lib/urllib3/filepost.py#L15-L22 | |
raymontag/keepassc | 3a3c7ef7b3ee1ceb16b613176d54dad89c0408df | keepassc/daemon.py | python | Daemon.run | (self) | You should override this method when you subclass Daemon.
It will be called after the process has been daemonized by
start() or restart(). | You should override this method when you subclass Daemon.
It will be called after the process has been daemonized by
start() or restart(). | [
"You",
"should",
"override",
"this",
"method",
"when",
"you",
"subclass",
"Daemon",
".",
"It",
"will",
"be",
"called",
"after",
"the",
"process",
"has",
"been",
"daemonized",
"by",
"start",
"()",
"or",
"restart",
"()",
"."
] | def run(self):
"""You should override this method when you subclass Daemon.
It will be called after the process has been daemonized by
start() or restart().""" | [
"def",
"run",
"(",
"self",
")",
":"
] | https://github.com/raymontag/keepassc/blob/3a3c7ef7b3ee1ceb16b613176d54dad89c0408df/keepassc/daemon.py#L118-L122 | ||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/google/appengine/ext/ndb/blobstore.py | python | BlobInfo.get_multi | (cls, blob_keys, **ctx_options) | return [fut.get_result() for fut in futs] | Multi-key version of get().
Args:
blob_keys: A list of blob keys.
**ctx_options: Context options for Model().get_by_id().
Returns:
A list whose items are each either a BlobInfo entity or None. | Multi-key version of get(). | [
"Multi",
"-",
"key",
"version",
"of",
"get",
"()",
"."
] | def get_multi(cls, blob_keys, **ctx_options):
"""Multi-key version of get().
Args:
blob_keys: A list of blob keys.
**ctx_options: Context options for Model().get_by_id().
Returns:
A list whose items are each either a BlobInfo entity or None.
"""
futs = cls.get_multi_async(blob_keys, **ctx_options)
return [fut.get_result() for fut in futs] | [
"def",
"get_multi",
"(",
"cls",
",",
"blob_keys",
",",
"*",
"*",
"ctx_options",
")",
":",
"futs",
"=",
"cls",
".",
"get_multi_async",
"(",
"blob_keys",
",",
"*",
"*",
"ctx_options",
")",
"return",
"[",
"fut",
".",
"get_result",
"(",
")",
"for",
"fut",
... | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/ext/ndb/blobstore.py#L176-L187 | |
nopernik/mpDNS | b17dc39e7068406df82cb3431b3042e74e520cf9 | circuits/net/sockets.py | python | parse_ipv4_parameter | (bind_parameter) | return bind | [] | def parse_ipv4_parameter(bind_parameter):
if isinstance(bind_parameter, int):
try:
bind = (gethostbyname(gethostname()), bind_parameter)
except gaierror:
bind = ("0.0.0.0", bind_parameter)
elif isinstance(bind_parameter, str) and ":" in bind_parameter:
host, port = bind_parameter.split(":")
port = int(port)
bind = (host, port)
else:
bind = bind_parameter
return bind | [
"def",
"parse_ipv4_parameter",
"(",
"bind_parameter",
")",
":",
"if",
"isinstance",
"(",
"bind_parameter",
",",
"int",
")",
":",
"try",
":",
"bind",
"=",
"(",
"gethostbyname",
"(",
"gethostname",
"(",
")",
")",
",",
"bind_parameter",
")",
"except",
"gaierror... | https://github.com/nopernik/mpDNS/blob/b17dc39e7068406df82cb3431b3042e74e520cf9/circuits/net/sockets.py#L666-L679 | |||
ronf/asyncssh | ee1714c598d8c2ea6f5484e465443f38b68714aa | asyncssh/packet.py | python | UInt32 | (value: int) | return value.to_bytes(4, 'big') | Encode a 32-bit integer value | Encode a 32-bit integer value | [
"Encode",
"a",
"32",
"-",
"bit",
"integer",
"value"
] | def UInt32(value: int) -> bytes:
"""Encode a 32-bit integer value"""
return value.to_bytes(4, 'big') | [
"def",
"UInt32",
"(",
"value",
":",
"int",
")",
"->",
"bytes",
":",
"return",
"value",
".",
"to_bytes",
"(",
"4",
",",
"'big'",
")"
] | https://github.com/ronf/asyncssh/blob/ee1714c598d8c2ea6f5484e465443f38b68714aa/asyncssh/packet.py#L55-L58 | |
openedx/edx-platform | 68dd185a0ab45862a2a61e0f803d7e03d2be71b5 | common/djangoapps/student/views/dashboard.py | python | get_org_black_and_whitelist_for_site | () | return org_whitelist, org_blacklist | Returns the org blacklist and whitelist for the current site.
Returns:
(org_whitelist, org_blacklist): A tuple of lists of orgs that serve as
either a blacklist or a whitelist of orgs for the current site. The
whitelist takes precedence, and the blacklist is used if the
whitelist is None. | Returns the org blacklist and whitelist for the current site. | [
"Returns",
"the",
"org",
"blacklist",
"and",
"whitelist",
"for",
"the",
"current",
"site",
"."
] | def get_org_black_and_whitelist_for_site():
"""
Returns the org blacklist and whitelist for the current site.
Returns:
(org_whitelist, org_blacklist): A tuple of lists of orgs that serve as
either a blacklist or a whitelist of orgs for the current site. The
whitelist takes precedence, and the blacklist is used if the
whitelist is None.
"""
# Default blacklist is empty.
org_blacklist = None
# Whitelist the orgs configured for the current site. Each site outside
# of edx.org has a list of orgs associated with its configuration.
org_whitelist = configuration_helpers.get_current_site_orgs()
if not org_whitelist:
# If there is no whitelist, the blacklist will include all orgs that
# have been configured for any other sites. This applies to edx.org,
# where it is easier to blacklist all other orgs.
org_blacklist = configuration_helpers.get_all_orgs()
return org_whitelist, org_blacklist | [
"def",
"get_org_black_and_whitelist_for_site",
"(",
")",
":",
"# Default blacklist is empty.",
"org_blacklist",
"=",
"None",
"# Whitelist the orgs configured for the current site. Each site outside",
"# of edx.org has a list of orgs associated with its configuration.",
"org_whitelist",
"=",... | https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/common/djangoapps/student/views/dashboard.py#L68-L90 | |
beringresearch/ivis | 690d610d62be786b7a9a98debe57129bae678095 | ivis/data/generators/triplet_generators.py | python | TripletGenerator.gen_negative_indices | (self, neighbour_matrix) | return cands | Generate random candidate negative indices until the candidate for every
row is not present in corresponding row of neighbour_matrix. | Generate random candidate negative indices until the candidate for every
row is not present in corresponding row of neighbour_matrix. | [
"Generate",
"random",
"candidate",
"negative",
"indices",
"until",
"the",
"candidate",
"for",
"every",
"row",
"is",
"not",
"present",
"in",
"corresponding",
"row",
"of",
"neighbour_matrix",
"."
] | def gen_negative_indices(self, neighbour_matrix):
"""Generate random candidate negative indices until the candidate for every
row is not present in corresponding row of neighbour_matrix."""
neighbour_matrix = np.asarray(neighbour_matrix)
generate_cands = partial(np.random.randint, self.X.shape[0], dtype=self._idx_dtype)
cands = generate_cands(size=len(neighbour_matrix))
# Where random cand is present in neighbour row, invalid cand
invalid_cands = (cands[:, np.newaxis] == neighbour_matrix).any(axis=1)
n_invalid = invalid_cands.sum()
while n_invalid > 0:
cands[invalid_cands] = generate_cands(size=n_invalid)
invalid_cands = (cands[:, np.newaxis] == neighbour_matrix).any(axis=1)
n_invalid = invalid_cands.sum()
return cands | [
"def",
"gen_negative_indices",
"(",
"self",
",",
"neighbour_matrix",
")",
":",
"neighbour_matrix",
"=",
"np",
".",
"asarray",
"(",
"neighbour_matrix",
")",
"generate_cands",
"=",
"partial",
"(",
"np",
".",
"random",
".",
"randint",
",",
"self",
".",
"X",
"."... | https://github.com/beringresearch/ivis/blob/690d610d62be786b7a9a98debe57129bae678095/ivis/data/generators/triplet_generators.py#L92-L106 | |
danilobellini/audiolazy | dba0a278937909980ed40b976d866b8e97c35dee | audiolazy/lazy_itertools.py | python | accumulate | (iterable) | Return series of accumulated sums. | Return series of accumulated sums. | [
"Return",
"series",
"of",
"accumulated",
"sums",
"."
] | def accumulate(iterable):
" Return series of accumulated sums. "
iterator = iter(iterable)
sum_data = next(iterator)
yield sum_data
for el in iterator:
sum_data += el
yield sum_data | [
"def",
"accumulate",
"(",
"iterable",
")",
":",
"iterator",
"=",
"iter",
"(",
"iterable",
")",
"sum_data",
"=",
"next",
"(",
"iterator",
")",
"yield",
"sum_data",
"for",
"el",
"in",
"iterator",
":",
"sum_data",
"+=",
"el",
"yield",
"sum_data"
] | https://github.com/danilobellini/audiolazy/blob/dba0a278937909980ed40b976d866b8e97c35dee/audiolazy/lazy_itertools.py#L69-L76 | ||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/webapp2-2.5.2/webapp2_extras/i18n.py | python | I18n.parse_decimal | (self, string) | return numbers.parse_decimal(string, locale=self.locale) | Parses localized decimal string into a float. Example::
>>> parse_decimal('1,099.98', locale='en_US')
1099.98
>>> parse_decimal('1.099,98', locale='de')
1099.98
When the given string cannot be parsed, an exception is raised::
>>> parse_decimal('2,109,998', locale='de')
Traceback (most recent call last):
...
NumberFormatError: '2,109,998' is not a valid decimal number
:param string:
The string to parse.
:returns:
The parsed decimal number.
:raises:
``NumberFormatError`` if the string can not be converted to a
decimal number. | Parses localized decimal string into a float. Example:: | [
"Parses",
"localized",
"decimal",
"string",
"into",
"a",
"float",
".",
"Example",
"::"
] | def parse_decimal(self, string):
"""Parses localized decimal string into a float. Example::
>>> parse_decimal('1,099.98', locale='en_US')
1099.98
>>> parse_decimal('1.099,98', locale='de')
1099.98
When the given string cannot be parsed, an exception is raised::
>>> parse_decimal('2,109,998', locale='de')
Traceback (most recent call last):
...
NumberFormatError: '2,109,998' is not a valid decimal number
:param string:
The string to parse.
:returns:
The parsed decimal number.
:raises:
``NumberFormatError`` if the string can not be converted to a
decimal number.
"""
return numbers.parse_decimal(string, locale=self.locale) | [
"def",
"parse_decimal",
"(",
"self",
",",
"string",
")",
":",
"return",
"numbers",
".",
"parse_decimal",
"(",
"string",
",",
"locale",
"=",
"self",
".",
"locale",
")"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/webapp2-2.5.2/webapp2_extras/i18n.py#L655-L678 | |
a312863063/seeprettyface-face_editor | 0a318ef8128ffca6929aea348457a70e6127087d | dnnlib/tflib/optimizer.py | python | Optimizer.register_gradients | (self, loss: TfExpression, trainable_vars: Union[List, dict]) | Register the gradients of the given loss function with respect to the given variables.
Intended to be called once per GPU. | Register the gradients of the given loss function with respect to the given variables.
Intended to be called once per GPU. | [
"Register",
"the",
"gradients",
"of",
"the",
"given",
"loss",
"function",
"with",
"respect",
"to",
"the",
"given",
"variables",
".",
"Intended",
"to",
"be",
"called",
"once",
"per",
"GPU",
"."
] | def register_gradients(self, loss: TfExpression, trainable_vars: Union[List, dict]) -> None:
"""Register the gradients of the given loss function with respect to the given variables.
Intended to be called once per GPU."""
assert not self._updates_applied
# Validate arguments.
if isinstance(trainable_vars, dict):
trainable_vars = list(trainable_vars.values()) # allow passing in Network.trainables as vars
assert isinstance(trainable_vars, list) and len(trainable_vars) >= 1
assert all(tfutil.is_tf_expression(expr) for expr in trainable_vars + [loss])
if self._grad_shapes is None:
self._grad_shapes = [tfutil.shape_to_list(var.shape) for var in trainable_vars]
assert len(trainable_vars) == len(self._grad_shapes)
assert all(tfutil.shape_to_list(var.shape) == var_shape for var, var_shape in zip(trainable_vars, self._grad_shapes))
dev = loss.device
assert all(var.device == dev for var in trainable_vars)
# Register device and compute gradients.
with tf.name_scope(self.id + "_grad"), tf.device(dev):
if dev not in self._dev_opt:
opt_name = self.scope.replace("/", "_") + "_opt%d" % len(self._dev_opt)
assert callable(self.optimizer_class)
self._dev_opt[dev] = self.optimizer_class(name=opt_name, learning_rate=self.learning_rate, **self.optimizer_kwargs)
self._dev_grads[dev] = []
loss = self.apply_loss_scaling(tf.cast(loss, tf.float32))
grads = self._dev_opt[dev].compute_gradients(loss, trainable_vars, gate_gradients=tf.train.Optimizer.GATE_NONE) # disable gating to reduce memory usage
grads = [(g, v) if g is not None else (tf.zeros_like(v), v) for g, v in grads] # replace disconnected gradients with zeros
self._dev_grads[dev].append(grads) | [
"def",
"register_gradients",
"(",
"self",
",",
"loss",
":",
"TfExpression",
",",
"trainable_vars",
":",
"Union",
"[",
"List",
",",
"dict",
"]",
")",
"->",
"None",
":",
"assert",
"not",
"self",
".",
"_updates_applied",
"# Validate arguments.",
"if",
"isinstance... | https://github.com/a312863063/seeprettyface-face_editor/blob/0a318ef8128ffca6929aea348457a70e6127087d/dnnlib/tflib/optimizer.py#L67-L100 | ||
home-assistant/core | 265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1 | homeassistant/helpers/device_registry.py | python | DeviceRegistry.async_load | (self) | Load the device registry. | Load the device registry. | [
"Load",
"the",
"device",
"registry",
"."
] | async def async_load(self) -> None:
"""Load the device registry."""
async_setup_cleanup(self.hass, self)
data = await self._store.async_load()
devices = OrderedDict()
deleted_devices = OrderedDict()
if data is not None:
data = cast("dict[str, Any]", data)
for device in data["devices"]:
devices[device["id"]] = DeviceEntry(
area_id=device["area_id"],
config_entries=set(device["config_entries"]),
configuration_url=device["configuration_url"],
# type ignores (if tuple arg was cast): likely https://github.com/python/mypy/issues/8625
connections={tuple(conn) for conn in device["connections"]}, # type: ignore[misc]
disabled_by=DeviceEntryDisabler(device["disabled_by"])
if device["disabled_by"]
else None,
entry_type=DeviceEntryType(device["entry_type"])
if device["entry_type"]
else None,
id=device["id"],
identifiers={tuple(iden) for iden in device["identifiers"]}, # type: ignore[misc]
manufacturer=device["manufacturer"],
model=device["model"],
name_by_user=device["name_by_user"],
name=device["name"],
sw_version=device["sw_version"],
hw_version=device["hw_version"],
via_device_id=device["via_device_id"],
)
# Introduced in 0.111
for device in data["deleted_devices"]:
deleted_devices[device["id"]] = DeletedDeviceEntry(
config_entries=set(device["config_entries"]),
# type ignores (if tuple arg was cast): likely https://github.com/python/mypy/issues/8625
connections={tuple(conn) for conn in device["connections"]}, # type: ignore[misc]
identifiers={tuple(iden) for iden in device["identifiers"]}, # type: ignore[misc]
id=device["id"],
orphaned_timestamp=device["orphaned_timestamp"],
)
self.devices = devices
self.deleted_devices = deleted_devices
self._rebuild_index() | [
"async",
"def",
"async_load",
"(",
"self",
")",
"->",
"None",
":",
"async_setup_cleanup",
"(",
"self",
".",
"hass",
",",
"self",
")",
"data",
"=",
"await",
"self",
".",
"_store",
".",
"async_load",
"(",
")",
"devices",
"=",
"OrderedDict",
"(",
")",
"de... | https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/helpers/device_registry.py#L538-L585 | ||
beville/ComicStreamer | 62eb914652695ea41a5e1f0cfbd044cbc6854e84 | comicstreamerlib/bookmarker.py | python | Bookmarker.stop | (self) | [] | def stop(self):
self.quit = True
self.join() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"quit",
"=",
"True",
"self",
".",
"join",
"(",
")"
] | https://github.com/beville/ComicStreamer/blob/62eb914652695ea41a5e1f0cfbd044cbc6854e84/comicstreamerlib/bookmarker.py#L41-L43 | ||||
skylander86/lambda-text-extractor | 6da52d077a2fc571e38bfe29c33ae68f6443cd5a | lib-linux_x64/odf/odf2xhtml.py | python | ODF2XHTML.s_table_table_cell | (self, tag, attrs) | Start a table cell | Start a table cell | [
"Start",
"a",
"table",
"cell"
] | def s_table_table_cell(self, tag, attrs):
""" Start a table cell """
#FIXME: number-columns-repeated § 8.1.3
#repeated = int(attrs.get( (TABLENS,'number-columns-repeated'), 1))
htmlattrs = {}
rowspan = attrs.get( (TABLENS,'number-rows-spanned') )
if rowspan:
htmlattrs['rowspan'] = rowspan
colspan = attrs.get( (TABLENS,'number-columns-spanned') )
if colspan:
htmlattrs['colspan'] = colspan
c = attrs.get( (TABLENS,'style-name') )
if c:
htmlattrs['class'] = 'TD-%s' % c.replace(".","_")
self.opentag('td', htmlattrs)
self.purgedata() | [
"def",
"s_table_table_cell",
"(",
"self",
",",
"tag",
",",
"attrs",
")",
":",
"#FIXME: number-columns-repeated § 8.1.3",
"#repeated = int(attrs.get( (TABLENS,'number-columns-repeated'), 1))",
"htmlattrs",
"=",
"{",
"}",
"rowspan",
"=",
"attrs",
".",
"get",
"(",
"(",
"TA... | https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/odf/odf2xhtml.py#L1096-L1112 | ||
nikitakit/self-attentive-parser | 24435a156a64d7433829e9a500a81f46b7e58030 | src/transliterate.py | python | hebrew | (inp) | return out | Undo Hebrew transliteration
See: http://www.phil.uu.nl/ozsl/articles/simaan02.pdf
This code inspired by:
https://github.com/habeanf/yap/blob/b57502364b73ef78f3510eb890319ae268eeacca/nlp/parser/xliter8/types.go | Undo Hebrew transliteration | [
"Undo",
"Hebrew",
"transliteration"
] | def hebrew(inp):
"""
Undo Hebrew transliteration
See: http://www.phil.uu.nl/ozsl/articles/simaan02.pdf
This code inspired by:
https://github.com/habeanf/yap/blob/b57502364b73ef78f3510eb890319ae268eeacca/nlp/parser/xliter8/types.go
"""
out = "".join(
HEBREW_MAP.get(char, char)
for char in HEBREW_UNESCAPE.get(inp, inp))
if out and (out[-1] in HEBREW_SUFFIX_MAP):
out = out[:-1] + HEBREW_SUFFIX_MAP[out[-1]]
return out | [
"def",
"hebrew",
"(",
"inp",
")",
":",
"out",
"=",
"\"\"",
".",
"join",
"(",
"HEBREW_MAP",
".",
"get",
"(",
"char",
",",
"char",
")",
"for",
"char",
"in",
"HEBREW_UNESCAPE",
".",
"get",
"(",
"inp",
",",
"inp",
")",
")",
"if",
"out",
"and",
"(",
... | https://github.com/nikitakit/self-attentive-parser/blob/24435a156a64d7433829e9a500a81f46b7e58030/src/transliterate.py#L142-L156 | |
Northxw/Python3_WebSpider | 903044564a09f470516a51ab2fa457b3c6f6c7a9 | 09-Bilibili/bilibili.py | python | Crack_bb.move_to_gap | (self, slider, tracks) | 拖动滑块到缺口位置
:param slider: 滑块
:param tracks: 轨迹
:return: None | 拖动滑块到缺口位置
:param slider: 滑块
:param tracks: 轨迹
:return: None | [
"拖动滑块到缺口位置",
":",
"param",
"slider",
":",
"滑块",
":",
"param",
"tracks",
":",
"轨迹",
":",
"return",
":",
"None"
] | def move_to_gap(self, slider, tracks):
"""
拖动滑块到缺口位置
:param slider: 滑块
:param tracks: 轨迹
:return: None
"""
# 按住鼠标准备拖动
ActionChains(self.browser).click_and_hold(slider).perform()
# 拖动滑块
for x in tracks:
ActionChains(self.browser).move_by_offset(xoffset=x, yoffset=0).perform()
sleep(0.5)
# 释放滑块
ActionChains(self.browser).release().perform() | [
"def",
"move_to_gap",
"(",
"self",
",",
"slider",
",",
"tracks",
")",
":",
"# 按住鼠标准备拖动",
"ActionChains",
"(",
"self",
".",
"browser",
")",
".",
"click_and_hold",
"(",
"slider",
")",
".",
"perform",
"(",
")",
"# 拖动滑块",
"for",
"x",
"in",
"tracks",
":",
"... | https://github.com/Northxw/Python3_WebSpider/blob/903044564a09f470516a51ab2fa457b3c6f6c7a9/09-Bilibili/bilibili.py#L179-L193 | ||
mdiazcl/fuzzbunch-debian | 2b76c2249ade83a389ae3badb12a1bd09901fd2c | windows/Resources/Python/Core/Lib/random.py | python | Random._randbelow | (self, n, _log=_log, int=int, _maxwidth=1 << BPF, _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType) | return int(self.random() * n) | Return a random int in the range [0,n)
Handles the case where n has more bits than returned
by a single call to the underlying generator. | Return a random int in the range [0,n)
Handles the case where n has more bits than returned
by a single call to the underlying generator. | [
"Return",
"a",
"random",
"int",
"in",
"the",
"range",
"[",
"0",
"n",
")",
"Handles",
"the",
"case",
"where",
"n",
"has",
"more",
"bits",
"than",
"returned",
"by",
"a",
"single",
"call",
"to",
"the",
"underlying",
"generator",
"."
] | def _randbelow(self, n, _log=_log, int=int, _maxwidth=1 << BPF, _Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):
"""Return a random int in the range [0,n)
Handles the case where n has more bits than returned
by a single call to the underlying generator.
"""
try:
getrandbits = self.getrandbits
except AttributeError:
pass
else:
if type(self.random) is _BuiltinMethod or type(getrandbits) is _Method:
k = int(1.00001 + _log(n - 1, 2.0))
r = getrandbits(k)
while r >= n:
r = getrandbits(k)
return r
if n >= _maxwidth:
_warn('Underlying random() generator does not supply \nenough bits to choose from a population range this large')
return int(self.random() * n) | [
"def",
"_randbelow",
"(",
"self",
",",
"n",
",",
"_log",
"=",
"_log",
",",
"int",
"=",
"int",
",",
"_maxwidth",
"=",
"1",
"<<",
"BPF",
",",
"_Method",
"=",
"_MethodType",
",",
"_BuiltinMethod",
"=",
"_BuiltinMethodType",
")",
":",
"try",
":",
"getrandb... | https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/random.py#L203-L224 | |
VLSIDA/OpenRAM | f66aac3264598eeae31225c62b6a4af52412d407 | compiler/pgates/pinv.py | python | pinv.create_layout | (self) | Calls all functions related to the generation of the layout | Calls all functions related to the generation of the layout | [
"Calls",
"all",
"functions",
"related",
"to",
"the",
"generation",
"of",
"the",
"layout"
] | def create_layout(self):
""" Calls all functions related to the generation of the layout """
self.place_ptx()
if self.add_wells:
self.add_well_contacts()
self.determine_width()
self.extend_wells()
self.route_input_gate(self.pmos_inst,
self.nmos_inst,
self.output_pos.y,
"A",
position="farleft")
self.route_outputs()
self.route_supply_rails()
self.connect_rails()
self.add_boundary() | [
"def",
"create_layout",
"(",
"self",
")",
":",
"self",
".",
"place_ptx",
"(",
")",
"if",
"self",
".",
"add_wells",
":",
"self",
".",
"add_well_contacts",
"(",
")",
"self",
".",
"determine_width",
"(",
")",
"self",
".",
"extend_wells",
"(",
")",
"self",
... | https://github.com/VLSIDA/OpenRAM/blob/f66aac3264598eeae31225c62b6a4af52412d407/compiler/pgates/pinv.py#L57-L72 | ||
mysql/mysql-connector-python | c5460bcbb0dff8e4e48bf4af7a971c89bf486d85 | lib/mysqlx/result.py | python | Result.get_generated_ids | (self) | return self._generated_ids | Returns the generated ids. | Returns the generated ids. | [
"Returns",
"the",
"generated",
"ids",
"."
] | def get_generated_ids(self):
"""Returns the generated ids.
"""
return self._generated_ids | [
"def",
"get_generated_ids",
"(",
"self",
")",
":",
"return",
"self",
".",
"_generated_ids"
] | https://github.com/mysql/mysql-connector-python/blob/c5460bcbb0dff8e4e48bf4af7a971c89bf486d85/lib/mysqlx/result.py#L918-L921 | |
dayorbyte/MongoAlchemy | e64ef0c87feff385637459707fe6090bd789e116 | mongoalchemy/query.py | python | Query.descending | (self, qfield) | return self.__sort(qfield, DESCENDING) | Sort the result based on ``qfield`` in ascending order. These calls
can be chained to sort by multiple fields.
:param qfield: Instance of :class:``mongoalchemy.query.QueryField`` \
specifying which field to sort by. | Sort the result based on ``qfield`` in ascending order. These calls
can be chained to sort by multiple fields. | [
"Sort",
"the",
"result",
"based",
"on",
"qfield",
"in",
"ascending",
"order",
".",
"These",
"calls",
"can",
"be",
"chained",
"to",
"sort",
"by",
"multiple",
"fields",
"."
] | def descending(self, qfield):
''' Sort the result based on ``qfield`` in ascending order. These calls
can be chained to sort by multiple fields.
:param qfield: Instance of :class:``mongoalchemy.query.QueryField`` \
specifying which field to sort by.
'''
return self.__sort(qfield, DESCENDING) | [
"def",
"descending",
"(",
"self",
",",
"qfield",
")",
":",
"return",
"self",
".",
"__sort",
"(",
"qfield",
",",
"DESCENDING",
")"
] | https://github.com/dayorbyte/MongoAlchemy/blob/e64ef0c87feff385637459707fe6090bd789e116/mongoalchemy/query.py#L268-L275 | |
deepgram/kur | fd0c120e50815c1e5be64e5dde964dcd47234556 | kur/utils/cuda.py | python | ready | (func) | return wrapper | Decorator for a class instance method which requires that the class's
"_ready" property be set. | Decorator for a class instance method which requires that the class's
"_ready" property be set. | [
"Decorator",
"for",
"a",
"class",
"instance",
"method",
"which",
"requires",
"that",
"the",
"class",
"s",
"_ready",
"property",
"be",
"set",
"."
] | def ready(func):
""" Decorator for a class instance method which requires that the class's
"_ready" property be set.
"""
###########################################################################
@wraps(func)
def wrapper(self, *args, **kwargs):
""" The wrapped function.
"""
if not self._ready:
raise ValueError('CUDA has not been initialized for this object. '
'Be sure to only use this object only within Python context '
'management.')
return func(self, *args, **kwargs)
return wrapper | [
"def",
"ready",
"(",
"func",
")",
":",
"###########################################################################",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\" The wrapped function.\n\... | https://github.com/deepgram/kur/blob/fd0c120e50815c1e5be64e5dde964dcd47234556/kur/utils/cuda.py#L57-L73 | |
jacoxu/encoder_decoder | 6829c3bc42105aedfd1b8a81c81be19df4326c0a | keras/models.py | python | model_from_yaml | (yaml_string, custom_objects={}) | return model_from_config(config, custom_objects=custom_objects) | Returns a model generated from a local yaml file,
which is either created by hand or from to_yaml method
of Sequential or Graph | Returns a model generated from a local yaml file,
which is either created by hand or from to_yaml method
of Sequential or Graph | [
"Returns",
"a",
"model",
"generated",
"from",
"a",
"local",
"yaml",
"file",
"which",
"is",
"either",
"created",
"by",
"hand",
"or",
"from",
"to_yaml",
"method",
"of",
"Sequential",
"or",
"Graph"
] | def model_from_yaml(yaml_string, custom_objects={}):
'''
Returns a model generated from a local yaml file,
which is either created by hand or from to_yaml method
of Sequential or Graph
'''
import yaml
config = yaml.load(yaml_string)
return model_from_config(config, custom_objects=custom_objects) | [
"def",
"model_from_yaml",
"(",
"yaml_string",
",",
"custom_objects",
"=",
"{",
"}",
")",
":",
"import",
"yaml",
"config",
"=",
"yaml",
".",
"load",
"(",
"yaml_string",
")",
"return",
"model_from_config",
"(",
"config",
",",
"custom_objects",
"=",
"custom_objec... | https://github.com/jacoxu/encoder_decoder/blob/6829c3bc42105aedfd1b8a81c81be19df4326c0a/keras/models.py#L152-L160 | |
cltk/cltk | 1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1 | src/cltk/tag/pos.py | python | POSTag.tag_tnt | (self, untagged_string: str) | return tagged_text | Tag POS with TnT tagger.
:type untagged_string: str
:param : An untagged, untokenized string of text.
:rtype tagged_text: str | Tag POS with TnT tagger.
:type untagged_string: str
:param : An untagged, untokenized string of text.
:rtype tagged_text: str | [
"Tag",
"POS",
"with",
"TnT",
"tagger",
".",
":",
"type",
"untagged_string",
":",
"str",
":",
"param",
":",
"An",
"untagged",
"untokenized",
"string",
"of",
"text",
".",
":",
"rtype",
"tagged_text",
":",
"str"
] | def tag_tnt(self, untagged_string: str):
"""Tag POS with TnT tagger.
:type untagged_string: str
:param : An untagged, untokenized string of text.
:rtype tagged_text: str
"""
untagged_tokens = wordpunct_tokenize(untagged_string)
tagger = self._load_model("tnt")
tagged_text = tagger.tag(untagged_tokens)
return tagged_text | [
"def",
"tag_tnt",
"(",
"self",
",",
"untagged_string",
":",
"str",
")",
":",
"untagged_tokens",
"=",
"wordpunct_tokenize",
"(",
"untagged_string",
")",
"tagger",
"=",
"self",
".",
"_load_model",
"(",
"\"tnt\"",
")",
"tagged_text",
"=",
"tagger",
".",
"tag",
... | https://github.com/cltk/cltk/blob/1a8c2f5ef72389e2579dfce1fa5af8e59ebc9ec1/src/cltk/tag/pos.py#L143-L152 | |
facebookresearch/pyrobot | 27ffd64bbb7ce3ff6ec4b2122d84b438d5641d0f | examples/grasping/grasp_samplers/grasp_object.py | python | GraspTorchObj.convert_hw | (self, h) | return torch.FloatTensor(h) | Converts a list of floats to a torch Tensor
:param h: List of floats
:type h: list
:returns: A torch FloatTensor
:rtype: torch FloatTensor | Converts a list of floats to a torch Tensor
:param h: List of floats
:type h: list
:returns: A torch FloatTensor
:rtype: torch FloatTensor | [
"Converts",
"a",
"list",
"of",
"floats",
"to",
"a",
"torch",
"Tensor",
":",
"param",
"h",
":",
"List",
"of",
"floats",
":",
"type",
"h",
":",
"list",
":",
"returns",
":",
"A",
"torch",
"FloatTensor",
":",
"rtype",
":",
"torch",
"FloatTensor"
] | def convert_hw(self, h):
"""
Converts a list of floats to a torch Tensor
:param h: List of floats
:type h: list
:returns: A torch FloatTensor
:rtype: torch FloatTensor
"""
return torch.FloatTensor(h) | [
"def",
"convert_hw",
"(",
"self",
",",
"h",
")",
":",
"return",
"torch",
".",
"FloatTensor",
"(",
"h",
")"
] | https://github.com/facebookresearch/pyrobot/blob/27ffd64bbb7ce3ff6ec4b2122d84b438d5641d0f/examples/grasping/grasp_samplers/grasp_object.py#L119-L129 | |
Project-Platypus/Platypus | a4e56410a772798e905407e99f80d03b86296ad3 | platypus/algorithms.py | python | SMPSO._mutate | (self) | [] | def _mutate(self):
for i in range(self.swarm_size):
if i % 6 == 0:
self.particles[i] = self.mutate.mutate(self.particles[i]) | [
"def",
"_mutate",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"swarm_size",
")",
":",
"if",
"i",
"%",
"6",
"==",
"0",
":",
"self",
".",
"particles",
"[",
"i",
"]",
"=",
"self",
".",
"mutate",
".",
"mutate",
"(",
"self",
... | https://github.com/Project-Platypus/Platypus/blob/a4e56410a772798e905407e99f80d03b86296ad3/platypus/algorithms.py#L1023-L1026 | ||||
PyMVPA/PyMVPA | 76c476b3de8264b0bb849bf226da5674d659564e | mvpa2/clfs/model_selector.py | python | ModelSelector.__init__ | (self, parametric_model, dataset) | TODO: | TODO: | [
"TODO",
":"
] | def __init__(self, parametric_model, dataset):
"""TODO:
"""
self.parametric_model = parametric_model
self.dataset = dataset
self.hyperparameters_best = None
self.log_marginal_likelihood_best = None
self.problem = None
pass | [
"def",
"__init__",
"(",
"self",
",",
"parametric_model",
",",
"dataset",
")",
":",
"self",
".",
"parametric_model",
"=",
"parametric_model",
"self",
".",
"dataset",
"=",
"dataset",
"self",
".",
"hyperparameters_best",
"=",
"None",
"self",
".",
"log_marginal_like... | https://github.com/PyMVPA/PyMVPA/blob/76c476b3de8264b0bb849bf226da5674d659564e/mvpa2/clfs/model_selector.py#L51-L59 | ||
rajarshd/Multi-Step-Reasoning | 3218d626839f7217554f38d82e00e4f460b508e4 | msr/reader/utils.py | python | f1_score | (prediction, ground_truth) | return f1 | Compute the geometric mean of precision and recall for answer tokens. | Compute the geometric mean of precision and recall for answer tokens. | [
"Compute",
"the",
"geometric",
"mean",
"of",
"precision",
"and",
"recall",
"for",
"answer",
"tokens",
"."
] | def f1_score(prediction, ground_truth):
"""Compute the geometric mean of precision and recall for answer tokens."""
prediction_tokens = normalize_answer(prediction).split()
ground_truth_tokens = normalize_answer(ground_truth).split()
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
num_same = sum(common.values())
if num_same == 0:
return 0
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(ground_truth_tokens)
f1 = (2 * precision * recall) / (precision + recall)
return f1 | [
"def",
"f1_score",
"(",
"prediction",
",",
"ground_truth",
")",
":",
"prediction_tokens",
"=",
"normalize_answer",
"(",
"prediction",
")",
".",
"split",
"(",
")",
"ground_truth_tokens",
"=",
"normalize_answer",
"(",
"ground_truth",
")",
".",
"split",
"(",
")",
... | https://github.com/rajarshd/Multi-Step-Reasoning/blob/3218d626839f7217554f38d82e00e4f460b508e4/msr/reader/utils.py#L201-L212 | |
GenTang/intro_ds | 886e678e5353e9b4c0d4f3da83a00d6b9a2f06a5 | ch10-unsupervised/dimension_reduction/kernel_pca.py | python | trainKernelPCA | (data) | return model | 使用带有核函数的主成分分析对数据进行降维 | 使用带有核函数的主成分分析对数据进行降维 | [
"使用带有核函数的主成分分析对数据进行降维"
] | def trainKernelPCA(data):
"""
使用带有核函数的主成分分析对数据进行降维
"""
model = KernelPCA(n_components=2, kernel="rbf", gamma=25)
model.fit(data)
return model | [
"def",
"trainKernelPCA",
"(",
"data",
")",
":",
"model",
"=",
"KernelPCA",
"(",
"n_components",
"=",
"2",
",",
"kernel",
"=",
"\"rbf\"",
",",
"gamma",
"=",
"25",
")",
"model",
".",
"fit",
"(",
"data",
")",
"return",
"model"
] | https://github.com/GenTang/intro_ds/blob/886e678e5353e9b4c0d4f3da83a00d6b9a2f06a5/ch10-unsupervised/dimension_reduction/kernel_pca.py#L34-L40 | |
DataDog/dd-trace-py | 13f9c6c1a8b4820365b299ab204f2bb5189d2a49 | ddtrace/contrib/rq/__init__.py | python | traced_perform_job | (rq, pin, func, instance, args, kwargs) | Trace rq.Worker.perform_job | Trace rq.Worker.perform_job | [
"Trace",
"rq",
".",
"Worker",
".",
"perform_job"
] | def traced_perform_job(rq, pin, func, instance, args, kwargs):
"""Trace rq.Worker.perform_job"""
# `perform_job` is executed in a freshly forked, short-lived instance
job = get_argument_value(args, kwargs, 0, "job")
if config.rq_worker.distributed_tracing_enabled:
ctx = HTTPPropagator.extract(job.meta)
if ctx.trace_id:
pin.tracer.context_provider.activate(ctx)
try:
with pin.tracer.trace(
"rq.worker.perform_job",
service=trace_utils.int_service(pin, config.rq_worker),
span_type=SpanTypes.WORKER,
resource=job.func_name,
) as span:
span.set_tag("job.id", job.get_id())
try:
return func(*args, **kwargs)
finally:
span.set_tag("job.status", job.get_status())
span.set_tag("job.origin", job.origin)
if job.is_failed:
span.error = 1
finally:
# Force flush to agent since the process `os.exit()`s
# immediately after this method returns
pin.tracer.writer.flush_queue() | [
"def",
"traced_perform_job",
"(",
"rq",
",",
"pin",
",",
"func",
",",
"instance",
",",
"args",
",",
"kwargs",
")",
":",
"# `perform_job` is executed in a freshly forked, short-lived instance",
"job",
"=",
"get_argument_value",
"(",
"args",
",",
"kwargs",
",",
"0",
... | https://github.com/DataDog/dd-trace-py/blob/13f9c6c1a8b4820365b299ab204f2bb5189d2a49/ddtrace/contrib/rq/__init__.py#L152-L180 | ||
mcfletch/pyopengl | 02d11dad9ff18e50db10e975c4756e17bf198464 | OpenGL/GL/ATI/envmap_bumpmap.py | python | glInitEnvmapBumpmapATI | () | return extensions.hasGLExtension( _EXTENSION_NAME ) | Return boolean indicating whether this extension is available | Return boolean indicating whether this extension is available | [
"Return",
"boolean",
"indicating",
"whether",
"this",
"extension",
"is",
"available"
] | def glInitEnvmapBumpmapATI():
'''Return boolean indicating whether this extension is available'''
from OpenGL import extensions
return extensions.hasGLExtension( _EXTENSION_NAME ) | [
"def",
"glInitEnvmapBumpmapATI",
"(",
")",
":",
"from",
"OpenGL",
"import",
"extensions",
"return",
"extensions",
".",
"hasGLExtension",
"(",
"_EXTENSION_NAME",
")"
] | https://github.com/mcfletch/pyopengl/blob/02d11dad9ff18e50db10e975c4756e17bf198464/OpenGL/GL/ATI/envmap_bumpmap.py#L35-L38 | |
WikidPad/WikidPad | 558109638807bc76b4672922686e416ab2d5f79c | WikidPad/lib/pwiki/WikiHtmlView2.py | python | WikiHtmlView2.addZoom | (self, step) | Modify the zoom setting by step relative to current zoom in
configuration.
html2.SetZoom only has 5 different zoom levels (0-4)
It may be worth using a javascript based zoom which would
allow for finer control | Modify the zoom setting by step relative to current zoom in
configuration. | [
"Modify",
"the",
"zoom",
"setting",
"by",
"step",
"relative",
"to",
"current",
"zoom",
"in",
"configuration",
"."
] | def addZoom(self, step):
"""
Modify the zoom setting by step relative to current zoom in
configuration.
html2.SetZoom only has 5 different zoom levels (0-4)
It may be worth using a javascript based zoom which would
allow for finer control
"""
zoom = self.presenter.getConfig().getint("main", "preview_zoom", 0)
zoom += step
# Restrict to allowed range.
# In the internal configuration the value 0 means the default size
# This should be kept consistent between different WikiHtmlView
# implementations.
# So it is restricted to range -2...2
zoom = between(-2, zoom, 2)
self.presenter.getConfig().set("main", "preview_zoom", str(zoom))
self.outOfSync = True
self.refresh()
# The parameter must be in range 0...4 where 2 is default value
try:
self.html.SetZoom(zoom + 2)
except wx._core.wxAssertionError:
# Fails for unknown reason with IE under Windows 7
pass | [
"def",
"addZoom",
"(",
"self",
",",
"step",
")",
":",
"zoom",
"=",
"self",
".",
"presenter",
".",
"getConfig",
"(",
")",
".",
"getint",
"(",
"\"main\"",
",",
"\"preview_zoom\"",
",",
"0",
")",
"zoom",
"+=",
"step",
"# Restrict to allowed range.",
"# In the... | https://github.com/WikidPad/WikidPad/blob/558109638807bc76b4672922686e416ab2d5f79c/WikidPad/lib/pwiki/WikiHtmlView2.py#L1324-L1353 | ||
AppScale/gts | 46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9 | AppServer/lib/mox/mox.py | python | Mox.ResetAll | (self) | Call reset on all mock objects. This does not unset stubs. | Call reset on all mock objects. This does not unset stubs. | [
"Call",
"reset",
"on",
"all",
"mock",
"objects",
".",
"This",
"does",
"not",
"unset",
"stubs",
"."
] | def ResetAll(self):
"""Call reset on all mock objects. This does not unset stubs."""
for mock_obj in self._mock_objects:
mock_obj._Reset() | [
"def",
"ResetAll",
"(",
"self",
")",
":",
"for",
"mock_obj",
"in",
"self",
".",
"_mock_objects",
":",
"mock_obj",
".",
"_Reset",
"(",
")"
] | https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/mox/mox.py#L286-L290 | ||
Trusted-AI/adversarial-robustness-toolbox | 9fabffdbb92947efa1ecc5d825d634d30dfbaf29 | art/defences/detector/poison/activation_defence.py | python | measure_misclassification | (
classifier: "CLASSIFIER_NEURALNETWORK_TYPE", x_test: np.ndarray, y_test: np.ndarray
) | return 1.0 - np.sum(predictions == np.argmax(y_test, axis=1)) / y_test.shape[0] | Computes 1-accuracy given x_test and y_test
:param classifier: Classifier to be used for predictions.
:param x_test: Test set.
:param y_test: Labels for test set.
:return: 1-accuracy. | Computes 1-accuracy given x_test and y_test | [
"Computes",
"1",
"-",
"accuracy",
"given",
"x_test",
"and",
"y_test"
] | def measure_misclassification(
classifier: "CLASSIFIER_NEURALNETWORK_TYPE", x_test: np.ndarray, y_test: np.ndarray
) -> float:
"""
Computes 1-accuracy given x_test and y_test
:param classifier: Classifier to be used for predictions.
:param x_test: Test set.
:param y_test: Labels for test set.
:return: 1-accuracy.
"""
predictions = np.argmax(classifier.predict(x_test), axis=1)
return 1.0 - np.sum(predictions == np.argmax(y_test, axis=1)) / y_test.shape[0] | [
"def",
"measure_misclassification",
"(",
"classifier",
":",
"\"CLASSIFIER_NEURALNETWORK_TYPE\"",
",",
"x_test",
":",
"np",
".",
"ndarray",
",",
"y_test",
":",
"np",
".",
"ndarray",
")",
"->",
"float",
":",
"predictions",
"=",
"np",
".",
"argmax",
"(",
"classif... | https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/9fabffdbb92947efa1ecc5d825d634d30dfbaf29/art/defences/detector/poison/activation_defence.py#L617-L629 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.