partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | AsyncBserCodec._loads | Parse the BSER packet | python/pywatchman_aio/__init__.py | def _loads(self, response):
""" Parse the BSER packet """
return bser.loads(
response,
True,
value_encoding=encoding.get_local_encoding(),
value_errors=encoding.default_local_errors,
) | def _loads(self, response):
""" Parse the BSER packet """
return bser.loads(
response,
True,
value_encoding=encoding.get_local_encoding(),
value_errors=encoding.default_local_errors,
) | [
"Parse",
"the",
"BSER",
"packet"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L191-L198 | [
"def",
"_loads",
"(",
"self",
",",
"response",
")",
":",
"return",
"bser",
".",
"loads",
"(",
"response",
",",
"True",
",",
"value_encoding",
"=",
"encoding",
".",
"get_local_encoding",
"(",
")",
",",
"value_errors",
"=",
"encoding",
".",
"default_local_erro... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | AIOClient.receive_bilateral_response | Receive the response to a request made to the Watchman service. | python/pywatchman_aio/__init__.py | async def receive_bilateral_response(self):
"""Receive the response to a request made to the Watchman service."""
self._check_receive_loop()
resp = await self.bilateral_response_queue.get()
self._check_error(resp)
return resp | async def receive_bilateral_response(self):
"""Receive the response to a request made to the Watchman service."""
self._check_receive_loop()
resp = await self.bilateral_response_queue.get()
self._check_error(resp)
return resp | [
"Receive",
"the",
"response",
"to",
"a",
"request",
"made",
"to",
"the",
"Watchman",
"service",
"."
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L240-L246 | [
"async",
"def",
"receive_bilateral_response",
"(",
"self",
")",
":",
"self",
".",
"_check_receive_loop",
"(",
")",
"resp",
"=",
"await",
"self",
".",
"bilateral_response_queue",
".",
"get",
"(",
")",
"self",
".",
"_check_error",
"(",
"resp",
")",
"return",
"... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | AIOClient.query | Send a query to the Watchman service and return the response. | python/pywatchman_aio/__init__.py | async def query(self, *args):
"""Send a query to the Watchman service and return the response."""
self._check_receive_loop()
try:
await self.connection.send(args)
return await self.receive_bilateral_response()
except CommandError as ex:
ex.setCommand(... | async def query(self, *args):
"""Send a query to the Watchman service and return the response."""
self._check_receive_loop()
try:
await self.connection.send(args)
return await self.receive_bilateral_response()
except CommandError as ex:
ex.setCommand(... | [
"Send",
"a",
"query",
"to",
"the",
"Watchman",
"service",
"and",
"return",
"the",
"response",
"."
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L248-L257 | [
"async",
"def",
"query",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"_check_receive_loop",
"(",
")",
"try",
":",
"await",
"self",
".",
"connection",
".",
"send",
"(",
"args",
")",
"return",
"await",
"self",
".",
"receive_bilateral_response",
"... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | AIOClient.capability_check | Perform a server capability check. | python/pywatchman_aio/__init__.py | async def capability_check(self, optional=None, required=None):
"""Perform a server capability check."""
self._check_receive_loop()
# If the returned response is an error, self.query will raise an error
await self.query(
"version", {"optional": optional or [], "required": re... | async def capability_check(self, optional=None, required=None):
"""Perform a server capability check."""
self._check_receive_loop()
# If the returned response is an error, self.query will raise an error
await self.query(
"version", {"optional": optional or [], "required": re... | [
"Perform",
"a",
"server",
"capability",
"check",
"."
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L259-L266 | [
"async",
"def",
"capability_check",
"(",
"self",
",",
"optional",
"=",
"None",
",",
"required",
"=",
"None",
")",
":",
"self",
".",
"_check_receive_loop",
"(",
")",
"# If the returned response is an error, self.query will raise an error",
"await",
"self",
".",
"query"... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | AIOClient.get_subscription | Retrieve the data associated with a named subscription
Returns None if there is no data associated with `name`
If root is not None, then only return the subscription
data that matches both root and name. When used in this way,
remove processing impacts both the unscoped and scoped sto... | python/pywatchman_aio/__init__.py | async def get_subscription(self, name, root):
""" Retrieve the data associated with a named subscription
Returns None if there is no data associated with `name`
If root is not None, then only return the subscription
data that matches both root and name. When used in this way,
... | async def get_subscription(self, name, root):
""" Retrieve the data associated with a named subscription
Returns None if there is no data associated with `name`
If root is not None, then only return the subscription
data that matches both root and name. When used in this way,
... | [
"Retrieve",
"the",
"data",
"associated",
"with",
"a",
"named",
"subscription"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L268-L282 | [
"async",
"def",
"get_subscription",
"(",
"self",
",",
"name",
",",
"root",
")",
":",
"self",
".",
"_check_receive_loop",
"(",
")",
"self",
".",
"_ensure_subscription_queue_exists",
"(",
"name",
",",
"root",
")",
"res",
"=",
"await",
"self",
".",
"sub_by_root... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | AIOClient.pop_log | Get one log from the log queue. | python/pywatchman_aio/__init__.py | async def pop_log(self):
"""Get one log from the log queue."""
self._check_receive_loop()
res = self.log_queue.get()
self._check_error(res)
return res | async def pop_log(self):
"""Get one log from the log queue."""
self._check_receive_loop()
res = self.log_queue.get()
self._check_error(res)
return res | [
"Get",
"one",
"log",
"from",
"the",
"log",
"queue",
"."
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L284-L289 | [
"async",
"def",
"pop_log",
"(",
"self",
")",
":",
"self",
".",
"_check_receive_loop",
"(",
")",
"res",
"=",
"self",
".",
"log_queue",
".",
"get",
"(",
")",
"self",
".",
"_check_error",
"(",
"res",
")",
"return",
"res"
] | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | AIOClient.close | Close the underlying connection. | python/pywatchman_aio/__init__.py | def close(self):
"""Close the underlying connection."""
self._closed = True
if self.receive_task:
self.receive_task.cancel()
if self.connection:
self.connection.close() | def close(self):
"""Close the underlying connection."""
self._closed = True
if self.receive_task:
self.receive_task.cancel()
if self.connection:
self.connection.close() | [
"Close",
"the",
"underlying",
"connection",
"."
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L291-L297 | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_closed",
"=",
"True",
"if",
"self",
".",
"receive_task",
":",
"self",
".",
"receive_task",
".",
"cancel",
"(",
")",
"if",
"self",
".",
"connection",
":",
"self",
".",
"connection",
".",
"close",
"... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | AIOClient.enable_receiving | Schedules the receive loop to run on the given loop. | python/pywatchman_aio/__init__.py | def enable_receiving(self, loop=None):
"""Schedules the receive loop to run on the given loop."""
self.receive_task = asyncio.ensure_future(self._receive_loop(), loop=loop)
def do_if_done(fut):
try:
fut.result()
except asyncio.CancelledError:
... | def enable_receiving(self, loop=None):
"""Schedules the receive loop to run on the given loop."""
self.receive_task = asyncio.ensure_future(self._receive_loop(), loop=loop)
def do_if_done(fut):
try:
fut.result()
except asyncio.CancelledError:
... | [
"Schedules",
"the",
"receive",
"loop",
"to",
"run",
"on",
"the",
"given",
"loop",
"."
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L299-L312 | [
"def",
"enable_receiving",
"(",
"self",
",",
"loop",
"=",
"None",
")",
":",
"self",
".",
"receive_task",
"=",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"_receive_loop",
"(",
")",
",",
"loop",
"=",
"loop",
")",
"def",
"do_if_done",
"(",
"fut",
... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | AIOClient.from_socket | Create a new AIOClient using Unix transport and BSER Codec
connecting to the specified socket. If the specified socket is None,
then resolve the socket path automatically.
This method also schedules the receive loop to run on the event loop.
This method is a coroutine. | python/pywatchman_aio/__init__.py | async def from_socket(cls, sockname: typing.Optional[str] = None) -> "AIOClient":
"""Create a new AIOClient using Unix transport and BSER Codec
connecting to the specified socket. If the specified socket is None,
then resolve the socket path automatically.
This method also schedules the... | async def from_socket(cls, sockname: typing.Optional[str] = None) -> "AIOClient":
"""Create a new AIOClient using Unix transport and BSER Codec
connecting to the specified socket. If the specified socket is None,
then resolve the socket path automatically.
This method also schedules the... | [
"Create",
"a",
"new",
"AIOClient",
"using",
"Unix",
"transport",
"and",
"BSER",
"Codec",
"connecting",
"to",
"the",
"specified",
"socket",
".",
"If",
"the",
"specified",
"socket",
"is",
"None",
"then",
"resolve",
"the",
"socket",
"path",
"automatically",
"."
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L315-L330 | [
"async",
"def",
"from_socket",
"(",
"cls",
",",
"sockname",
":",
"typing",
".",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"\"AIOClient\"",
":",
"if",
"not",
"sockname",
":",
"sockname",
"=",
"await",
"_resolve_sockname",
"(",
")",
"transport",
... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | AIOClient._receive_loop | Receive the response to a request made to the Watchman service.
Note that when trying to receive a PDU from the Watchman service,
we might get a unilateral response to a subscription or log, so these
are processed and queued up for later retrieval. This function only
returns when a non-... | python/pywatchman_aio/__init__.py | async def _receive_loop(self):
"""Receive the response to a request made to the Watchman service.
Note that when trying to receive a PDU from the Watchman service,
we might get a unilateral response to a subscription or log, so these
are processed and queued up for later retrieval. This... | async def _receive_loop(self):
"""Receive the response to a request made to the Watchman service.
Note that when trying to receive a PDU from the Watchman service,
we might get a unilateral response to a subscription or log, so these
are processed and queued up for later retrieval. This... | [
"Receive",
"the",
"response",
"to",
"a",
"request",
"made",
"to",
"the",
"Watchman",
"service",
"."
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L332-L351 | [
"async",
"def",
"_receive_loop",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"response",
"=",
"await",
"self",
".",
"connection",
".",
"receive",
"(",
")",
"if",
"self",
".",
"_is_unilateral",
"(",
"response",
")",
":",
"await",
"self",
".... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | _win32_strerror | expand a win32 error code into a human readable message | python/pywatchman/__init__.py | def _win32_strerror(err):
""" expand a win32 error code into a human readable message """
# FormatMessage will allocate memory and assign it here
buf = ctypes.c_char_p()
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_IGNORE_INSERTS,
... | def _win32_strerror(err):
""" expand a win32 error code into a human readable message """
# FormatMessage will allocate memory and assign it here
buf = ctypes.c_char_p()
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_IGNORE_INSERTS,
... | [
"expand",
"a",
"win32",
"error",
"code",
"into",
"a",
"human",
"readable",
"message"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L211-L230 | [
"def",
"_win32_strerror",
"(",
"err",
")",
":",
"# FormatMessage will allocate memory and assign it here",
"buf",
"=",
"ctypes",
".",
"c_char_p",
"(",
")",
"FormatMessage",
"(",
"FORMAT_MESSAGE_FROM_SYSTEM",
"|",
"FORMAT_MESSAGE_ALLOCATE_BUFFER",
"|",
"FORMAT_MESSAGE_IGNORE_I... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | _get_overlapped_result_ex_impl | Windows 7 and earlier does not support GetOverlappedResultEx. The
alternative is to use GetOverlappedResult and wait for read or write
operation to complete. This is done be using CreateEvent and
WaitForSingleObjectEx. CreateEvent, WaitForSingleObjectEx
and GetOverlappedResult are all part of Windows AP... | python/pywatchman/__init__.py | def _get_overlapped_result_ex_impl(pipe, olap, nbytes, millis, alertable):
""" Windows 7 and earlier does not support GetOverlappedResultEx. The
alternative is to use GetOverlappedResult and wait for read or write
operation to complete. This is done be using CreateEvent and
WaitForSingleObjectEx. Create... | def _get_overlapped_result_ex_impl(pipe, olap, nbytes, millis, alertable):
""" Windows 7 and earlier does not support GetOverlappedResultEx. The
alternative is to use GetOverlappedResult and wait for read or write
operation to complete. This is done be using CreateEvent and
WaitForSingleObjectEx. Create... | [
"Windows",
"7",
"and",
"earlier",
"does",
"not",
"support",
"GetOverlappedResultEx",
".",
"The",
"alternative",
"is",
"to",
"use",
"GetOverlappedResult",
"and",
"wait",
"for",
"read",
"or",
"write",
"operation",
"to",
"complete",
".",
"This",
"is",
"done",
"be... | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L397-L434 | [
"def",
"_get_overlapped_result_ex_impl",
"(",
"pipe",
",",
"olap",
",",
"nbytes",
",",
"millis",
",",
"alertable",
")",
":",
"log",
"(",
"\"Preparing to wait for maximum %dms\"",
",",
"millis",
")",
"if",
"millis",
"!=",
"0",
":",
"waitReturnCode",
"=",
"WaitFor... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | Transport.readLine | read a line
Maintains its own buffer, callers of the transport should not mix
calls to readBytes and readLine. | python/pywatchman/__init__.py | def readLine(self):
""" read a line
Maintains its own buffer, callers of the transport should not mix
calls to readBytes and readLine.
"""
if self.buf is None:
self.buf = []
# Buffer may already have a line if we've received unilateral
# response(s) f... | def readLine(self):
""" read a line
Maintains its own buffer, callers of the transport should not mix
calls to readBytes and readLine.
"""
if self.buf is None:
self.buf = []
# Buffer may already have a line if we've received unilateral
# response(s) f... | [
"read",
"a",
"line",
"Maintains",
"its",
"own",
"buffer",
"callers",
"of",
"the",
"transport",
"should",
"not",
"mix",
"calls",
"to",
"readBytes",
"and",
"readLine",
"."
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L311-L333 | [
"def",
"readLine",
"(",
"self",
")",
":",
"if",
"self",
".",
"buf",
"is",
"None",
":",
"self",
".",
"buf",
"=",
"[",
"]",
"# Buffer may already have a line if we've received unilateral",
"# response(s) from the server",
"if",
"len",
"(",
"self",
".",
"buf",
")",... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | WindowsNamedPipeTransport.readBytes | A read can block for an unbounded amount of time, even if the
kernel reports that the pipe handle is signalled, so we need to
always perform our reads asynchronously | python/pywatchman/__init__.py | def readBytes(self, size):
""" A read can block for an unbounded amount of time, even if the
kernel reports that the pipe handle is signalled, so we need to
always perform our reads asynchronously
"""
# try to satisfy the read from any buffered data
if self._iobu... | def readBytes(self, size):
""" A read can block for an unbounded amount of time, even if the
kernel reports that the pipe handle is signalled, so we need to
always perform our reads asynchronously
"""
# try to satisfy the read from any buffered data
if self._iobu... | [
"A",
"read",
"can",
"block",
"for",
"an",
"unbounded",
"amount",
"of",
"time",
"even",
"if",
"the",
"kernel",
"reports",
"that",
"the",
"pipe",
"handle",
"is",
"signalled",
"so",
"we",
"need",
"to",
"always",
"perform",
"our",
"reads",
"asynchronously"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L496-L562 | [
"def",
"readBytes",
"(",
"self",
",",
"size",
")",
":",
"# try to satisfy the read from any buffered data",
"if",
"self",
".",
"_iobuf",
":",
"if",
"size",
">=",
"len",
"(",
"self",
".",
"_iobuf",
")",
":",
"res",
"=",
"self",
".",
"_iobuf",
"self",
".",
... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | client._connect | establish transport connection | python/pywatchman/__init__.py | def _connect(self):
""" establish transport connection """
if self.recvConn:
if self.pid != os.getpid():
raise UseAfterFork(
"do not re-use a connection after fork; open a new client instead"
)
return
if self.sockpath ... | def _connect(self):
""" establish transport connection """
if self.recvConn:
if self.pid != os.getpid():
raise UseAfterFork(
"do not re-use a connection after fork; open a new client instead"
)
return
if self.sockpath ... | [
"establish",
"transport",
"connection"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L980-L1000 | [
"def",
"_connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"recvConn",
":",
"if",
"self",
".",
"pid",
"!=",
"os",
".",
"getpid",
"(",
")",
":",
"raise",
"UseAfterFork",
"(",
"\"do not re-use a connection after fork; open a new client instead\"",
")",
"return",... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | client.receive | receive the next PDU from the watchman service
If the client has activated subscriptions or logs then
this PDU may be a unilateral PDU sent by the service to
inform the client of a log event or subscription change.
It may also simply be the response portion of a request
initiat... | python/pywatchman/__init__.py | def receive(self):
""" receive the next PDU from the watchman service
If the client has activated subscriptions or logs then
this PDU may be a unilateral PDU sent by the service to
inform the client of a log event or subscription change.
It may also simply be the response porti... | def receive(self):
""" receive the next PDU from the watchman service
If the client has activated subscriptions or logs then
this PDU may be a unilateral PDU sent by the service to
inform the client of a log event or subscription change.
It may also simply be the response porti... | [
"receive",
"the",
"next",
"PDU",
"from",
"the",
"watchman",
"service"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L1019-L1056 | [
"def",
"receive",
"(",
"self",
")",
":",
"self",
".",
"_connect",
"(",
")",
"result",
"=",
"self",
".",
"recvConn",
".",
"receive",
"(",
")",
"if",
"self",
".",
"_hasprop",
"(",
"result",
",",
"\"error\"",
")",
":",
"raise",
"CommandError",
"(",
"res... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | client.getLog | Retrieve buffered log data
If remove is true the data will be removed from the buffer.
Otherwise it will be left in the buffer | python/pywatchman/__init__.py | def getLog(self, remove=True):
""" Retrieve buffered log data
If remove is true the data will be removed from the buffer.
Otherwise it will be left in the buffer
"""
res = self.logs
if remove:
self.logs = []
return res | def getLog(self, remove=True):
""" Retrieve buffered log data
If remove is true the data will be removed from the buffer.
Otherwise it will be left in the buffer
"""
res = self.logs
if remove:
self.logs = []
return res | [
"Retrieve",
"buffered",
"log",
"data"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L1067-L1076 | [
"def",
"getLog",
"(",
"self",
",",
"remove",
"=",
"True",
")",
":",
"res",
"=",
"self",
".",
"logs",
"if",
"remove",
":",
"self",
".",
"logs",
"=",
"[",
"]",
"return",
"res"
] | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | client.getSubscription | Retrieve the data associated with a named subscription
If remove is True (the default), the subscription data is removed
from the buffer. Otherwise the data is returned but left in
the buffer.
Returns None if there is no data associated with `name`
If root is not None, then o... | python/pywatchman/__init__.py | def getSubscription(self, name, remove=True, root=None):
""" Retrieve the data associated with a named subscription
If remove is True (the default), the subscription data is removed
from the buffer. Otherwise the data is returned but left in
the buffer.
Returns None if there i... | def getSubscription(self, name, remove=True, root=None):
""" Retrieve the data associated with a named subscription
If remove is True (the default), the subscription data is removed
from the buffer. Otherwise the data is returned but left in
the buffer.
Returns None if there i... | [
"Retrieve",
"the",
"data",
"associated",
"with",
"a",
"named",
"subscription"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L1078-L1111 | [
"def",
"getSubscription",
"(",
"self",
",",
"name",
",",
"remove",
"=",
"True",
",",
"root",
"=",
"None",
")",
":",
"if",
"root",
"is",
"not",
"None",
":",
"root",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"normcase",
... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | client.query | Send a query to the watchman service and return the response
This call will block until the response is returned.
If any unilateral responses are sent by the service in between
the request-response they will be buffered up in the client object
and NOT returned via this method. | python/pywatchman/__init__.py | def query(self, *args):
""" Send a query to the watchman service and return the response
This call will block until the response is returned.
If any unilateral responses are sent by the service in between
the request-response they will be buffered up in the client object
and NOT... | def query(self, *args):
""" Send a query to the watchman service and return the response
This call will block until the response is returned.
If any unilateral responses are sent by the service in between
the request-response they will be buffered up in the client object
and NOT... | [
"Send",
"a",
"query",
"to",
"the",
"watchman",
"service",
"and",
"return",
"the",
"response"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L1113-L1143 | [
"def",
"query",
"(",
"self",
",",
"*",
"args",
")",
":",
"log",
"(",
"\"calling client.query\"",
")",
"self",
".",
"_connect",
"(",
")",
"try",
":",
"self",
".",
"sendConn",
".",
"send",
"(",
"args",
")",
"res",
"=",
"self",
".",
"receive",
"(",
")... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | client.capabilityCheck | Perform a server capability check | python/pywatchman/__init__.py | def capabilityCheck(self, optional=None, required=None):
""" Perform a server capability check """
res = self.query(
"version", {"optional": optional or [], "required": required or []}
)
if not self._hasprop(res, "capabilities"):
# Server doesn't support capabili... | def capabilityCheck(self, optional=None, required=None):
""" Perform a server capability check """
res = self.query(
"version", {"optional": optional or [], "required": required or []}
)
if not self._hasprop(res, "capabilities"):
# Server doesn't support capabili... | [
"Perform",
"a",
"server",
"capability",
"check"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L1145-L1158 | [
"def",
"capabilityCheck",
"(",
"self",
",",
"optional",
"=",
"None",
",",
"required",
"=",
"None",
")",
":",
"res",
"=",
"self",
".",
"query",
"(",
"\"version\"",
",",
"{",
"\"optional\"",
":",
"optional",
"or",
"[",
"]",
",",
"\"required\"",
":",
"req... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | _read_bytes | Read bytes from a file-like object
@param fp: File-like object that implements read(int)
@type fp: file
@param buf: Buffer to read into
@type buf: bytes
@return: buf | python/pywatchman/load.py | def _read_bytes(fp, buf):
"""Read bytes from a file-like object
@param fp: File-like object that implements read(int)
@type fp: file
@param buf: Buffer to read into
@type buf: bytes
@return: buf
"""
# Do the first read without resizing the input buffer
offset = 0
remaining = ... | def _read_bytes(fp, buf):
"""Read bytes from a file-like object
@param fp: File-like object that implements read(int)
@type fp: file
@param buf: Buffer to read into
@type buf: bytes
@return: buf
"""
# Do the first read without resizing the input buffer
offset = 0
remaining = ... | [
"Read",
"bytes",
"from",
"a",
"file",
"-",
"like",
"object"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/load.py#L44-L65 | [
"def",
"_read_bytes",
"(",
"fp",
",",
"buf",
")",
":",
"# Do the first read without resizing the input buffer",
"offset",
"=",
"0",
"remaining",
"=",
"len",
"(",
"buf",
")",
"while",
"remaining",
">",
"0",
":",
"l",
"=",
"fp",
".",
"readinto",
"(",
"(",
"c... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | load | Deserialize a BSER-encoded blob.
@param fp: The file-object to deserialize.
@type file:
@param mutable: Whether to return mutable results.
@type mutable: bool
@param value_encoding: Optional codec to use to decode values. If
unspecified or None, return values as bytestr... | python/pywatchman/load.py | def load(fp, mutable=True, value_encoding=None, value_errors=None):
"""Deserialize a BSER-encoded blob.
@param fp: The file-object to deserialize.
@type file:
@param mutable: Whether to return mutable results.
@type mutable: bool
@param value_encoding: Optional codec to use to decode values. ... | def load(fp, mutable=True, value_encoding=None, value_errors=None):
"""Deserialize a BSER-encoded blob.
@param fp: The file-object to deserialize.
@type file:
@param mutable: Whether to return mutable results.
@type mutable: bool
@param value_encoding: Optional codec to use to decode values. ... | [
"Deserialize",
"a",
"BSER",
"-",
"encoded",
"blob",
"."
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/load.py#L68-L107 | [
"def",
"load",
"(",
"fp",
",",
"mutable",
"=",
"True",
",",
"value_encoding",
"=",
"None",
",",
"value_errors",
"=",
"None",
")",
":",
"buf",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"8192",
")",
"SNIFF_BUFFER_SIZE",
"=",
"len",
"(",
"EMPTY_HEADER"... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | make_docker_context | Returns a path to the Docker context directory. See parse_args.py.
Helper for making a command-line utility that writes your project's
Dockerfile and associated data into a (temporary) directory. Your main
program might look something like this:
print(make_docker_context(
lambda build... | build/fbcode_builder/make_docker_context.py | def make_docker_context(
get_steps_fn, github_project, opts=None, default_context_dir=None
):
'''
Returns a path to the Docker context directory. See parse_args.py.
Helper for making a command-line utility that writes your project's
Dockerfile and associated data into a (temporary) directory. Your... | def make_docker_context(
get_steps_fn, github_project, opts=None, default_context_dir=None
):
'''
Returns a path to the Docker context directory. See parse_args.py.
Helper for making a command-line utility that writes your project's
Dockerfile and associated data into a (temporary) directory. Your... | [
"Returns",
"a",
"path",
"to",
"the",
"Docker",
"context",
"directory",
".",
"See",
"parse_args",
".",
"py",
"."
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/make_docker_context.py#L27-L164 | [
"def",
"make_docker_context",
"(",
"get_steps_fn",
",",
"github_project",
",",
"opts",
"=",
"None",
",",
"default_context_dir",
"=",
"None",
")",
":",
"if",
"opts",
"is",
"None",
":",
"opts",
"=",
"{",
"}",
"valid_versions",
"=",
"(",
"(",
"'ubuntu:16.04'",
... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | FBCodeBuilder.diagnostics | Log some system diagnostics before/after setup for ease of debugging | build/fbcode_builder/fbcode_builder.py | def diagnostics(self):
'Log some system diagnostics before/after setup for ease of debugging'
# The builder's repr is not used in a command to avoid pointlessly
# invalidating Docker's build cache.
return self.step('Diagnostics', [
self.comment('Builder {0}'.format(repr(self)... | def diagnostics(self):
'Log some system diagnostics before/after setup for ease of debugging'
# The builder's repr is not used in a command to avoid pointlessly
# invalidating Docker's build cache.
return self.step('Diagnostics', [
self.comment('Builder {0}'.format(repr(self)... | [
"Log",
"some",
"system",
"diagnostics",
"before",
"/",
"after",
"setup",
"for",
"ease",
"of",
"debugging"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/fbcode_builder.py#L151-L161 | [
"def",
"diagnostics",
"(",
"self",
")",
":",
"# The builder's repr is not used in a command to avoid pointlessly",
"# invalidating Docker's build cache.",
"return",
"self",
".",
"step",
"(",
"'Diagnostics'",
",",
"[",
"self",
".",
"comment",
"(",
"'Builder {0}'",
".",
"fo... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | FBCodeBuilder.fb_github_project_workdir | This helper lets Facebook-internal CI special-cases FB projects | build/fbcode_builder/fbcode_builder.py | def fb_github_project_workdir(self, project_and_path, github_org='facebook'):
'This helper lets Facebook-internal CI special-cases FB projects'
project, path = project_and_path.split('/', 1)
return self.github_project_workdir(github_org + '/' + project, path) | def fb_github_project_workdir(self, project_and_path, github_org='facebook'):
'This helper lets Facebook-internal CI special-cases FB projects'
project, path = project_and_path.split('/', 1)
return self.github_project_workdir(github_org + '/' + project, path) | [
"This",
"helper",
"lets",
"Facebook",
"-",
"internal",
"CI",
"special",
"-",
"cases",
"FB",
"projects"
] | facebook/watchman | python | https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/fbcode_builder.py#L293-L296 | [
"def",
"fb_github_project_workdir",
"(",
"self",
",",
"project_and_path",
",",
"github_org",
"=",
"'facebook'",
")",
":",
"project",
",",
"path",
"=",
"project_and_path",
".",
"split",
"(",
"'/'",
",",
"1",
")",
"return",
"self",
".",
"github_project_workdir",
... | d416c249dd8f463dc69fc2691d0f890598c045a9 |
train | make_gp_funs | Functions that perform Gaussian process regression.
cov_func has signature (cov_params, x, x') | examples/gaussian_process.py | def make_gp_funs(cov_func, num_cov_params):
"""Functions that perform Gaussian process regression.
cov_func has signature (cov_params, x, x')"""
def unpack_kernel_params(params):
mean = params[0]
cov_params = params[2:]
noise_scale = np.exp(params[1]) + 0.0001
ret... | def make_gp_funs(cov_func, num_cov_params):
"""Functions that perform Gaussian process regression.
cov_func has signature (cov_params, x, x')"""
def unpack_kernel_params(params):
mean = params[0]
cov_params = params[2:]
noise_scale = np.exp(params[1]) + 0.0001
ret... | [
"Functions",
"that",
"perform",
"Gaussian",
"process",
"regression",
".",
"cov_func",
"has",
"signature",
"(",
"cov_params",
"x",
"x",
")"
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/gaussian_process.py#L13-L40 | [
"def",
"make_gp_funs",
"(",
"cov_func",
",",
"num_cov_params",
")",
":",
"def",
"unpack_kernel_params",
"(",
"params",
")",
":",
"mean",
"=",
"params",
"[",
"0",
"]",
"cov_params",
"=",
"params",
"[",
"2",
":",
"]",
"noise_scale",
"=",
"np",
".",
"exp",
... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | def_linear | Flags that a function is linear wrt all args | autograd/core.py | def def_linear(fun):
"""Flags that a function is linear wrt all args"""
defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs:
fun(*subval(args, argnum, g), **kwargs)) | def def_linear(fun):
"""Flags that a function is linear wrt all args"""
defjvp_argnum(fun, lambda argnum, g, ans, args, kwargs:
fun(*subval(args, argnum, g), **kwargs)) | [
"Flags",
"that",
"a",
"function",
"is",
"linear",
"wrt",
"all",
"args"
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/core.py#L151-L154 | [
"def",
"def_linear",
"(",
"fun",
")",
":",
"defjvp_argnum",
"(",
"fun",
",",
"lambda",
"argnum",
",",
"g",
",",
"ans",
",",
"args",
",",
"kwargs",
":",
"fun",
"(",
"*",
"subval",
"(",
"args",
",",
"argnum",
",",
"g",
")",
",",
"*",
"*",
"kwargs",... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | project | Project the velocity field to be approximately mass-conserving,
using a few iterations of Gauss-Seidel. | examples/fluidsim/fluidsim.py | def project(vx, vy):
"""Project the velocity field to be approximately mass-conserving,
using a few iterations of Gauss-Seidel."""
p = np.zeros(vx.shape)
h = 1.0/vx.shape[0]
div = -0.5 * h * (np.roll(vx, -1, axis=0) - np.roll(vx, 1, axis=0)
+ np.roll(vy, -1, axis=1) - np.roll(... | def project(vx, vy):
"""Project the velocity field to be approximately mass-conserving,
using a few iterations of Gauss-Seidel."""
p = np.zeros(vx.shape)
h = 1.0/vx.shape[0]
div = -0.5 * h * (np.roll(vx, -1, axis=0) - np.roll(vx, 1, axis=0)
+ np.roll(vy, -1, axis=1) - np.roll(... | [
"Project",
"the",
"velocity",
"field",
"to",
"be",
"approximately",
"mass",
"-",
"conserving",
"using",
"a",
"few",
"iterations",
"of",
"Gauss",
"-",
"Seidel",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/fluidsim/fluidsim.py#L18-L32 | [
"def",
"project",
"(",
"vx",
",",
"vy",
")",
":",
"p",
"=",
"np",
".",
"zeros",
"(",
"vx",
".",
"shape",
")",
"h",
"=",
"1.0",
"/",
"vx",
".",
"shape",
"[",
"0",
"]",
"div",
"=",
"-",
"0.5",
"*",
"h",
"*",
"(",
"np",
".",
"roll",
"(",
"... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | primitive | Wraps a function so that its gradient can be specified and its invocation
can be recorded. For examples, see the docs. | autograd/tracer.py | def primitive(f_raw):
"""
Wraps a function so that its gradient can be specified and its invocation
can be recorded. For examples, see the docs."""
@wraps(f_raw)
def f_wrapped(*args, **kwargs):
boxed_args, trace, node_constructor = find_top_boxed_args(args)
if boxed_args:
... | def primitive(f_raw):
"""
Wraps a function so that its gradient can be specified and its invocation
can be recorded. For examples, see the docs."""
@wraps(f_raw)
def f_wrapped(*args, **kwargs):
boxed_args, trace, node_constructor = find_top_boxed_args(args)
if boxed_args:
... | [
"Wraps",
"a",
"function",
"so",
"that",
"its",
"gradient",
"can",
"be",
"specified",
"and",
"its",
"invocation",
"can",
"be",
"recorded",
".",
"For",
"examples",
"see",
"the",
"docs",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/tracer.py#L31-L51 | [
"def",
"primitive",
"(",
"f_raw",
")",
":",
"@",
"wraps",
"(",
"f_raw",
")",
"def",
"f_wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"boxed_args",
",",
"trace",
",",
"node_constructor",
"=",
"find_top_boxed_args",
"(",
"args",
")",
"if... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | logsumexp | Numerically stable log(sum(exp(x))), also defined in scipy.misc | examples/define_gradient.py | def logsumexp(x):
"""Numerically stable log(sum(exp(x))), also defined in scipy.misc"""
max_x = np.max(x)
return max_x + np.log(np.sum(np.exp(x - max_x))) | def logsumexp(x):
"""Numerically stable log(sum(exp(x))), also defined in scipy.misc"""
max_x = np.max(x)
return max_x + np.log(np.sum(np.exp(x - max_x))) | [
"Numerically",
"stable",
"log",
"(",
"sum",
"(",
"exp",
"(",
"x",
")))",
"also",
"defined",
"in",
"scipy",
".",
"misc"
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/define_gradient.py#L19-L22 | [
"def",
"logsumexp",
"(",
"x",
")",
":",
"max_x",
"=",
"np",
".",
"max",
"(",
"x",
")",
"return",
"max_x",
"+",
"np",
".",
"log",
"(",
"np",
".",
"sum",
"(",
"np",
".",
"exp",
"(",
"x",
"-",
"max_x",
")",
")",
")"
] | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | init_net_params | Build a (weights, biases) tuples for all layers. | examples/variational_autoencoder.py | def init_net_params(scale, layer_sizes, rs=npr.RandomState(0)):
"""Build a (weights, biases) tuples for all layers."""
return [(scale * rs.randn(m, n), # weight matrix
scale * rs.randn(n)) # bias vector
for m, n in zip(layer_sizes[:-1], layer_sizes[1:])] | def init_net_params(scale, layer_sizes, rs=npr.RandomState(0)):
"""Build a (weights, biases) tuples for all layers."""
return [(scale * rs.randn(m, n), # weight matrix
scale * rs.randn(n)) # bias vector
for m, n in zip(layer_sizes[:-1], layer_sizes[1:])] | [
"Build",
"a",
"(",
"weights",
"biases",
")",
"tuples",
"for",
"all",
"layers",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/variational_autoencoder.py#L34-L38 | [
"def",
"init_net_params",
"(",
"scale",
",",
"layer_sizes",
",",
"rs",
"=",
"npr",
".",
"RandomState",
"(",
"0",
")",
")",
":",
"return",
"[",
"(",
"scale",
"*",
"rs",
".",
"randn",
"(",
"m",
",",
"n",
")",
",",
"# weight matrix",
"scale",
"*",
"rs... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | build_dataset | Loads a text file, and turns each line into an encoded sequence. | examples/hmm_em.py | def build_dataset(filename, max_lines=-1):
"""Loads a text file, and turns each line into an encoded sequence."""
encodings = dict(list(map(reversed, enumerate(string.printable))))
digitize = lambda char: encodings[char] if char in encodings else len(encodings)
encode_line = lambda line: np.array(list(m... | def build_dataset(filename, max_lines=-1):
"""Loads a text file, and turns each line into an encoded sequence."""
encodings = dict(list(map(reversed, enumerate(string.printable))))
digitize = lambda char: encodings[char] if char in encodings else len(encodings)
encode_line = lambda line: np.array(list(m... | [
"Loads",
"a",
"text",
"file",
"and",
"turns",
"each",
"line",
"into",
"an",
"encoded",
"sequence",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/hmm_em.py#L57-L70 | [
"def",
"build_dataset",
"(",
"filename",
",",
"max_lines",
"=",
"-",
"1",
")",
":",
"encodings",
"=",
"dict",
"(",
"list",
"(",
"map",
"(",
"reversed",
",",
"enumerate",
"(",
"string",
".",
"printable",
")",
")",
")",
")",
"digitize",
"=",
"lambda",
... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | project | Project the velocity field to be approximately mass-conserving,
using a few iterations of Gauss-Seidel. | examples/fluidsim/wing.py | def project(vx, vy, occlusion):
"""Project the velocity field to be approximately mass-conserving,
using a few iterations of Gauss-Seidel."""
p = np.zeros(vx.shape)
div = -0.5 * (np.roll(vx, -1, axis=1) - np.roll(vx, 1, axis=1)
+ np.roll(vy, -1, axis=0) - np.roll(vy, 1, axis=0))
d... | def project(vx, vy, occlusion):
"""Project the velocity field to be approximately mass-conserving,
using a few iterations of Gauss-Seidel."""
p = np.zeros(vx.shape)
div = -0.5 * (np.roll(vx, -1, axis=1) - np.roll(vx, 1, axis=1)
+ np.roll(vy, -1, axis=0) - np.roll(vy, 1, axis=0))
d... | [
"Project",
"the",
"velocity",
"field",
"to",
"be",
"approximately",
"mass",
"-",
"conserving",
"using",
"a",
"few",
"iterations",
"of",
"Gauss",
"-",
"Seidel",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/fluidsim/wing.py#L21-L39 | [
"def",
"project",
"(",
"vx",
",",
"vy",
",",
"occlusion",
")",
":",
"p",
"=",
"np",
".",
"zeros",
"(",
"vx",
".",
"shape",
")",
"div",
"=",
"-",
"0.5",
"*",
"(",
"np",
".",
"roll",
"(",
"vx",
",",
"-",
"1",
",",
"axis",
"=",
"1",
")",
"-"... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | advect | Move field f according to x and y velocities (u and v)
using an implicit Euler integrator. | examples/fluidsim/wing.py | def advect(f, vx, vy):
"""Move field f according to x and y velocities (u and v)
using an implicit Euler integrator."""
rows, cols = f.shape
cell_xs, cell_ys = np.meshgrid(np.arange(cols), np.arange(rows))
center_xs = (cell_xs - vx).ravel()
center_ys = (cell_ys - vy).ravel()
# Compute in... | def advect(f, vx, vy):
"""Move field f according to x and y velocities (u and v)
using an implicit Euler integrator."""
rows, cols = f.shape
cell_xs, cell_ys = np.meshgrid(np.arange(cols), np.arange(rows))
center_xs = (cell_xs - vx).ravel()
center_ys = (cell_ys - vy).ravel()
# Compute in... | [
"Move",
"field",
"f",
"according",
"to",
"x",
"and",
"y",
"velocities",
"(",
"u",
"and",
"v",
")",
"using",
"an",
"implicit",
"Euler",
"integrator",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/fluidsim/wing.py#L41-L62 | [
"def",
"advect",
"(",
"f",
",",
"vx",
",",
"vy",
")",
":",
"rows",
",",
"cols",
"=",
"f",
".",
"shape",
"cell_xs",
",",
"cell_ys",
"=",
"np",
".",
"meshgrid",
"(",
"np",
".",
"arange",
"(",
"cols",
")",
",",
"np",
".",
"arange",
"(",
"rows",
... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | unflatten_optimizer | Takes an optimizer that operates on flat 1D numpy arrays and returns a
wrapped version that handles trees of nested containers (lists/tuples/dicts)
with arrays/scalars at the leaves. | autograd/misc/optimizers.py | def unflatten_optimizer(optimize):
"""Takes an optimizer that operates on flat 1D numpy arrays and returns a
wrapped version that handles trees of nested containers (lists/tuples/dicts)
with arrays/scalars at the leaves."""
@wraps(optimize)
def _optimize(grad, x0, callback=None, *args, **kwargs):
... | def unflatten_optimizer(optimize):
"""Takes an optimizer that operates on flat 1D numpy arrays and returns a
wrapped version that handles trees of nested containers (lists/tuples/dicts)
with arrays/scalars at the leaves."""
@wraps(optimize)
def _optimize(grad, x0, callback=None, *args, **kwargs):
... | [
"Takes",
"an",
"optimizer",
"that",
"operates",
"on",
"flat",
"1D",
"numpy",
"arrays",
"and",
"returns",
"a",
"wrapped",
"version",
"that",
"handles",
"trees",
"of",
"nested",
"containers",
"(",
"lists",
"/",
"tuples",
"/",
"dicts",
")",
"with",
"arrays",
... | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/misc/optimizers.py#L16-L30 | [
"def",
"unflatten_optimizer",
"(",
"optimize",
")",
":",
"@",
"wraps",
"(",
"optimize",
")",
"def",
"_optimize",
"(",
"grad",
",",
"x0",
",",
"callback",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"_x0",
",",
"unflatten",
"=",
... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | sgd | Stochastic gradient descent with momentum.
grad() must have signature grad(x, i), where i is the iteration number. | autograd/misc/optimizers.py | def sgd(grad, x, callback=None, num_iters=200, step_size=0.1, mass=0.9):
"""Stochastic gradient descent with momentum.
grad() must have signature grad(x, i), where i is the iteration number."""
velocity = np.zeros(len(x))
for i in range(num_iters):
g = grad(x, i)
if callback: callback(x,... | def sgd(grad, x, callback=None, num_iters=200, step_size=0.1, mass=0.9):
"""Stochastic gradient descent with momentum.
grad() must have signature grad(x, i), where i is the iteration number."""
velocity = np.zeros(len(x))
for i in range(num_iters):
g = grad(x, i)
if callback: callback(x,... | [
"Stochastic",
"gradient",
"descent",
"with",
"momentum",
".",
"grad",
"()",
"must",
"have",
"signature",
"grad",
"(",
"x",
"i",
")",
"where",
"i",
"is",
"the",
"iteration",
"number",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/misc/optimizers.py#L33-L42 | [
"def",
"sgd",
"(",
"grad",
",",
"x",
",",
"callback",
"=",
"None",
",",
"num_iters",
"=",
"200",
",",
"step_size",
"=",
"0.1",
",",
"mass",
"=",
"0.9",
")",
":",
"velocity",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"x",
")",
")",
"for",
"i",
... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | rmsprop | Root mean squared prop: See Adagrad paper for details. | autograd/misc/optimizers.py | def rmsprop(grad, x, callback=None, num_iters=100,
step_size=0.1, gamma=0.9, eps=10**-8):
"""Root mean squared prop: See Adagrad paper for details."""
avg_sq_grad = np.ones(len(x))
for i in range(num_iters):
g = grad(x, i)
if callback: callback(x, i, g)
avg_sq_grad = avg_... | def rmsprop(grad, x, callback=None, num_iters=100,
step_size=0.1, gamma=0.9, eps=10**-8):
"""Root mean squared prop: See Adagrad paper for details."""
avg_sq_grad = np.ones(len(x))
for i in range(num_iters):
g = grad(x, i)
if callback: callback(x, i, g)
avg_sq_grad = avg_... | [
"Root",
"mean",
"squared",
"prop",
":",
"See",
"Adagrad",
"paper",
"for",
"details",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/misc/optimizers.py#L45-L54 | [
"def",
"rmsprop",
"(",
"grad",
",",
"x",
",",
"callback",
"=",
"None",
",",
"num_iters",
"=",
"100",
",",
"step_size",
"=",
"0.1",
",",
"gamma",
"=",
"0.9",
",",
"eps",
"=",
"10",
"**",
"-",
"8",
")",
":",
"avg_sq_grad",
"=",
"np",
".",
"ones",
... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | adam | Adam as described in http://arxiv.org/pdf/1412.6980.pdf.
It's basically RMSprop with momentum and some correction terms. | autograd/misc/optimizers.py | def adam(grad, x, callback=None, num_iters=100,
step_size=0.001, b1=0.9, b2=0.999, eps=10**-8):
"""Adam as described in http://arxiv.org/pdf/1412.6980.pdf.
It's basically RMSprop with momentum and some correction terms."""
m = np.zeros(len(x))
v = np.zeros(len(x))
for i in range(num_iters):... | def adam(grad, x, callback=None, num_iters=100,
step_size=0.001, b1=0.9, b2=0.999, eps=10**-8):
"""Adam as described in http://arxiv.org/pdf/1412.6980.pdf.
It's basically RMSprop with momentum and some correction terms."""
m = np.zeros(len(x))
v = np.zeros(len(x))
for i in range(num_iters):... | [
"Adam",
"as",
"described",
"in",
"http",
":",
"//",
"arxiv",
".",
"org",
"/",
"pdf",
"/",
"1412",
".",
"6980",
".",
"pdf",
".",
"It",
"s",
"basically",
"RMSprop",
"with",
"momentum",
"and",
"some",
"correction",
"terms",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/misc/optimizers.py#L57-L71 | [
"def",
"adam",
"(",
"grad",
",",
"x",
",",
"callback",
"=",
"None",
",",
"num_iters",
"=",
"100",
",",
"step_size",
"=",
"0.001",
",",
"b1",
"=",
"0.9",
",",
"b2",
"=",
"0.999",
",",
"eps",
"=",
"10",
"**",
"-",
"8",
")",
":",
"m",
"=",
"np",... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | make_ica_funs | These functions implement independent component analysis.
The model is:
latents are drawn i.i.d. for each data point from a product of student-ts.
weights are the same across all datapoints.
each data = latents * weghts + noise. | examples/ica.py | def make_ica_funs(observed_dimension, latent_dimension):
"""These functions implement independent component analysis.
The model is:
latents are drawn i.i.d. for each data point from a product of student-ts.
weights are the same across all datapoints.
each data = latents * weghts + noise."""
de... | def make_ica_funs(observed_dimension, latent_dimension):
"""These functions implement independent component analysis.
The model is:
latents are drawn i.i.d. for each data point from a product of student-ts.
weights are the same across all datapoints.
each data = latents * weghts + noise."""
de... | [
"These",
"functions",
"implement",
"independent",
"component",
"analysis",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/ica.py#L13-L41 | [
"def",
"make_ica_funs",
"(",
"observed_dimension",
",",
"latent_dimension",
")",
":",
"def",
"sample",
"(",
"weights",
",",
"n_samples",
",",
"noise_std",
",",
"rs",
")",
":",
"latents",
"=",
"rs",
".",
"randn",
"(",
"latent_dimension",
",",
"n_samples",
")"... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | neural_net_predict | Implements a deep neural network for classification.
params is a list of (weights, bias) tuples.
inputs is an (N x D) matrix.
returns normalized class log-probabilities. | examples/neural_net.py | def neural_net_predict(params, inputs):
"""Implements a deep neural network for classification.
params is a list of (weights, bias) tuples.
inputs is an (N x D) matrix.
returns normalized class log-probabilities."""
for W, b in params:
outputs = np.dot(inputs, W) + b
inputs ... | def neural_net_predict(params, inputs):
"""Implements a deep neural network for classification.
params is a list of (weights, bias) tuples.
inputs is an (N x D) matrix.
returns normalized class log-probabilities."""
for W, b in params:
outputs = np.dot(inputs, W) + b
inputs ... | [
"Implements",
"a",
"deep",
"neural",
"network",
"for",
"classification",
".",
"params",
"is",
"a",
"list",
"of",
"(",
"weights",
"bias",
")",
"tuples",
".",
"inputs",
"is",
"an",
"(",
"N",
"x",
"D",
")",
"matrix",
".",
"returns",
"normalized",
"class",
... | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/neural_net.py#L20-L28 | [
"def",
"neural_net_predict",
"(",
"params",
",",
"inputs",
")",
":",
"for",
"W",
",",
"b",
"in",
"params",
":",
"outputs",
"=",
"np",
".",
"dot",
"(",
"inputs",
",",
"W",
")",
"+",
"b",
"inputs",
"=",
"np",
".",
"tanh",
"(",
"outputs",
")",
"retu... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | l2_norm | Computes l2 norm of params by flattening them into a vector. | examples/neural_net.py | def l2_norm(params):
"""Computes l2 norm of params by flattening them into a vector."""
flattened, _ = flatten(params)
return np.dot(flattened, flattened) | def l2_norm(params):
"""Computes l2 norm of params by flattening them into a vector."""
flattened, _ = flatten(params)
return np.dot(flattened, flattened) | [
"Computes",
"l2",
"norm",
"of",
"params",
"by",
"flattening",
"them",
"into",
"a",
"vector",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/neural_net.py#L30-L33 | [
"def",
"l2_norm",
"(",
"params",
")",
":",
"flattened",
",",
"_",
"=",
"flatten",
"(",
"params",
")",
"return",
"np",
".",
"dot",
"(",
"flattened",
",",
"flattened",
")"
] | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | make_nn_funs | These functions implement a standard multi-layer perceptron,
vectorized over both training examples and weight samples. | examples/bayesian_neural_net.py | def make_nn_funs(layer_sizes, L2_reg, noise_variance, nonlinearity=np.tanh):
"""These functions implement a standard multi-layer perceptron,
vectorized over both training examples and weight samples."""
shapes = list(zip(layer_sizes[:-1], layer_sizes[1:]))
num_weights = sum((m+1)*n for m, n in shapes)
... | def make_nn_funs(layer_sizes, L2_reg, noise_variance, nonlinearity=np.tanh):
"""These functions implement a standard multi-layer perceptron,
vectorized over both training examples and weight samples."""
shapes = list(zip(layer_sizes[:-1], layer_sizes[1:]))
num_weights = sum((m+1)*n for m, n in shapes)
... | [
"These",
"functions",
"implement",
"a",
"standard",
"multi",
"-",
"layer",
"perceptron",
"vectorized",
"over",
"both",
"training",
"examples",
"and",
"weight",
"samples",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/bayesian_neural_net.py#L12-L40 | [
"def",
"make_nn_funs",
"(",
"layer_sizes",
",",
"L2_reg",
",",
"noise_variance",
",",
"nonlinearity",
"=",
"np",
".",
"tanh",
")",
":",
"shapes",
"=",
"list",
"(",
"zip",
"(",
"layer_sizes",
"[",
":",
"-",
"1",
"]",
",",
"layer_sizes",
"[",
"1",
":",
... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | neural_net_predict | Params is a list of (weights, bias) tuples.
inputs is an (N x D) matrix. | examples/generative_adversarial_net.py | def neural_net_predict(params, inputs):
"""Params is a list of (weights, bias) tuples.
inputs is an (N x D) matrix."""
inpW, inpb = params[0]
inputs = relu(np.dot(inputs, inpW) + inpb)
for W, b in params[1:-1]:
outputs = batch_normalize(np.dot(inputs, W) + b)
inputs = relu(outputs... | def neural_net_predict(params, inputs):
"""Params is a list of (weights, bias) tuples.
inputs is an (N x D) matrix."""
inpW, inpb = params[0]
inputs = relu(np.dot(inputs, inpW) + inpb)
for W, b in params[1:-1]:
outputs = batch_normalize(np.dot(inputs, W) + b)
inputs = relu(outputs... | [
"Params",
"is",
"a",
"list",
"of",
"(",
"weights",
"bias",
")",
"tuples",
".",
"inputs",
"is",
"an",
"(",
"N",
"x",
"D",
")",
"matrix",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/generative_adversarial_net.py#L33-L43 | [
"def",
"neural_net_predict",
"(",
"params",
",",
"inputs",
")",
":",
"inpW",
",",
"inpb",
"=",
"params",
"[",
"0",
"]",
"inputs",
"=",
"relu",
"(",
"np",
".",
"dot",
"(",
"inputs",
",",
"inpW",
")",
"+",
"inpb",
")",
"for",
"W",
",",
"b",
"in",
... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | adam_minimax | Adam modified to do minimiax optimization, for instance to help with
training generative adversarial networks. | examples/generative_adversarial_net.py | def adam_minimax(grad_both, init_params_max, init_params_min, callback=None, num_iters=100,
step_size_max=0.001, step_size_min=0.001, b1=0.9, b2=0.999, eps=10**-8):
"""Adam modified to do minimiax optimization, for instance to help with
training generative adversarial networks."""
x_max, unflatten... | def adam_minimax(grad_both, init_params_max, init_params_min, callback=None, num_iters=100,
step_size_max=0.001, step_size_min=0.001, b1=0.9, b2=0.999, eps=10**-8):
"""Adam modified to do minimiax optimization, for instance to help with
training generative adversarial networks."""
x_max, unflatten... | [
"Adam",
"modified",
"to",
"do",
"minimiax",
"optimization",
"for",
"instance",
"to",
"help",
"with",
"training",
"generative",
"adversarial",
"networks",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/generative_adversarial_net.py#L59-L91 | [
"def",
"adam_minimax",
"(",
"grad_both",
",",
"init_params_max",
",",
"init_params_min",
",",
"callback",
"=",
"None",
",",
"num_iters",
"=",
"100",
",",
"step_size_max",
"=",
"0.001",
",",
"step_size_min",
"=",
"0.001",
",",
"b1",
"=",
"0.9",
",",
"b2",
"... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | elementwise_grad | Returns a function that computes the sum of each column of the Jacobian of
`fun`, in one pass. If the Jacobian is diagonal, then this is the diagonal
of the Jacobian. | autograd/differential_operators.py | def elementwise_grad(fun, x):
"""
Returns a function that computes the sum of each column of the Jacobian of
`fun`, in one pass. If the Jacobian is diagonal, then this is the diagonal
of the Jacobian.
"""
vjp, ans = _make_vjp(fun, x)
if vspace(ans).iscomplex:
raise TypeError("Element... | def elementwise_grad(fun, x):
"""
Returns a function that computes the sum of each column of the Jacobian of
`fun`, in one pass. If the Jacobian is diagonal, then this is the diagonal
of the Jacobian.
"""
vjp, ans = _make_vjp(fun, x)
if vspace(ans).iscomplex:
raise TypeError("Element... | [
"Returns",
"a",
"function",
"that",
"computes",
"the",
"sum",
"of",
"each",
"column",
"of",
"the",
"Jacobian",
"of",
"fun",
"in",
"one",
"pass",
".",
"If",
"the",
"Jacobian",
"is",
"diagonal",
"then",
"this",
"is",
"the",
"diagonal",
"of",
"the",
"Jacobi... | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L32-L41 | [
"def",
"elementwise_grad",
"(",
"fun",
",",
"x",
")",
":",
"vjp",
",",
"ans",
"=",
"_make_vjp",
"(",
"fun",
",",
"x",
")",
"if",
"vspace",
"(",
"ans",
")",
".",
"iscomplex",
":",
"raise",
"TypeError",
"(",
"\"Elementwise_grad only applies to real-output func... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | jacobian | Returns a function which computes the Jacobian of `fun` with respect to
positional argument number `argnum`, which must be a scalar or array. Unlike
`grad` it is not restricted to scalar-output functions, but also it cannot
take derivatives with respect to some argument types (like lists or dicts).
If t... | autograd/differential_operators.py | def jacobian(fun, x):
"""
Returns a function which computes the Jacobian of `fun` with respect to
positional argument number `argnum`, which must be a scalar or array. Unlike
`grad` it is not restricted to scalar-output functions, but also it cannot
take derivatives with respect to some argument typ... | def jacobian(fun, x):
"""
Returns a function which computes the Jacobian of `fun` with respect to
positional argument number `argnum`, which must be a scalar or array. Unlike
`grad` it is not restricted to scalar-output functions, but also it cannot
take derivatives with respect to some argument typ... | [
"Returns",
"a",
"function",
"which",
"computes",
"the",
"Jacobian",
"of",
"fun",
"with",
"respect",
"to",
"positional",
"argument",
"number",
"argnum",
"which",
"must",
"be",
"a",
"scalar",
"or",
"array",
".",
"Unlike",
"grad",
"it",
"is",
"not",
"restricted... | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L48-L61 | [
"def",
"jacobian",
"(",
"fun",
",",
"x",
")",
":",
"vjp",
",",
"ans",
"=",
"_make_vjp",
"(",
"fun",
",",
"x",
")",
"ans_vspace",
"=",
"vspace",
"(",
"ans",
")",
"jacobian_shape",
"=",
"ans_vspace",
".",
"shape",
"+",
"vspace",
"(",
"x",
")",
".",
... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | grad_named | Takes gradients with respect to a named argument.
Doesn't work on *args or **kwargs. | autograd/differential_operators.py | def grad_named(fun, argname):
'''Takes gradients with respect to a named argument.
Doesn't work on *args or **kwargs.'''
arg_index = getargspec(fun).args.index(argname)
return grad(fun, arg_index) | def grad_named(fun, argname):
'''Takes gradients with respect to a named argument.
Doesn't work on *args or **kwargs.'''
arg_index = getargspec(fun).args.index(argname)
return grad(fun, arg_index) | [
"Takes",
"gradients",
"with",
"respect",
"to",
"a",
"named",
"argument",
".",
"Doesn",
"t",
"work",
"on",
"*",
"args",
"or",
"**",
"kwargs",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L69-L73 | [
"def",
"grad_named",
"(",
"fun",
",",
"argname",
")",
":",
"arg_index",
"=",
"getargspec",
"(",
"fun",
")",
".",
"args",
".",
"index",
"(",
"argname",
")",
"return",
"grad",
"(",
"fun",
",",
"arg_index",
")"
] | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | hessian_tensor_product | Builds a function that returns the exact Hessian-tensor product.
The returned function has arguments (*args, tensor, **kwargs), and for
vectors takes roughly 4x as long to evaluate as the original function. | autograd/differential_operators.py | def hessian_tensor_product(fun, argnum=0):
"""Builds a function that returns the exact Hessian-tensor product.
The returned function has arguments (*args, tensor, **kwargs), and for
vectors takes roughly 4x as long to evaluate as the original function."""
fun_grad = grad(fun, argnum)
def vector_dot_... | def hessian_tensor_product(fun, argnum=0):
"""Builds a function that returns the exact Hessian-tensor product.
The returned function has arguments (*args, tensor, **kwargs), and for
vectors takes roughly 4x as long to evaluate as the original function."""
fun_grad = grad(fun, argnum)
def vector_dot_... | [
"Builds",
"a",
"function",
"that",
"returns",
"the",
"exact",
"Hessian",
"-",
"tensor",
"product",
".",
"The",
"returned",
"function",
"has",
"arguments",
"(",
"*",
"args",
"tensor",
"**",
"kwargs",
")",
"and",
"for",
"vectors",
"takes",
"roughly",
"4x",
"... | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L87-L95 | [
"def",
"hessian_tensor_product",
"(",
"fun",
",",
"argnum",
"=",
"0",
")",
":",
"fun_grad",
"=",
"grad",
"(",
"fun",
",",
"argnum",
")",
"def",
"vector_dot_grad",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
",",
"vector",
"=",
"args"... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | tensor_jacobian_product | Builds a function that returns the exact tensor-Jacobian product, that
is the Jacobian matrix left-multiplied by tensor. The returned function
has arguments (*args, tensor, **kwargs). | autograd/differential_operators.py | def tensor_jacobian_product(fun, argnum=0):
"""Builds a function that returns the exact tensor-Jacobian product, that
is the Jacobian matrix left-multiplied by tensor. The returned function
has arguments (*args, tensor, **kwargs)."""
def vector_dot_fun(*args, **kwargs):
args, vector = args[:-1],... | def tensor_jacobian_product(fun, argnum=0):
"""Builds a function that returns the exact tensor-Jacobian product, that
is the Jacobian matrix left-multiplied by tensor. The returned function
has arguments (*args, tensor, **kwargs)."""
def vector_dot_fun(*args, **kwargs):
args, vector = args[:-1],... | [
"Builds",
"a",
"function",
"that",
"returns",
"the",
"exact",
"tensor",
"-",
"Jacobian",
"product",
"that",
"is",
"the",
"Jacobian",
"matrix",
"left",
"-",
"multiplied",
"by",
"tensor",
".",
"The",
"returned",
"function",
"has",
"arguments",
"(",
"*",
"args"... | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L98-L105 | [
"def",
"tensor_jacobian_product",
"(",
"fun",
",",
"argnum",
"=",
"0",
")",
":",
"def",
"vector_dot_fun",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
",",
"vector",
"=",
"args",
"[",
":",
"-",
"1",
"]",
",",
"args",
"[",
"-",
"1"... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | make_jvp_reversemode | Builds a function for evaluating the Jacobian-vector product at a
point. Roughly 1.5x more FLOPs than forward-mode, plus memory requirements
that scale with the number of primitives applied in the evaluation of f, as
well as other overheads. See j-towns.github.io/2017/06/12/A-new-trick.html. | autograd/differential_operators.py | def make_jvp_reversemode(fun, x):
"""Builds a function for evaluating the Jacobian-vector product at a
point. Roughly 1.5x more FLOPs than forward-mode, plus memory requirements
that scale with the number of primitives applied in the evaluation of f, as
well as other overheads. See j-towns.github.io/201... | def make_jvp_reversemode(fun, x):
"""Builds a function for evaluating the Jacobian-vector product at a
point. Roughly 1.5x more FLOPs than forward-mode, plus memory requirements
that scale with the number of primitives applied in the evaluation of f, as
well as other overheads. See j-towns.github.io/201... | [
"Builds",
"a",
"function",
"for",
"evaluating",
"the",
"Jacobian",
"-",
"vector",
"product",
"at",
"a",
"point",
".",
"Roughly",
"1",
".",
"5x",
"more",
"FLOPs",
"than",
"forward",
"-",
"mode",
"plus",
"memory",
"requirements",
"that",
"scale",
"with",
"th... | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L109-L116 | [
"def",
"make_jvp_reversemode",
"(",
"fun",
",",
"x",
")",
":",
"vjp",
",",
"y",
"=",
"_make_vjp",
"(",
"fun",
",",
"x",
")",
"vjp_vjp",
",",
"_",
"=",
"_make_vjp",
"(",
"vjp",
",",
"vspace",
"(",
"y",
")",
".",
"zeros",
"(",
")",
")",
"return",
... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | make_ggnvp | Builds a function for evaluating generalized-Gauss-Newton-vector products
at a point. Slightly more expensive than mixed-mode. | autograd/differential_operators.py | def make_ggnvp(f, g=lambda x: 1./2*np.sum(x**2, axis=-1), f_argnum=0):
"""Builds a function for evaluating generalized-Gauss-Newton-vector products
at a point. Slightly more expensive than mixed-mode."""
@unary_to_nary
def _make_ggnvp(f, x):
f_vjp, f_x = _make_vjp(f, x)
g_hvp, grad_g_x =... | def make_ggnvp(f, g=lambda x: 1./2*np.sum(x**2, axis=-1), f_argnum=0):
"""Builds a function for evaluating generalized-Gauss-Newton-vector products
at a point. Slightly more expensive than mixed-mode."""
@unary_to_nary
def _make_ggnvp(f, x):
f_vjp, f_x = _make_vjp(f, x)
g_hvp, grad_g_x =... | [
"Builds",
"a",
"function",
"for",
"evaluating",
"generalized",
"-",
"Gauss",
"-",
"Newton",
"-",
"vector",
"products",
"at",
"a",
"point",
".",
"Slightly",
"more",
"expensive",
"than",
"mixed",
"-",
"mode",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L119-L129 | [
"def",
"make_ggnvp",
"(",
"f",
",",
"g",
"=",
"lambda",
"x",
":",
"1.",
"/",
"2",
"*",
"np",
".",
"sum",
"(",
"x",
"**",
"2",
",",
"axis",
"=",
"-",
"1",
")",
",",
"f_argnum",
"=",
"0",
")",
":",
"@",
"unary_to_nary",
"def",
"_make_ggnvp",
"(... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | value_and_grad | Returns a function that returns both value and gradient. Suitable for use
in scipy.optimize | autograd/differential_operators.py | def value_and_grad(fun, x):
"""Returns a function that returns both value and gradient. Suitable for use
in scipy.optimize"""
vjp, ans = _make_vjp(fun, x)
if not vspace(ans).size == 1:
raise TypeError("value_and_grad only applies to real scalar-output "
"functions. Try ja... | def value_and_grad(fun, x):
"""Returns a function that returns both value and gradient. Suitable for use
in scipy.optimize"""
vjp, ans = _make_vjp(fun, x)
if not vspace(ans).size == 1:
raise TypeError("value_and_grad only applies to real scalar-output "
"functions. Try ja... | [
"Returns",
"a",
"function",
"that",
"returns",
"both",
"value",
"and",
"gradient",
".",
"Suitable",
"for",
"use",
"in",
"scipy",
".",
"optimize"
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L132-L140 | [
"def",
"value_and_grad",
"(",
"fun",
",",
"x",
")",
":",
"vjp",
",",
"ans",
"=",
"_make_vjp",
"(",
"fun",
",",
"x",
")",
"if",
"not",
"vspace",
"(",
"ans",
")",
".",
"size",
"==",
"1",
":",
"raise",
"TypeError",
"(",
"\"value_and_grad only applies to r... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | grad_and_aux | Builds a function that returns the gradient of the first output and the
(unmodified) second output of a function that returns two outputs. | autograd/differential_operators.py | def grad_and_aux(fun, x):
"""Builds a function that returns the gradient of the first output and the
(unmodified) second output of a function that returns two outputs."""
vjp, (ans, aux) = _make_vjp(lambda x: atuple(fun(x)), x)
return vjp((vspace(ans).ones(), vspace(aux).zeros())), aux | def grad_and_aux(fun, x):
"""Builds a function that returns the gradient of the first output and the
(unmodified) second output of a function that returns two outputs."""
vjp, (ans, aux) = _make_vjp(lambda x: atuple(fun(x)), x)
return vjp((vspace(ans).ones(), vspace(aux).zeros())), aux | [
"Builds",
"a",
"function",
"that",
"returns",
"the",
"gradient",
"of",
"the",
"first",
"output",
"and",
"the",
"(",
"unmodified",
")",
"second",
"output",
"of",
"a",
"function",
"that",
"returns",
"two",
"outputs",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L143-L147 | [
"def",
"grad_and_aux",
"(",
"fun",
",",
"x",
")",
":",
"vjp",
",",
"(",
"ans",
",",
"aux",
")",
"=",
"_make_vjp",
"(",
"lambda",
"x",
":",
"atuple",
"(",
"fun",
"(",
"x",
")",
")",
",",
"x",
")",
"return",
"vjp",
"(",
"(",
"vspace",
"(",
"ans... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | multigrad_dict | Takes gradients wrt all arguments simultaneously, | autograd/differential_operators.py | def multigrad_dict(fun):
"Takes gradients wrt all arguments simultaneously,"
"returns a dict mapping 'argname' to 'gradval'"
import funcsigs
sig = funcsigs.signature(fun)
def select(preds, lst):
idx = lambda item: next(
(i for i, pred in enumerate(preds) if pred(item)), len(pre... | def multigrad_dict(fun):
"Takes gradients wrt all arguments simultaneously,"
"returns a dict mapping 'argname' to 'gradval'"
import funcsigs
sig = funcsigs.signature(fun)
def select(preds, lst):
idx = lambda item: next(
(i for i, pred in enumerate(preds) if pred(item)), len(pre... | [
"Takes",
"gradients",
"wrt",
"all",
"arguments",
"simultaneously"
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L149-L190 | [
"def",
"multigrad_dict",
"(",
"fun",
")",
":",
"\"returns a dict mapping 'argname' to 'gradval'\"",
"import",
"funcsigs",
"sig",
"=",
"funcsigs",
".",
"signature",
"(",
"fun",
")",
"def",
"select",
"(",
"preds",
",",
"lst",
")",
":",
"idx",
"=",
"lambda",
"ite... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | checkpoint | Returns a checkpointed version of `fun`, where intermediate values
computed during the forward pass of `fun` are discarded and then recomputed
for the backward pass. Useful to save memory, effectively trading off time
and memory. See e.g. arxiv.org/abs/1604.06174. | autograd/differential_operators.py | def checkpoint(fun):
"""Returns a checkpointed version of `fun`, where intermediate values
computed during the forward pass of `fun` are discarded and then recomputed
for the backward pass. Useful to save memory, effectively trading off time
and memory. See e.g. arxiv.org/abs/1604.06174.
"""
def... | def checkpoint(fun):
"""Returns a checkpointed version of `fun`, where intermediate values
computed during the forward pass of `fun` are discarded and then recomputed
for the backward pass. Useful to save memory, effectively trading off time
and memory. See e.g. arxiv.org/abs/1604.06174.
"""
def... | [
"Returns",
"a",
"checkpointed",
"version",
"of",
"fun",
"where",
"intermediate",
"values",
"computed",
"during",
"the",
"forward",
"pass",
"of",
"fun",
"are",
"discarded",
"and",
"then",
"recomputed",
"for",
"the",
"backward",
"pass",
".",
"Useful",
"to",
"sav... | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L192-L202 | [
"def",
"checkpoint",
"(",
"fun",
")",
":",
"def",
"wrapped_grad",
"(",
"argnum",
",",
"ans",
",",
"args",
",",
"kwargs",
")",
":",
"return",
"make_vjp",
"(",
"fun",
",",
"argnum",
")",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"[",
"0",
"]"... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | string_to_one_hot | Converts an ASCII string to a one-of-k encoding. | examples/rnn.py | def string_to_one_hot(string, maxchar):
"""Converts an ASCII string to a one-of-k encoding."""
ascii = np.array([ord(c) for c in string]).T
return np.array(ascii[:,None] == np.arange(maxchar)[None, :], dtype=int) | def string_to_one_hot(string, maxchar):
"""Converts an ASCII string to a one-of-k encoding."""
ascii = np.array([ord(c) for c in string]).T
return np.array(ascii[:,None] == np.arange(maxchar)[None, :], dtype=int) | [
"Converts",
"an",
"ASCII",
"string",
"to",
"a",
"one",
"-",
"of",
"-",
"k",
"encoding",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/rnn.py#L62-L65 | [
"def",
"string_to_one_hot",
"(",
"string",
",",
"maxchar",
")",
":",
"ascii",
"=",
"np",
".",
"array",
"(",
"[",
"ord",
"(",
"c",
")",
"for",
"c",
"in",
"string",
"]",
")",
".",
"T",
"return",
"np",
".",
"array",
"(",
"ascii",
"[",
":",
",",
"N... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | build_dataset | Loads a text file, and turns each line into an encoded sequence. | examples/rnn.py | def build_dataset(filename, sequence_length, alphabet_size, max_lines=-1):
"""Loads a text file, and turns each line into an encoded sequence."""
with open(filename) as f:
content = f.readlines()
content = content[:max_lines]
content = [line for line in content if len(line) > 2] # Remove blank... | def build_dataset(filename, sequence_length, alphabet_size, max_lines=-1):
"""Loads a text file, and turns each line into an encoded sequence."""
with open(filename) as f:
content = f.readlines()
content = content[:max_lines]
content = [line for line in content if len(line) > 2] # Remove blank... | [
"Loads",
"a",
"text",
"file",
"and",
"turns",
"each",
"line",
"into",
"an",
"encoded",
"sequence",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/rnn.py#L70-L80 | [
"def",
"build_dataset",
"(",
"filename",
",",
"sequence_length",
",",
"alphabet_size",
",",
"max_lines",
"=",
"-",
"1",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"content",
"=",
"f",
".",
"readlines",
"(",
")",
"content",
"=",
"co... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | init_nn_params | Build a list of (weights, biases) tuples, one for each layer. | examples/ode_net.py | def init_nn_params(scale, layer_sizes, rs=npr.RandomState(0)):
"""Build a list of (weights, biases) tuples, one for each layer."""
return [(rs.randn(insize, outsize) * scale, # weight matrix
rs.randn(outsize) * scale) # bias vector
for insize, outsize in zip(layer_sizes[:-1]... | def init_nn_params(scale, layer_sizes, rs=npr.RandomState(0)):
"""Build a list of (weights, biases) tuples, one for each layer."""
return [(rs.randn(insize, outsize) * scale, # weight matrix
rs.randn(outsize) * scale) # bias vector
for insize, outsize in zip(layer_sizes[:-1]... | [
"Build",
"a",
"list",
"of",
"(",
"weights",
"biases",
")",
"tuples",
"one",
"for",
"each",
"layer",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/ode_net.py#L32-L36 | [
"def",
"init_nn_params",
"(",
"scale",
",",
"layer_sizes",
",",
"rs",
"=",
"npr",
".",
"RandomState",
"(",
"0",
")",
")",
":",
"return",
"[",
"(",
"rs",
".",
"randn",
"(",
"insize",
",",
"outsize",
")",
"*",
"scale",
",",
"# weight matrix",
"rs",
"."... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | make_rfft_factors | make the compression factors and compute the normalization
for irfft and rfft. | autograd/numpy/fft.py | def make_rfft_factors(axes, resshape, facshape, normshape, norm):
""" make the compression factors and compute the normalization
for irfft and rfft.
"""
N = 1.0
for n in normshape: N = N * n
# inplace modification is fine because we produce a constant
# which doesn't go into autograd.
... | def make_rfft_factors(axes, resshape, facshape, normshape, norm):
""" make the compression factors and compute the normalization
for irfft and rfft.
"""
N = 1.0
for n in normshape: N = N * n
# inplace modification is fine because we produce a constant
# which doesn't go into autograd.
... | [
"make",
"the",
"compression",
"factors",
"and",
"compute",
"the",
"normalization",
"for",
"irfft",
"and",
"rfft",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/numpy/fft.py#L128-L149 | [
"def",
"make_rfft_factors",
"(",
"axes",
",",
"resshape",
",",
"facshape",
",",
"normshape",
",",
"norm",
")",
":",
"N",
"=",
"1.0",
"for",
"n",
"in",
"normshape",
":",
"N",
"=",
"N",
"*",
"n",
"# inplace modification is fine because we produce a constant",
"#... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | variational_lower_bound | Provides a stochastic estimate of the variational lower bound,
for any variational family and model density. | examples/mixture_variational_inference.py | def variational_lower_bound(params, t, logprob, sampler, log_density,
num_samples, rs):
"""Provides a stochastic estimate of the variational lower bound,
for any variational family and model density."""
samples = sampler(params, num_samples, rs)
log_qs = log_density(params... | def variational_lower_bound(params, t, logprob, sampler, log_density,
num_samples, rs):
"""Provides a stochastic estimate of the variational lower bound,
for any variational family and model density."""
samples = sampler(params, num_samples, rs)
log_qs = log_density(params... | [
"Provides",
"a",
"stochastic",
"estimate",
"of",
"the",
"variational",
"lower",
"bound",
"for",
"any",
"variational",
"family",
"and",
"model",
"density",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/mixture_variational_inference.py#L37-L46 | [
"def",
"variational_lower_bound",
"(",
"params",
",",
"t",
",",
"logprob",
",",
"sampler",
",",
"log_density",
",",
"num_samples",
",",
"rs",
")",
":",
"samples",
"=",
"sampler",
"(",
"params",
",",
"num_samples",
",",
"rs",
")",
"log_qs",
"=",
"log_densit... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | grad_eigh | Gradient for eigenvalues and vectors of a symmetric matrix. | autograd/numpy/linalg.py | def grad_eigh(ans, x, UPLO='L'):
"""Gradient for eigenvalues and vectors of a symmetric matrix."""
N = x.shape[-1]
w, v = ans # Eigenvalues, eigenvectors.
def vjp(g):
wg, vg = g # Gradient w.r.t. eigenvalues, eigenvectors.
w_repeated = anp.repeat(w[..., anp.newaxis]... | def grad_eigh(ans, x, UPLO='L'):
"""Gradient for eigenvalues and vectors of a symmetric matrix."""
N = x.shape[-1]
w, v = ans # Eigenvalues, eigenvectors.
def vjp(g):
wg, vg = g # Gradient w.r.t. eigenvalues, eigenvectors.
w_repeated = anp.repeat(w[..., anp.newaxis]... | [
"Gradient",
"for",
"eigenvalues",
"and",
"vectors",
"of",
"a",
"symmetric",
"matrix",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/numpy/linalg.py#L104-L114 | [
"def",
"grad_eigh",
"(",
"ans",
",",
"x",
",",
"UPLO",
"=",
"'L'",
")",
":",
"N",
"=",
"x",
".",
"shape",
"[",
"-",
"1",
"]",
"w",
",",
"v",
"=",
"ans",
"# Eigenvalues, eigenvectors.",
"def",
"vjp",
"(",
"g",
")",
":",
"wg",
",",
"vg",
"=",
"... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | black_box_variational_inference | Implements http://arxiv.org/abs/1401.0118, and uses the
local reparameterization trick from http://arxiv.org/abs/1506.02557 | examples/black_box_svi.py | def black_box_variational_inference(logprob, D, num_samples):
"""Implements http://arxiv.org/abs/1401.0118, and uses the
local reparameterization trick from http://arxiv.org/abs/1506.02557"""
def unpack_params(params):
# Variational dist is a diagonal Gaussian.
mean, log_std = params[:D], p... | def black_box_variational_inference(logprob, D, num_samples):
"""Implements http://arxiv.org/abs/1401.0118, and uses the
local reparameterization trick from http://arxiv.org/abs/1506.02557"""
def unpack_params(params):
# Variational dist is a diagonal Gaussian.
mean, log_std = params[:D], p... | [
"Implements",
"http",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1401",
".",
"0118",
"and",
"uses",
"the",
"local",
"reparameterization",
"trick",
"from",
"http",
":",
"//",
"arxiv",
".",
"org",
"/",
"abs",
"/",
"1506",
".",
"02557"
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/black_box_svi.py#L14-L36 | [
"def",
"black_box_variational_inference",
"(",
"logprob",
",",
"D",
",",
"num_samples",
")",
":",
"def",
"unpack_params",
"(",
"params",
")",
":",
"# Variational dist is a diagonal Gaussian.",
"mean",
",",
"log_std",
"=",
"params",
"[",
":",
"D",
"]",
",",
"para... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | repeat_to_match_shape | Returns the array g repeated along axis to fit vector space vs.
Also returns the number of repetitions of the array. | autograd/numpy/numpy_vjps.py | def repeat_to_match_shape(g, shape, dtype, axis, keepdims):
"""Returns the array g repeated along axis to fit vector space vs.
Also returns the number of repetitions of the array."""
if shape == ():
return g, 1
axis = list(axis) if isinstance(axis, tuple) else axis
new_shape = onp.array(sha... | def repeat_to_match_shape(g, shape, dtype, axis, keepdims):
"""Returns the array g repeated along axis to fit vector space vs.
Also returns the number of repetitions of the array."""
if shape == ():
return g, 1
axis = list(axis) if isinstance(axis, tuple) else axis
new_shape = onp.array(sha... | [
"Returns",
"the",
"array",
"g",
"repeated",
"along",
"axis",
"to",
"fit",
"vector",
"space",
"vs",
".",
"Also",
"returns",
"the",
"number",
"of",
"repetitions",
"of",
"the",
"array",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/numpy/numpy_vjps.py#L274-L285 | [
"def",
"repeat_to_match_shape",
"(",
"g",
",",
"shape",
",",
"dtype",
",",
"axis",
",",
"keepdims",
")",
":",
"if",
"shape",
"==",
"(",
")",
":",
"return",
"g",
",",
"1",
"axis",
"=",
"list",
"(",
"axis",
")",
"if",
"isinstance",
"(",
"axis",
",",
... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | plot_images | Images should be a (N_images x pixels) matrix. | examples/data.py | def plot_images(images, ax, ims_per_row=5, padding=5, digit_dimensions=(28, 28),
cmap=matplotlib.cm.binary, vmin=None, vmax=None):
"""Images should be a (N_images x pixels) matrix."""
N_images = images.shape[0]
N_rows = (N_images - 1) // ims_per_row + 1
pad_value = np.min(images.ravel())... | def plot_images(images, ax, ims_per_row=5, padding=5, digit_dimensions=(28, 28),
cmap=matplotlib.cm.binary, vmin=None, vmax=None):
"""Images should be a (N_images x pixels) matrix."""
N_images = images.shape[0]
N_rows = (N_images - 1) // ims_per_row + 1
pad_value = np.min(images.ravel())... | [
"Images",
"should",
"be",
"a",
"(",
"N_images",
"x",
"pixels",
")",
"matrix",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/data.py#L22-L41 | [
"def",
"plot_images",
"(",
"images",
",",
"ax",
",",
"ims_per_row",
"=",
"5",
",",
"padding",
"=",
"5",
",",
"digit_dimensions",
"=",
"(",
"28",
",",
"28",
")",
",",
"cmap",
"=",
"matplotlib",
".",
"cm",
".",
"binary",
",",
"vmin",
"=",
"None",
","... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | make_pinwheel | Based on code by Ryan P. Adams. | examples/data.py | def make_pinwheel(radial_std, tangential_std, num_classes, num_per_class, rate,
rs=npr.RandomState(0)):
"""Based on code by Ryan P. Adams."""
rads = np.linspace(0, 2*np.pi, num_classes, endpoint=False)
features = rs.randn(num_classes*num_per_class, 2) \
* np.array([radial_std, tan... | def make_pinwheel(radial_std, tangential_std, num_classes, num_per_class, rate,
rs=npr.RandomState(0)):
"""Based on code by Ryan P. Adams."""
rads = np.linspace(0, 2*np.pi, num_classes, endpoint=False)
features = rs.randn(num_classes*num_per_class, 2) \
* np.array([radial_std, tan... | [
"Based",
"on",
"code",
"by",
"Ryan",
"P",
".",
"Adams",
"."
] | HIPS/autograd | python | https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/data.py#L53-L67 | [
"def",
"make_pinwheel",
"(",
"radial_std",
",",
"tangential_std",
",",
"num_classes",
",",
"num_per_class",
",",
"rate",
",",
"rs",
"=",
"npr",
".",
"RandomState",
"(",
"0",
")",
")",
":",
"rads",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"2",
"*",
... | e3b525302529d7490769d5c0bcfc7457e24e3b3e |
train | shannon_entropy | Borrowed from http://blog.dkbza.org/2007/05/scanning-data-for-entropy-anomalies.html | truffleHog/truffleHog.py | def shannon_entropy(data, iterator):
"""
Borrowed from http://blog.dkbza.org/2007/05/scanning-data-for-entropy-anomalies.html
"""
if not data:
return 0
entropy = 0
for x in iterator:
p_x = float(data.count(x))/len(data)
if p_x > 0:
entropy += - p_x*math.log(p_... | def shannon_entropy(data, iterator):
"""
Borrowed from http://blog.dkbza.org/2007/05/scanning-data-for-entropy-anomalies.html
"""
if not data:
return 0
entropy = 0
for x in iterator:
p_x = float(data.count(x))/len(data)
if p_x > 0:
entropy += - p_x*math.log(p_... | [
"Borrowed",
"from",
"http",
":",
"//",
"blog",
".",
"dkbza",
".",
"org",
"/",
"2007",
"/",
"05",
"/",
"scanning",
"-",
"data",
"-",
"for",
"-",
"entropy",
"-",
"anomalies",
".",
"html"
] | dxa4481/truffleHog | python | https://github.com/dxa4481/truffleHog/blob/a4c69fa2f6b256bfe824ac82b96c77eb8c06b2d0/truffleHog/truffleHog.py#L85-L96 | [
"def",
"shannon_entropy",
"(",
"data",
",",
"iterator",
")",
":",
"if",
"not",
"data",
":",
"return",
"0",
"entropy",
"=",
"0",
"for",
"x",
"in",
"iterator",
":",
"p_x",
"=",
"float",
"(",
"data",
".",
"count",
"(",
"x",
")",
")",
"/",
"len",
"("... | a4c69fa2f6b256bfe824ac82b96c77eb8c06b2d0 |
train | srt_formatter | Serialize a list of subtitles according to the SRT format, with optional time padding. | autosub/formatters.py | def srt_formatter(subtitles, padding_before=0, padding_after=0):
"""
Serialize a list of subtitles according to the SRT format, with optional time padding.
"""
sub_rip_file = pysrt.SubRipFile()
for i, ((start, end), text) in enumerate(subtitles, start=1):
item = pysrt.SubRipItem()
it... | def srt_formatter(subtitles, padding_before=0, padding_after=0):
"""
Serialize a list of subtitles according to the SRT format, with optional time padding.
"""
sub_rip_file = pysrt.SubRipFile()
for i, ((start, end), text) in enumerate(subtitles, start=1):
item = pysrt.SubRipItem()
it... | [
"Serialize",
"a",
"list",
"of",
"subtitles",
"according",
"to",
"the",
"SRT",
"format",
"with",
"optional",
"time",
"padding",
"."
] | agermanidis/autosub | python | https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/formatters.py#L14-L26 | [
"def",
"srt_formatter",
"(",
"subtitles",
",",
"padding_before",
"=",
"0",
",",
"padding_after",
"=",
"0",
")",
":",
"sub_rip_file",
"=",
"pysrt",
".",
"SubRipFile",
"(",
")",
"for",
"i",
",",
"(",
"(",
"start",
",",
"end",
")",
",",
"text",
")",
"in... | d32389cb76e63ec6959111c3f989a72f36f726fe |
train | vtt_formatter | Serialize a list of subtitles according to the VTT format, with optional time padding. | autosub/formatters.py | def vtt_formatter(subtitles, padding_before=0, padding_after=0):
"""
Serialize a list of subtitles according to the VTT format, with optional time padding.
"""
text = srt_formatter(subtitles, padding_before, padding_after)
text = 'WEBVTT\n\n' + text.replace(',', '.')
return text | def vtt_formatter(subtitles, padding_before=0, padding_after=0):
"""
Serialize a list of subtitles according to the VTT format, with optional time padding.
"""
text = srt_formatter(subtitles, padding_before, padding_after)
text = 'WEBVTT\n\n' + text.replace(',', '.')
return text | [
"Serialize",
"a",
"list",
"of",
"subtitles",
"according",
"to",
"the",
"VTT",
"format",
"with",
"optional",
"time",
"padding",
"."
] | agermanidis/autosub | python | https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/formatters.py#L29-L35 | [
"def",
"vtt_formatter",
"(",
"subtitles",
",",
"padding_before",
"=",
"0",
",",
"padding_after",
"=",
"0",
")",
":",
"text",
"=",
"srt_formatter",
"(",
"subtitles",
",",
"padding_before",
",",
"padding_after",
")",
"text",
"=",
"'WEBVTT\\n\\n'",
"+",
"text",
... | d32389cb76e63ec6959111c3f989a72f36f726fe |
train | json_formatter | Serialize a list of subtitles as a JSON blob. | autosub/formatters.py | def json_formatter(subtitles):
"""
Serialize a list of subtitles as a JSON blob.
"""
subtitle_dicts = [
{
'start': start,
'end': end,
'content': text,
}
for ((start, end), text)
in subtitles
]
return json.dumps(subtitle_dicts) | def json_formatter(subtitles):
"""
Serialize a list of subtitles as a JSON blob.
"""
subtitle_dicts = [
{
'start': start,
'end': end,
'content': text,
}
for ((start, end), text)
in subtitles
]
return json.dumps(subtitle_dicts) | [
"Serialize",
"a",
"list",
"of",
"subtitles",
"as",
"a",
"JSON",
"blob",
"."
] | agermanidis/autosub | python | https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/formatters.py#L38-L51 | [
"def",
"json_formatter",
"(",
"subtitles",
")",
":",
"subtitle_dicts",
"=",
"[",
"{",
"'start'",
":",
"start",
",",
"'end'",
":",
"end",
",",
"'content'",
":",
"text",
",",
"}",
"for",
"(",
"(",
"start",
",",
"end",
")",
",",
"text",
")",
"in",
"su... | d32389cb76e63ec6959111c3f989a72f36f726fe |
train | percentile | Calculate the given percentile of arr. | autosub/__init__.py | def percentile(arr, percent):
"""
Calculate the given percentile of arr.
"""
arr = sorted(arr)
index = (len(arr) - 1) * percent
floor = math.floor(index)
ceil = math.ceil(index)
if floor == ceil:
return arr[int(index)]
low_value = arr[int(floor)] * (ceil - index)
high_val... | def percentile(arr, percent):
"""
Calculate the given percentile of arr.
"""
arr = sorted(arr)
index = (len(arr) - 1) * percent
floor = math.floor(index)
ceil = math.ceil(index)
if floor == ceil:
return arr[int(index)]
low_value = arr[int(floor)] * (ceil - index)
high_val... | [
"Calculate",
"the",
"given",
"percentile",
"of",
"arr",
"."
] | agermanidis/autosub | python | https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/__init__.py#L39-L51 | [
"def",
"percentile",
"(",
"arr",
",",
"percent",
")",
":",
"arr",
"=",
"sorted",
"(",
"arr",
")",
"index",
"=",
"(",
"len",
"(",
"arr",
")",
"-",
"1",
")",
"*",
"percent",
"floor",
"=",
"math",
".",
"floor",
"(",
"index",
")",
"ceil",
"=",
"mat... | d32389cb76e63ec6959111c3f989a72f36f726fe |
train | extract_audio | Extract audio from an input file to a temporary WAV file. | autosub/__init__.py | def extract_audio(filename, channels=1, rate=16000):
"""
Extract audio from an input file to a temporary WAV file.
"""
temp = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
if not os.path.isfile(filename):
print("The given file does not exist: {}".format(filename))
raise Ex... | def extract_audio(filename, channels=1, rate=16000):
"""
Extract audio from an input file to a temporary WAV file.
"""
temp = tempfile.NamedTemporaryFile(suffix='.wav', delete=False)
if not os.path.isfile(filename):
print("The given file does not exist: {}".format(filename))
raise Ex... | [
"Extract",
"audio",
"from",
"an",
"input",
"file",
"to",
"a",
"temporary",
"WAV",
"file",
"."
] | agermanidis/autosub | python | https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/__init__.py#L175-L191 | [
"def",
"extract_audio",
"(",
"filename",
",",
"channels",
"=",
"1",
",",
"rate",
"=",
"16000",
")",
":",
"temp",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"'.wav'",
",",
"delete",
"=",
"False",
")",
"if",
"not",
"os",
".",
"path",... | d32389cb76e63ec6959111c3f989a72f36f726fe |
train | find_speech_regions | Perform voice activity detection on a given audio file. | autosub/__init__.py | def find_speech_regions(filename, frame_width=4096, min_region_size=0.5, max_region_size=6): # pylint: disable=too-many-locals
"""
Perform voice activity detection on a given audio file.
"""
reader = wave.open(filename)
sample_width = reader.getsampwidth()
rate = reader.getframerate()
n_chan... | def find_speech_regions(filename, frame_width=4096, min_region_size=0.5, max_region_size=6): # pylint: disable=too-many-locals
"""
Perform voice activity detection on a given audio file.
"""
reader = wave.open(filename)
sample_width = reader.getsampwidth()
rate = reader.getframerate()
n_chan... | [
"Perform",
"voice",
"activity",
"detection",
"on",
"a",
"given",
"audio",
"file",
"."
] | agermanidis/autosub | python | https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/__init__.py#L194-L230 | [
"def",
"find_speech_regions",
"(",
"filename",
",",
"frame_width",
"=",
"4096",
",",
"min_region_size",
"=",
"0.5",
",",
"max_region_size",
"=",
"6",
")",
":",
"# pylint: disable=too-many-locals",
"reader",
"=",
"wave",
".",
"open",
"(",
"filename",
")",
"sample... | d32389cb76e63ec6959111c3f989a72f36f726fe |
train | generate_subtitles | Given an input audio/video file, generate subtitles in the specified language and format. | autosub/__init__.py | def generate_subtitles( # pylint: disable=too-many-locals,too-many-arguments
source_path,
output=None,
concurrency=DEFAULT_CONCURRENCY,
src_language=DEFAULT_SRC_LANGUAGE,
dst_language=DEFAULT_DST_LANGUAGE,
subtitle_file_format=DEFAULT_SUBTITLE_FORMAT,
api_key=None... | def generate_subtitles( # pylint: disable=too-many-locals,too-many-arguments
source_path,
output=None,
concurrency=DEFAULT_CONCURRENCY,
src_language=DEFAULT_SRC_LANGUAGE,
dst_language=DEFAULT_DST_LANGUAGE,
subtitle_file_format=DEFAULT_SUBTITLE_FORMAT,
api_key=None... | [
"Given",
"an",
"input",
"audio",
"/",
"video",
"file",
"generate",
"subtitles",
"in",
"the",
"specified",
"language",
"and",
"format",
"."
] | agermanidis/autosub | python | https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/__init__.py#L233-L318 | [
"def",
"generate_subtitles",
"(",
"# pylint: disable=too-many-locals,too-many-arguments",
"source_path",
",",
"output",
"=",
"None",
",",
"concurrency",
"=",
"DEFAULT_CONCURRENCY",
",",
"src_language",
"=",
"DEFAULT_SRC_LANGUAGE",
",",
"dst_language",
"=",
"DEFAULT_DST_LANGUA... | d32389cb76e63ec6959111c3f989a72f36f726fe |
train | validate | Check that the CLI arguments passed to autosub are valid. | autosub/__init__.py | def validate(args):
"""
Check that the CLI arguments passed to autosub are valid.
"""
if args.format not in FORMATTERS:
print(
"Subtitle format not supported. "
"Run with --list-formats to see all supported formats."
)
return False
if args.src_languag... | def validate(args):
"""
Check that the CLI arguments passed to autosub are valid.
"""
if args.format not in FORMATTERS:
print(
"Subtitle format not supported. "
"Run with --list-formats to see all supported formats."
)
return False
if args.src_languag... | [
"Check",
"that",
"the",
"CLI",
"arguments",
"passed",
"to",
"autosub",
"are",
"valid",
"."
] | agermanidis/autosub | python | https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/__init__.py#L321-L350 | [
"def",
"validate",
"(",
"args",
")",
":",
"if",
"args",
".",
"format",
"not",
"in",
"FORMATTERS",
":",
"print",
"(",
"\"Subtitle format not supported. \"",
"\"Run with --list-formats to see all supported formats.\"",
")",
"return",
"False",
"if",
"args",
".",
"src_lan... | d32389cb76e63ec6959111c3f989a72f36f726fe |
train | main | Run autosub as a command-line program. | autosub/__init__.py | def main():
"""
Run autosub as a command-line program.
"""
parser = argparse.ArgumentParser()
parser.add_argument('source_path', help="Path to the video or audio file to subtitle",
nargs='?')
parser.add_argument('-C', '--concurrency', help="Number of concurrent API reques... | def main():
"""
Run autosub as a command-line program.
"""
parser = argparse.ArgumentParser()
parser.add_argument('source_path', help="Path to the video or audio file to subtitle",
nargs='?')
parser.add_argument('-C', '--concurrency', help="Number of concurrent API reques... | [
"Run",
"autosub",
"as",
"a",
"command",
"-",
"line",
"program",
"."
] | agermanidis/autosub | python | https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/__init__.py#L353-L410 | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'source_path'",
",",
"help",
"=",
"\"Path to the video or audio file to subtitle\"",
",",
"nargs",
"=",
"'?'",
")",
"parser",
".",
"a... | d32389cb76e63ec6959111c3f989a72f36f726fe |
train | PylintLinter.lint | Plugin interface to pyls linter.
Args:
document: The document to be linted.
is_saved: Whether or not the file has been saved to disk.
flags: Additional flags to pass to pylint. Not exposed to
pyls_lint, but used for testing.
Returns:
A li... | pyls/plugins/pylint_lint.py | def lint(cls, document, is_saved, flags=''):
"""Plugin interface to pyls linter.
Args:
document: The document to be linted.
is_saved: Whether or not the file has been saved to disk.
flags: Additional flags to pass to pylint. Not exposed to
pyls_lint, ... | def lint(cls, document, is_saved, flags=''):
"""Plugin interface to pyls linter.
Args:
document: The document to be linted.
is_saved: Whether or not the file has been saved to disk.
flags: Additional flags to pass to pylint. Not exposed to
pyls_lint, ... | [
"Plugin",
"interface",
"to",
"pyls",
"linter",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/plugins/pylint_lint.py#L15-L131 | [
"def",
"lint",
"(",
"cls",
",",
"document",
",",
"is_saved",
",",
"flags",
"=",
"''",
")",
":",
"if",
"not",
"is_saved",
":",
"# Pylint can only be run on files that have been saved to disk.",
"# Rather than return nothing, return the previous list of",
"# diagnostics. If we ... | 96e08d85635382d17024c352306c4759f124195d |
train | _sort_text | Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item> | pyls/plugins/jedi_completion.py | def _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
# If its 'hidden', put it next last
prefix = 'z{}' if definition.name.startswith('_') else 'a{}'
return prefix.format(definition.name) | def _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
# If its 'hidden', put it next last
prefix = 'z{}' if definition.name.startswith('_') else 'a{}'
return prefix.format(definition.name) | [
"Ensure",
"builtins",
"appear",
"at",
"the",
"bottom",
".",
"Description",
"is",
"of",
"format",
"<type",
">",
":",
"<module",
">",
".",
"<item",
">"
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/plugins/jedi_completion.py#L95-L102 | [
"def",
"_sort_text",
"(",
"definition",
")",
":",
"# If its 'hidden', put it next last",
"prefix",
"=",
"'z{}'",
"if",
"definition",
".",
"name",
".",
"startswith",
"(",
"'_'",
")",
"else",
"'a{}'",
"return",
"prefix",
".",
"format",
"(",
"definition",
".",
"n... | 96e08d85635382d17024c352306c4759f124195d |
train | Config.settings | Settings are constructed from a few sources:
1. User settings, found in user's home directory
2. Plugin settings, reported by PyLS plugins
3. LSP settings, given to us from didChangeConfiguration
4. Project settings, found in config files in the current project.
... | pyls/config/config.py | def settings(self, document_path=None):
"""Settings are constructed from a few sources:
1. User settings, found in user's home directory
2. Plugin settings, reported by PyLS plugins
3. LSP settings, given to us from didChangeConfiguration
4. Project settings, fou... | def settings(self, document_path=None):
"""Settings are constructed from a few sources:
1. User settings, found in user's home directory
2. Plugin settings, reported by PyLS plugins
3. LSP settings, given to us from didChangeConfiguration
4. Project settings, fou... | [
"Settings",
"are",
"constructed",
"from",
"a",
"few",
"sources",
":"
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/config/config.py#L95-L133 | [
"def",
"settings",
"(",
"self",
",",
"document_path",
"=",
"None",
")",
":",
"settings",
"=",
"{",
"}",
"sources",
"=",
"self",
".",
"_settings",
".",
"get",
"(",
"'configurationSources'",
",",
"DEFAULT_CONFIG_SOURCES",
")",
"for",
"source_name",
"in",
"reve... | 96e08d85635382d17024c352306c4759f124195d |
train | Config.update | Recursively merge the given settings into the current settings. | pyls/config/config.py | def update(self, settings):
"""Recursively merge the given settings into the current settings."""
self.settings.cache_clear()
self._settings = settings
log.info("Updated settings to %s", self._settings)
self._update_disabled_plugins() | def update(self, settings):
"""Recursively merge the given settings into the current settings."""
self.settings.cache_clear()
self._settings = settings
log.info("Updated settings to %s", self._settings)
self._update_disabled_plugins() | [
"Recursively",
"merge",
"the",
"given",
"settings",
"into",
"the",
"current",
"settings",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/config/config.py#L142-L147 | [
"def",
"update",
"(",
"self",
",",
"settings",
")",
":",
"self",
".",
"settings",
".",
"cache_clear",
"(",
")",
"self",
".",
"_settings",
"=",
"settings",
"log",
".",
"info",
"(",
"\"Updated settings to %s\"",
",",
"self",
".",
"_settings",
")",
"self",
... | 96e08d85635382d17024c352306c4759f124195d |
train | Workspace.get_document | Return a managed document if-present, else create one pointing at disk.
See https://github.com/Microsoft/language-server-protocol/issues/177 | pyls/workspace.py | def get_document(self, doc_uri):
"""Return a managed document if-present, else create one pointing at disk.
See https://github.com/Microsoft/language-server-protocol/issues/177
"""
return self._docs.get(doc_uri) or self._create_document(doc_uri) | def get_document(self, doc_uri):
"""Return a managed document if-present, else create one pointing at disk.
See https://github.com/Microsoft/language-server-protocol/issues/177
"""
return self._docs.get(doc_uri) or self._create_document(doc_uri) | [
"Return",
"a",
"managed",
"document",
"if",
"-",
"present",
"else",
"create",
"one",
"pointing",
"at",
"disk",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/workspace.py#L63-L68 | [
"def",
"get_document",
"(",
"self",
",",
"doc_uri",
")",
":",
"return",
"self",
".",
"_docs",
".",
"get",
"(",
"doc_uri",
")",
"or",
"self",
".",
"_create_document",
"(",
"doc_uri",
")"
] | 96e08d85635382d17024c352306c4759f124195d |
train | Workspace.source_roots | Return the source roots for the given document. | pyls/workspace.py | def source_roots(self, document_path):
"""Return the source roots for the given document."""
files = _utils.find_parents(self._root_path, document_path, ['setup.py']) or []
return [os.path.dirname(setup_py) for setup_py in files] | def source_roots(self, document_path):
"""Return the source roots for the given document."""
files = _utils.find_parents(self._root_path, document_path, ['setup.py']) or []
return [os.path.dirname(setup_py) for setup_py in files] | [
"Return",
"the",
"source",
"roots",
"for",
"the",
"given",
"document",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/workspace.py#L89-L92 | [
"def",
"source_roots",
"(",
"self",
",",
"document_path",
")",
":",
"files",
"=",
"_utils",
".",
"find_parents",
"(",
"self",
".",
"_root_path",
",",
"document_path",
",",
"[",
"'setup.py'",
"]",
")",
"or",
"[",
"]",
"return",
"[",
"os",
".",
"path",
"... | 96e08d85635382d17024c352306c4759f124195d |
train | Document.apply_change | Apply a change to the document. | pyls/workspace.py | def apply_change(self, change):
"""Apply a change to the document."""
text = change['text']
change_range = change.get('range')
if not change_range:
# The whole file has changed
self._source = text
return
start_line = change_range['start']['li... | def apply_change(self, change):
"""Apply a change to the document."""
text = change['text']
change_range = change.get('range')
if not change_range:
# The whole file has changed
self._source = text
return
start_line = change_range['start']['li... | [
"Apply",
"a",
"change",
"to",
"the",
"document",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/workspace.py#L134-L175 | [
"def",
"apply_change",
"(",
"self",
",",
"change",
")",
":",
"text",
"=",
"change",
"[",
"'text'",
"]",
"change_range",
"=",
"change",
".",
"get",
"(",
"'range'",
")",
"if",
"not",
"change_range",
":",
"# The whole file has changed",
"self",
".",
"_source",
... | 96e08d85635382d17024c352306c4759f124195d |
train | Document.word_at_position | Get the word under the cursor returning the start and end positions. | pyls/workspace.py | def word_at_position(self, position):
"""Get the word under the cursor returning the start and end positions."""
if position['line'] >= len(self.lines):
return ''
line = self.lines[position['line']]
i = position['character']
# Split word in two
start = line[:... | def word_at_position(self, position):
"""Get the word under the cursor returning the start and end positions."""
if position['line'] >= len(self.lines):
return ''
line = self.lines[position['line']]
i = position['character']
# Split word in two
start = line[:... | [
"Get",
"the",
"word",
"under",
"the",
"cursor",
"returning",
"the",
"start",
"and",
"end",
"positions",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/workspace.py#L181-L197 | [
"def",
"word_at_position",
"(",
"self",
",",
"position",
")",
":",
"if",
"position",
"[",
"'line'",
"]",
">=",
"len",
"(",
"self",
".",
"lines",
")",
":",
"return",
"''",
"line",
"=",
"self",
".",
"lines",
"[",
"position",
"[",
"'line'",
"]",
"]",
... | 96e08d85635382d17024c352306c4759f124195d |
train | debounce | Debounce calls to this function until interval_s seconds have passed. | pyls/_utils.py | def debounce(interval_s, keyed_by=None):
"""Debounce calls to this function until interval_s seconds have passed."""
def wrapper(func):
timers = {}
lock = threading.Lock()
@functools.wraps(func)
def debounced(*args, **kwargs):
call_args = inspect.getcallargs(func, *a... | def debounce(interval_s, keyed_by=None):
"""Debounce calls to this function until interval_s seconds have passed."""
def wrapper(func):
timers = {}
lock = threading.Lock()
@functools.wraps(func)
def debounced(*args, **kwargs):
call_args = inspect.getcallargs(func, *a... | [
"Debounce",
"calls",
"to",
"this",
"function",
"until",
"interval_s",
"seconds",
"have",
"passed",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/_utils.py#L11-L36 | [
"def",
"debounce",
"(",
"interval_s",
",",
"keyed_by",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"timers",
"=",
"{",
"}",
"lock",
"=",
"threading",
".",
"Lock",
"(",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def"... | 96e08d85635382d17024c352306c4759f124195d |
train | find_parents | Find files matching the given names relative to the given path.
Args:
path (str): The file path to start searching up from.
names (List[str]): The file/directory names to look for.
root (str): The directory at which to stop recursing upwards.
Note:
The path MUST be within the r... | pyls/_utils.py | def find_parents(root, path, names):
"""Find files matching the given names relative to the given path.
Args:
path (str): The file path to start searching up from.
names (List[str]): The file/directory names to look for.
root (str): The directory at which to stop recursing upwards.
... | def find_parents(root, path, names):
"""Find files matching the given names relative to the given path.
Args:
path (str): The file path to start searching up from.
names (List[str]): The file/directory names to look for.
root (str): The directory at which to stop recursing upwards.
... | [
"Find",
"files",
"matching",
"the",
"given",
"names",
"relative",
"to",
"the",
"given",
"path",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/_utils.py#L39-L71 | [
"def",
"find_parents",
"(",
"root",
",",
"path",
",",
"names",
")",
":",
"if",
"not",
"root",
":",
"return",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"commonprefix",
"(",
"(",
"root",
",",
"path",
")",
")",
":",
"log",
".",
"warning",
"(",
... | 96e08d85635382d17024c352306c4759f124195d |
train | merge_dicts | Recursively merge dictionary b into dictionary a.
If override_nones is True, then | pyls/_utils.py | def merge_dicts(dict_a, dict_b):
"""Recursively merge dictionary b into dictionary a.
If override_nones is True, then
"""
def _merge_dicts_(a, b):
for key in set(a.keys()).union(b.keys()):
if key in a and key in b:
if isinstance(a[key], dict) and isinstance(b[key], d... | def merge_dicts(dict_a, dict_b):
"""Recursively merge dictionary b into dictionary a.
If override_nones is True, then
"""
def _merge_dicts_(a, b):
for key in set(a.keys()).union(b.keys()):
if key in a and key in b:
if isinstance(a[key], dict) and isinstance(b[key], d... | [
"Recursively",
"merge",
"dictionary",
"b",
"into",
"dictionary",
"a",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/_utils.py#L78-L96 | [
"def",
"merge_dicts",
"(",
"dict_a",
",",
"dict_b",
")",
":",
"def",
"_merge_dicts_",
"(",
"a",
",",
"b",
")",
":",
"for",
"key",
"in",
"set",
"(",
"a",
".",
"keys",
"(",
")",
")",
".",
"union",
"(",
"b",
".",
"keys",
"(",
")",
")",
":",
"if"... | 96e08d85635382d17024c352306c4759f124195d |
train | format_docstring | Python doc strings come in a number of formats, but LSP wants markdown.
Until we can find a fast enough way of discovering and parsing each format,
we can do a little better by at least preserving indentation. | pyls/_utils.py | def format_docstring(contents):
"""Python doc strings come in a number of formats, but LSP wants markdown.
Until we can find a fast enough way of discovering and parsing each format,
we can do a little better by at least preserving indentation.
"""
contents = contents.replace('\t', u'\u00A0' * 4)
... | def format_docstring(contents):
"""Python doc strings come in a number of formats, but LSP wants markdown.
Until we can find a fast enough way of discovering and parsing each format,
we can do a little better by at least preserving indentation.
"""
contents = contents.replace('\t', u'\u00A0' * 4)
... | [
"Python",
"doc",
"strings",
"come",
"in",
"a",
"number",
"of",
"formats",
"but",
"LSP",
"wants",
"markdown",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/_utils.py#L99-L108 | [
"def",
"format_docstring",
"(",
"contents",
")",
":",
"contents",
"=",
"contents",
".",
"replace",
"(",
"'\\t'",
",",
"u'\\u00A0'",
"*",
"4",
")",
"contents",
"=",
"contents",
".",
"replace",
"(",
"' '",
",",
"u'\\u00A0'",
"*",
"2",
")",
"contents",
"="... | 96e08d85635382d17024c352306c4759f124195d |
train | urlparse | Parse and decode the parts of a URI. | pyls/uris.py | def urlparse(uri):
"""Parse and decode the parts of a URI."""
scheme, netloc, path, params, query, fragment = parse.urlparse(uri)
return (
parse.unquote(scheme),
parse.unquote(netloc),
parse.unquote(path),
parse.unquote(params),
parse.unquote(query),
parse.unq... | def urlparse(uri):
"""Parse and decode the parts of a URI."""
scheme, netloc, path, params, query, fragment = parse.urlparse(uri)
return (
parse.unquote(scheme),
parse.unquote(netloc),
parse.unquote(path),
parse.unquote(params),
parse.unquote(query),
parse.unq... | [
"Parse",
"and",
"decode",
"the",
"parts",
"of",
"a",
"URI",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/uris.py#L13-L23 | [
"def",
"urlparse",
"(",
"uri",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
"=",
"parse",
".",
"urlparse",
"(",
"uri",
")",
"return",
"(",
"parse",
".",
"unquote",
"(",
"scheme",
")",
",",
"parse",
"... | 96e08d85635382d17024c352306c4759f124195d |
train | urlunparse | Unparse and encode parts of a URI. | pyls/uris.py | def urlunparse(parts):
"""Unparse and encode parts of a URI."""
scheme, netloc, path, params, query, fragment = parts
# Avoid encoding the windows drive letter colon
if RE_DRIVE_LETTER_PATH.match(path):
quoted_path = path[:3] + parse.quote(path[3:])
else:
quoted_path = parse.quote(p... | def urlunparse(parts):
"""Unparse and encode parts of a URI."""
scheme, netloc, path, params, query, fragment = parts
# Avoid encoding the windows drive letter colon
if RE_DRIVE_LETTER_PATH.match(path):
quoted_path = path[:3] + parse.quote(path[3:])
else:
quoted_path = parse.quote(p... | [
"Unparse",
"and",
"encode",
"parts",
"of",
"a",
"URI",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/uris.py#L26-L43 | [
"def",
"urlunparse",
"(",
"parts",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"params",
",",
"query",
",",
"fragment",
"=",
"parts",
"# Avoid encoding the windows drive letter colon",
"if",
"RE_DRIVE_LETTER_PATH",
".",
"match",
"(",
"path",
")",
":",
... | 96e08d85635382d17024c352306c4759f124195d |
train | to_fs_path | Returns the filesystem path of the given URI.
Will handle UNC paths and normalize windows drive letters to lower-case. Also
uses the platform specific path separator. Will *not* validate the path for
invalid characters and semantics. Will *not* look at the scheme of this URI. | pyls/uris.py | def to_fs_path(uri):
"""Returns the filesystem path of the given URI.
Will handle UNC paths and normalize windows drive letters to lower-case. Also
uses the platform specific path separator. Will *not* validate the path for
invalid characters and semantics. Will *not* look at the scheme of this URI.
... | def to_fs_path(uri):
"""Returns the filesystem path of the given URI.
Will handle UNC paths and normalize windows drive letters to lower-case. Also
uses the platform specific path separator. Will *not* validate the path for
invalid characters and semantics. Will *not* look at the scheme of this URI.
... | [
"Returns",
"the",
"filesystem",
"path",
"of",
"the",
"given",
"URI",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/uris.py#L46-L71 | [
"def",
"to_fs_path",
"(",
"uri",
")",
":",
"# scheme://netloc/path;parameters?query#fragment",
"scheme",
",",
"netloc",
",",
"path",
",",
"_params",
",",
"_query",
",",
"_fragment",
"=",
"urlparse",
"(",
"uri",
")",
"if",
"netloc",
"and",
"path",
"and",
"schem... | 96e08d85635382d17024c352306c4759f124195d |
train | from_fs_path | Returns a URI for the given filesystem path. | pyls/uris.py | def from_fs_path(path):
"""Returns a URI for the given filesystem path."""
scheme = 'file'
params, query, fragment = '', '', ''
path, netloc = _normalize_win_path(path)
return urlunparse((scheme, netloc, path, params, query, fragment)) | def from_fs_path(path):
"""Returns a URI for the given filesystem path."""
scheme = 'file'
params, query, fragment = '', '', ''
path, netloc = _normalize_win_path(path)
return urlunparse((scheme, netloc, path, params, query, fragment)) | [
"Returns",
"a",
"URI",
"for",
"the",
"given",
"filesystem",
"path",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/uris.py#L74-L79 | [
"def",
"from_fs_path",
"(",
"path",
")",
":",
"scheme",
"=",
"'file'",
"params",
",",
"query",
",",
"fragment",
"=",
"''",
",",
"''",
",",
"''",
"path",
",",
"netloc",
"=",
"_normalize_win_path",
"(",
"path",
")",
"return",
"urlunparse",
"(",
"(",
"sch... | 96e08d85635382d17024c352306c4759f124195d |
train | uri_with | Return a URI with the given part(s) replaced.
Parts are decoded / encoded. | pyls/uris.py | def uri_with(uri, scheme=None, netloc=None, path=None, params=None, query=None, fragment=None):
"""Return a URI with the given part(s) replaced.
Parts are decoded / encoded.
"""
old_scheme, old_netloc, old_path, old_params, old_query, old_fragment = urlparse(uri)
path, _netloc = _normalize_win_path... | def uri_with(uri, scheme=None, netloc=None, path=None, params=None, query=None, fragment=None):
"""Return a URI with the given part(s) replaced.
Parts are decoded / encoded.
"""
old_scheme, old_netloc, old_path, old_params, old_query, old_fragment = urlparse(uri)
path, _netloc = _normalize_win_path... | [
"Return",
"a",
"URI",
"with",
"the",
"given",
"part",
"(",
"s",
")",
"replaced",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/uris.py#L82-L96 | [
"def",
"uri_with",
"(",
"uri",
",",
"scheme",
"=",
"None",
",",
"netloc",
"=",
"None",
",",
"path",
"=",
"None",
",",
"params",
"=",
"None",
",",
"query",
"=",
"None",
",",
"fragment",
"=",
"None",
")",
":",
"old_scheme",
",",
"old_netloc",
",",
"o... | 96e08d85635382d17024c352306c4759f124195d |
train | PyflakesDiagnosticReport.flake | Get message like <filename>:<lineno>: <msg> | pyls/plugins/pyflakes_lint.py | def flake(self, message):
""" Get message like <filename>:<lineno>: <msg> """
err_range = {
'start': {'line': message.lineno - 1, 'character': message.col},
'end': {'line': message.lineno - 1, 'character': len(self.lines[message.lineno - 1])},
}
severity = lsp.Di... | def flake(self, message):
""" Get message like <filename>:<lineno>: <msg> """
err_range = {
'start': {'line': message.lineno - 1, 'character': message.col},
'end': {'line': message.lineno - 1, 'character': len(self.lines[message.lineno - 1])},
}
severity = lsp.Di... | [
"Get",
"message",
"like",
"<filename",
">",
":",
"<lineno",
">",
":",
"<msg",
">"
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/plugins/pyflakes_lint.py#L62-L80 | [
"def",
"flake",
"(",
"self",
",",
"message",
")",
":",
"err_range",
"=",
"{",
"'start'",
":",
"{",
"'line'",
":",
"message",
".",
"lineno",
"-",
"1",
",",
"'character'",
":",
"message",
".",
"col",
"}",
",",
"'end'",
":",
"{",
"'line'",
":",
"messa... | 96e08d85635382d17024c352306c4759f124195d |
train | PythonLanguageServer._hook | Calls hook_name and returns a list of results from all registered handlers | pyls/python_ls.py | def _hook(self, hook_name, doc_uri=None, **kwargs):
"""Calls hook_name and returns a list of results from all registered handlers"""
doc = self.workspace.get_document(doc_uri) if doc_uri else None
hook_handlers = self.config.plugin_manager.subset_hook_caller(hook_name, self.config.disabled_plugi... | def _hook(self, hook_name, doc_uri=None, **kwargs):
"""Calls hook_name and returns a list of results from all registered handlers"""
doc = self.workspace.get_document(doc_uri) if doc_uri else None
hook_handlers = self.config.plugin_manager.subset_hook_caller(hook_name, self.config.disabled_plugi... | [
"Calls",
"hook_name",
"and",
"returns",
"a",
"list",
"of",
"results",
"from",
"all",
"registered",
"handlers"
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/python_ls.py#L118-L122 | [
"def",
"_hook",
"(",
"self",
",",
"hook_name",
",",
"doc_uri",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"doc",
"=",
"self",
".",
"workspace",
".",
"get_document",
"(",
"doc_uri",
")",
"if",
"doc_uri",
"else",
"None",
"hook_handlers",
"=",
"self"... | 96e08d85635382d17024c352306c4759f124195d |
train | _sort_text | Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item> | pyls/plugins/rope_completion.py | def _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
if definition.name.startswith("_"):
# It's a 'hidden' func, put it next last
return 'z' + definition.name
elif definition.scope == 'builtin':
return 'y' ... | def _sort_text(definition):
""" Ensure builtins appear at the bottom.
Description is of format <type>: <module>.<item>
"""
if definition.name.startswith("_"):
# It's a 'hidden' func, put it next last
return 'z' + definition.name
elif definition.scope == 'builtin':
return 'y' ... | [
"Ensure",
"builtins",
"appear",
"at",
"the",
"bottom",
".",
"Description",
"is",
"of",
"format",
"<type",
">",
":",
"<module",
">",
".",
"<item",
">"
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/plugins/rope_completion.py#L58-L69 | [
"def",
"_sort_text",
"(",
"definition",
")",
":",
"if",
"definition",
".",
"name",
".",
"startswith",
"(",
"\"_\"",
")",
":",
"# It's a 'hidden' func, put it next last",
"return",
"'z'",
"+",
"definition",
".",
"name",
"elif",
"definition",
".",
"scope",
"==",
... | 96e08d85635382d17024c352306c4759f124195d |
train | _kind | Return the VSCode type | pyls/plugins/rope_completion.py | def _kind(d):
""" Return the VSCode type """
MAP = {
'none': lsp.CompletionItemKind.Value,
'type': lsp.CompletionItemKind.Class,
'tuple': lsp.CompletionItemKind.Class,
'dict': lsp.CompletionItemKind.Class,
'dictionary': lsp.CompletionItemKind.Class,
'function': ls... | def _kind(d):
""" Return the VSCode type """
MAP = {
'none': lsp.CompletionItemKind.Value,
'type': lsp.CompletionItemKind.Class,
'tuple': lsp.CompletionItemKind.Class,
'dict': lsp.CompletionItemKind.Class,
'dictionary': lsp.CompletionItemKind.Class,
'function': ls... | [
"Return",
"the",
"VSCode",
"type"
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/plugins/rope_completion.py#L72-L107 | [
"def",
"_kind",
"(",
"d",
")",
":",
"MAP",
"=",
"{",
"'none'",
":",
"lsp",
".",
"CompletionItemKind",
".",
"Value",
",",
"'type'",
":",
"lsp",
".",
"CompletionItemKind",
".",
"Class",
",",
"'tuple'",
":",
"lsp",
".",
"CompletionItemKind",
".",
"Class",
... | 96e08d85635382d17024c352306c4759f124195d |
train | _get_opt | Get an option from a configparser with the given type. | pyls/config/source.py | def _get_opt(config, key, option, opt_type):
"""Get an option from a configparser with the given type."""
for opt_key in [option, option.replace('-', '_')]:
if not config.has_option(key, opt_key):
continue
if opt_type == bool:
return config.getbool(key, opt_key)
... | def _get_opt(config, key, option, opt_type):
"""Get an option from a configparser with the given type."""
for opt_key in [option, option.replace('-', '_')]:
if not config.has_option(key, opt_key):
continue
if opt_type == bool:
return config.getbool(key, opt_key)
... | [
"Get",
"an",
"option",
"from",
"a",
"configparser",
"with",
"the",
"given",
"type",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/config/source.py#L48-L66 | [
"def",
"_get_opt",
"(",
"config",
",",
"key",
",",
"option",
",",
"opt_type",
")",
":",
"for",
"opt_key",
"in",
"[",
"option",
",",
"option",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"]",
":",
"if",
"not",
"config",
".",
"has_option",
"(",
"key... | 96e08d85635382d17024c352306c4759f124195d |
train | _set_opt | Set the value in the dictionary at the given path if the value is not None. | pyls/config/source.py | def _set_opt(config_dict, path, value):
"""Set the value in the dictionary at the given path if the value is not None."""
if value is None:
return
if '.' not in path:
config_dict[path] = value
return
key, rest = path.split(".", 1)
if key not in config_dict:
config_d... | def _set_opt(config_dict, path, value):
"""Set the value in the dictionary at the given path if the value is not None."""
if value is None:
return
if '.' not in path:
config_dict[path] = value
return
key, rest = path.split(".", 1)
if key not in config_dict:
config_d... | [
"Set",
"the",
"value",
"in",
"the",
"dictionary",
"at",
"the",
"given",
"path",
"if",
"the",
"value",
"is",
"not",
"None",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/config/source.py#L73-L86 | [
"def",
"_set_opt",
"(",
"config_dict",
",",
"path",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"if",
"'.'",
"not",
"in",
"path",
":",
"config_dict",
"[",
"path",
"]",
"=",
"value",
"return",
"key",
",",
"rest",
"=",
"path",
... | 96e08d85635382d17024c352306c4759f124195d |
train | ConfigSource.parse_config | Parse the config with the given options. | pyls/config/source.py | def parse_config(config, key, options):
"""Parse the config with the given options."""
conf = {}
for source, destination, opt_type in options:
opt_value = _get_opt(config, key, source, opt_type)
if opt_value is not None:
_set_opt(conf, destination, opt_val... | def parse_config(config, key, options):
"""Parse the config with the given options."""
conf = {}
for source, destination, opt_type in options:
opt_value = _get_opt(config, key, source, opt_type)
if opt_value is not None:
_set_opt(conf, destination, opt_val... | [
"Parse",
"the",
"config",
"with",
"the",
"given",
"options",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/config/source.py#L38-L45 | [
"def",
"parse_config",
"(",
"config",
",",
"key",
",",
"options",
")",
":",
"conf",
"=",
"{",
"}",
"for",
"source",
",",
"destination",
",",
"opt_type",
"in",
"options",
":",
"opt_value",
"=",
"_get_opt",
"(",
"config",
",",
"key",
",",
"source",
",",
... | 96e08d85635382d17024c352306c4759f124195d |
train | _binary_stdio | Construct binary stdio streams (not text mode).
This seems to be different for Window/Unix Python2/3, so going by:
https://stackoverflow.com/questions/2850893/reading-binary-data-from-stdin | pyls/__main__.py | def _binary_stdio():
"""Construct binary stdio streams (not text mode).
This seems to be different for Window/Unix Python2/3, so going by:
https://stackoverflow.com/questions/2850893/reading-binary-data-from-stdin
"""
PY3K = sys.version_info >= (3, 0)
if PY3K:
# pylint: disable=no-... | def _binary_stdio():
"""Construct binary stdio streams (not text mode).
This seems to be different for Window/Unix Python2/3, so going by:
https://stackoverflow.com/questions/2850893/reading-binary-data-from-stdin
"""
PY3K = sys.version_info >= (3, 0)
if PY3K:
# pylint: disable=no-... | [
"Construct",
"binary",
"stdio",
"streams",
"(",
"not",
"text",
"mode",
")",
"."
] | palantir/python-language-server | python | https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/__main__.py#L64-L87 | [
"def",
"_binary_stdio",
"(",
")",
":",
"PY3K",
"=",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
"if",
"PY3K",
":",
"# pylint: disable=no-member",
"stdin",
",",
"stdout",
"=",
"sys",
".",
"stdin",
".",
"buffer",
",",
"sys",
".",
"stdout",... | 96e08d85635382d17024c352306c4759f124195d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.