repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
mwouts/jupytext
jupytext/cell_to_text.py
LightScriptCellExporter.explicit_start_marker
def explicit_start_marker(self, source): """Does the python representation of this cell requires an explicit start of cell marker?""" if not self.use_cell_markers: return False if self.metadata: return True if self.cell_marker_start: start_code...
python
def explicit_start_marker(self, source): """Does the python representation of this cell requires an explicit start of cell marker?""" if not self.use_cell_markers: return False if self.metadata: return True if self.cell_marker_start: start_code...
[ "def", "explicit_start_marker", "(", "self", ",", "source", ")", ":", "if", "not", "self", ".", "use_cell_markers", ":", "return", "False", "if", "self", ".", "metadata", ":", "return", "True", "if", "self", ".", "cell_marker_start", ":", "start_code_re", "=...
Does the python representation of this cell requires an explicit start of cell marker?
[ "Does", "the", "python", "representation", "of", "this", "cell", "requires", "an", "explicit", "start", "of", "cell", "marker?" ]
eb7d6aee889f80ad779cfc53441c648f0db9246d
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_to_text.py#L257-L275
train
mwouts/jupytext
jupytext/cell_to_text.py
LightScriptCellExporter.remove_eoc_marker
def remove_eoc_marker(self, text, next_text): """Remove end of cell marker when next cell has an explicit start marker""" if self.cell_marker_start: return text if self.is_code() and text[-1] == self.comment + ' -': # remove end of cell marker when redundant with next ex...
python
def remove_eoc_marker(self, text, next_text): """Remove end of cell marker when next cell has an explicit start marker""" if self.cell_marker_start: return text if self.is_code() and text[-1] == self.comment + ' -': # remove end of cell marker when redundant with next ex...
[ "def", "remove_eoc_marker", "(", "self", ",", "text", ",", "next_text", ")", ":", "if", "self", ".", "cell_marker_start", ":", "return", "text", "if", "self", ".", "is_code", "(", ")", "and", "text", "[", "-", "1", "]", "==", "self", ".", "comment", ...
Remove end of cell marker when next cell has an explicit start marker
[ "Remove", "end", "of", "cell", "marker", "when", "next", "cell", "has", "an", "explicit", "start", "marker" ]
eb7d6aee889f80ad779cfc53441c648f0db9246d
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_to_text.py#L277-L300
train
mwouts/jupytext
jupytext/cell_to_text.py
LightScriptCellExporter.simplify_soc_marker
def simplify_soc_marker(self, text, prev_text): """Simplify start of cell marker when previous line is blank""" if self.cell_marker_start: return text if self.is_code() and text and text[0] == self.comment + ' + {}': if not prev_text or not prev_text[-1].strip(): ...
python
def simplify_soc_marker(self, text, prev_text): """Simplify start of cell marker when previous line is blank""" if self.cell_marker_start: return text if self.is_code() and text and text[0] == self.comment + ' + {}': if not prev_text or not prev_text[-1].strip(): ...
[ "def", "simplify_soc_marker", "(", "self", ",", "text", ",", "prev_text", ")", ":", "if", "self", ".", "cell_marker_start", ":", "return", "text", "if", "self", ".", "is_code", "(", ")", "and", "text", "and", "text", "[", "0", "]", "==", "self", ".", ...
Simplify start of cell marker when previous line is blank
[ "Simplify", "start", "of", "cell", "marker", "when", "previous", "line", "is", "blank" ]
eb7d6aee889f80ad779cfc53441c648f0db9246d
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_to_text.py#L302-L311
train
mwouts/jupytext
jupytext/cell_to_text.py
RScriptCellExporter.code_to_text
def code_to_text(self): """Return the text representation of a code cell""" active = is_active(self.ext, self.metadata) source = copy(self.source) escape_code_start(source, self.ext, self.language) if active: comment_magic(source, self.language, self.comment_magics) ...
python
def code_to_text(self): """Return the text representation of a code cell""" active = is_active(self.ext, self.metadata) source = copy(self.source) escape_code_start(source, self.ext, self.language) if active: comment_magic(source, self.language, self.comment_magics) ...
[ "def", "code_to_text", "(", "self", ")", ":", "active", "=", "is_active", "(", "self", ".", "ext", ",", "self", ".", "metadata", ")", "source", "=", "copy", "(", "self", ".", "source", ")", "escape_code_start", "(", "source", ",", "self", ".", "ext", ...
Return the text representation of a code cell
[ "Return", "the", "text", "representation", "of", "a", "code", "cell" ]
eb7d6aee889f80ad779cfc53441c648f0db9246d
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_to_text.py#L327-L346
train
mwouts/jupytext
jupytext/cell_to_text.py
DoublePercentCellExporter.cell_to_text
def cell_to_text(self): """Return the text representation for the cell""" if self.cell_type != 'code': self.metadata['cell_type'] = self.cell_type active = is_active('py', self.metadata) if self.language != self.default_language and 'active' not in self.metadata: ...
python
def cell_to_text(self): """Return the text representation for the cell""" if self.cell_type != 'code': self.metadata['cell_type'] = self.cell_type active = is_active('py', self.metadata) if self.language != self.default_language and 'active' not in self.metadata: ...
[ "def", "cell_to_text", "(", "self", ")", ":", "if", "self", ".", "cell_type", "!=", "'code'", ":", "self", ".", "metadata", "[", "'cell_type'", "]", "=", "self", ".", "cell_type", "active", "=", "is_active", "(", "'py'", ",", "self", ".", "metadata", "...
Return the text representation for the cell
[ "Return", "the", "text", "representation", "for", "the", "cell" ]
eb7d6aee889f80ad779cfc53441c648f0db9246d
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_to_text.py#L354-L378
train
mwouts/jupytext
jupytext/cell_to_text.py
SphinxGalleryCellExporter.cell_to_text
def cell_to_text(self): """Return the text representation for the cell""" if self.cell_type == 'code': source = copy(self.source) return comment_magic(source, self.language, self.comment_magics) if 'cell_marker' in self.metadata: cell_marker = self.metadata.p...
python
def cell_to_text(self): """Return the text representation for the cell""" if self.cell_type == 'code': source = copy(self.source) return comment_magic(source, self.language, self.comment_magics) if 'cell_marker' in self.metadata: cell_marker = self.metadata.p...
[ "def", "cell_to_text", "(", "self", ")", ":", "if", "self", ".", "cell_type", "==", "'code'", ":", "source", "=", "copy", "(", "self", ".", "source", ")", "return", "comment_magic", "(", "source", ",", "self", ".", "language", ",", "self", ".", "commen...
Return the text representation for the cell
[ "Return", "the", "text", "representation", "for", "the", "cell" ]
eb7d6aee889f80ad779cfc53441c648f0db9246d
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/cell_to_text.py#L406-L424
train
mwouts/jupytext
jupytext/pandoc.py
pandoc
def pandoc(args, filein=None, fileout=None): """Execute pandoc with the given arguments""" cmd = [u'pandoc'] if filein: cmd.append(filein) if fileout: cmd.append('-o') cmd.append(fileout) cmd.extend(args.split()) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) ...
python
def pandoc(args, filein=None, fileout=None): """Execute pandoc with the given arguments""" cmd = [u'pandoc'] if filein: cmd.append(filein) if fileout: cmd.append('-o') cmd.append(fileout) cmd.extend(args.split()) proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) ...
[ "def", "pandoc", "(", "args", ",", "filein", "=", "None", ",", "fileout", "=", "None", ")", ":", "cmd", "=", "[", "u'pandoc'", "]", "if", "filein", ":", "cmd", ".", "append", "(", "filein", ")", "if", "fileout", ":", "cmd", ".", "append", "(", "'...
Execute pandoc with the given arguments
[ "Execute", "pandoc", "with", "the", "given", "arguments" ]
eb7d6aee889f80ad779cfc53441c648f0db9246d
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/pandoc.py#L15-L32
train
mwouts/jupytext
jupytext/pandoc.py
pandoc_version
def pandoc_version(): """Pandoc's version number""" version = pandoc(u'--version').splitlines()[0].split()[1] if parse_version(version) < parse_version('2.7.2'): raise PandocError('Please install pandoc>=2.7.2 (found version {})'.format(version)) return version
python
def pandoc_version(): """Pandoc's version number""" version = pandoc(u'--version').splitlines()[0].split()[1] if parse_version(version) < parse_version('2.7.2'): raise PandocError('Please install pandoc>=2.7.2 (found version {})'.format(version)) return version
[ "def", "pandoc_version", "(", ")", ":", "version", "=", "pandoc", "(", "u'--version'", ")", ".", "splitlines", "(", ")", "[", "0", "]", ".", "split", "(", ")", "[", "1", "]", "if", "parse_version", "(", "version", ")", "<", "parse_version", "(", "'2....
Pandoc's version number
[ "Pandoc", "s", "version", "number" ]
eb7d6aee889f80ad779cfc53441c648f0db9246d
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/pandoc.py#L44-L50
train
mwouts/jupytext
jupytext/pandoc.py
md_to_notebook
def md_to_notebook(text): """Convert a Markdown text to a Jupyter notebook, using Pandoc""" tmp_file = tempfile.NamedTemporaryFile(delete=False) tmp_file.write(text.encode('utf-8')) tmp_file.close() pandoc(u'--from markdown --to ipynb -s --atx-headers --wrap=preserve --preserve-tabs', tmp_file.name...
python
def md_to_notebook(text): """Convert a Markdown text to a Jupyter notebook, using Pandoc""" tmp_file = tempfile.NamedTemporaryFile(delete=False) tmp_file.write(text.encode('utf-8')) tmp_file.close() pandoc(u'--from markdown --to ipynb -s --atx-headers --wrap=preserve --preserve-tabs', tmp_file.name...
[ "def", "md_to_notebook", "(", "text", ")", ":", "tmp_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", "tmp_file", ".", "write", "(", "text", ".", "encode", "(", "'utf-8'", ")", ")", "tmp_file", ".", "close", "(", ")", ...
Convert a Markdown text to a Jupyter notebook, using Pandoc
[ "Convert", "a", "Markdown", "text", "to", "a", "Jupyter", "notebook", "using", "Pandoc" ]
eb7d6aee889f80ad779cfc53441c648f0db9246d
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/pandoc.py#L53-L65
train
mwouts/jupytext
jupytext/pandoc.py
notebook_to_md
def notebook_to_md(notebook): """Convert a notebook to its Markdown representation, using Pandoc""" tmp_file = tempfile.NamedTemporaryFile(delete=False) tmp_file.write(ipynb_writes(notebook).encode('utf-8')) tmp_file.close() pandoc(u'--from ipynb --to markdown -s --atx-headers --wrap=preserve --pre...
python
def notebook_to_md(notebook): """Convert a notebook to its Markdown representation, using Pandoc""" tmp_file = tempfile.NamedTemporaryFile(delete=False) tmp_file.write(ipynb_writes(notebook).encode('utf-8')) tmp_file.close() pandoc(u'--from ipynb --to markdown -s --atx-headers --wrap=preserve --pre...
[ "def", "notebook_to_md", "(", "notebook", ")", ":", "tmp_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", "tmp_file", ".", "write", "(", "ipynb_writes", "(", "notebook", ")", ".", "encode", "(", "'utf-8'", ")", ")", "tmp...
Convert a notebook to its Markdown representation, using Pandoc
[ "Convert", "a", "notebook", "to", "its", "Markdown", "representation", "using", "Pandoc" ]
eb7d6aee889f80ad779cfc53441c648f0db9246d
https://github.com/mwouts/jupytext/blob/eb7d6aee889f80ad779cfc53441c648f0db9246d/jupytext/pandoc.py#L68-L80
train
facebook/watchman
python/pywatchman/pybser.py
_int_size
def _int_size(x): """Return the smallest size int that can store the value""" if -0x80 <= x <= 0x7F: return 1 elif -0x8000 <= x <= 0x7FFF: return 2 elif -0x80000000 <= x <= 0x7FFFFFFF: return 4 elif long(-0x8000000000000000) <= x <= long(0x7FFFFFFFFFFFFFFF): return 8 ...
python
def _int_size(x): """Return the smallest size int that can store the value""" if -0x80 <= x <= 0x7F: return 1 elif -0x8000 <= x <= 0x7FFF: return 2 elif -0x80000000 <= x <= 0x7FFFFFFF: return 4 elif long(-0x8000000000000000) <= x <= long(0x7FFFFFFFFFFFFFFF): return 8 ...
[ "def", "_int_size", "(", "x", ")", ":", "if", "-", "0x80", "<=", "x", "<=", "0x7F", ":", "return", "1", "elif", "-", "0x8000", "<=", "x", "<=", "0x7FFF", ":", "return", "2", "elif", "-", "0x80000000", "<=", "x", "<=", "0x7FFFFFFF", ":", "return", ...
Return the smallest size int that can store the value
[ "Return", "the", "smallest", "size", "int", "that", "can", "store", "the", "value" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/pybser.py#L75-L86
train
facebook/watchman
python/pywatchman/pybser.py
loads
def loads(buf, mutable=True, value_encoding=None, value_errors=None): """Deserialize a BSER-encoded blob. @param buf: The buffer to deserialize. @type buf: bytes @param mutable: Whether to return mutable results. @type mutable: bool @param value_encoding: Optional codec to use to decode value...
python
def loads(buf, mutable=True, value_encoding=None, value_errors=None): """Deserialize a BSER-encoded blob. @param buf: The buffer to deserialize. @type buf: bytes @param mutable: Whether to return mutable results. @type mutable: bool @param value_encoding: Optional codec to use to decode value...
[ "def", "loads", "(", "buf", ",", "mutable", "=", "True", ",", "value_encoding", "=", "None", ",", "value_errors", "=", "None", ")", ":", "info", "=", "_pdu_info_helper", "(", "buf", ")", "expected_len", "=", "info", "[", "2", "]", "pos", "=", "info", ...
Deserialize a BSER-encoded blob. @param buf: The buffer to deserialize. @type buf: bytes @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 bytest...
[ "Deserialize", "a", "BSER", "-", "encoded", "blob", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/pybser.py#L498-L530
train
facebook/watchman
build/fbcode_builder/utils.py
run_command
def run_command(*cmd, **kwargs): 'The stdout of most fbcode_builder utilities is meant to be parsed.' logging.debug('Running: {0} with {1}'.format(cmd, kwargs)) kwargs['stdout'] = sys.stderr subprocess.check_call(cmd, **kwargs)
python
def run_command(*cmd, **kwargs): 'The stdout of most fbcode_builder utilities is meant to be parsed.' logging.debug('Running: {0} with {1}'.format(cmd, kwargs)) kwargs['stdout'] = sys.stderr subprocess.check_call(cmd, **kwargs)
[ "def", "run_command", "(", "*", "cmd", ",", "*", "*", "kwargs", ")", ":", "logging", ".", "debug", "(", "'Running: {0} with {1}'", ".", "format", "(", "cmd", ",", "kwargs", ")", ")", "kwargs", "[", "'stdout'", "]", "=", "sys", ".", "stderr", "subproces...
The stdout of most fbcode_builder utilities is meant to be parsed.
[ "The", "stdout", "of", "most", "fbcode_builder", "utilities", "is", "meant", "to", "be", "parsed", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/utils.py#L26-L30
train
facebook/watchman
build/fbcode_builder/utils.py
_inner_read_config
def _inner_read_config(path): ''' Helper to read a named config file. The grossness with the global is a workaround for this python bug: https://bugs.python.org/issue21591 The bug prevents us from defining either a local function or a lambda in the scope of read_fbcode_builder_config below. ...
python
def _inner_read_config(path): ''' Helper to read a named config file. The grossness with the global is a workaround for this python bug: https://bugs.python.org/issue21591 The bug prevents us from defining either a local function or a lambda in the scope of read_fbcode_builder_config below. ...
[ "def", "_inner_read_config", "(", "path", ")", ":", "global", "_project_dir", "full_path", "=", "os", ".", "path", ".", "join", "(", "_project_dir", ",", "path", ")", "return", "read_fbcode_builder_config", "(", "full_path", ")" ]
Helper to read a named config file. The grossness with the global is a workaround for this python bug: https://bugs.python.org/issue21591 The bug prevents us from defining either a local function or a lambda in the scope of read_fbcode_builder_config below.
[ "Helper", "to", "read", "a", "named", "config", "file", ".", "The", "grossness", "with", "the", "global", "is", "a", "workaround", "for", "this", "python", "bug", ":", "https", ":", "//", "bugs", ".", "python", ".", "org", "/", "issue21591", "The", "bu...
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/utils.py#L42-L52
train
facebook/watchman
build/fbcode_builder/utils.py
steps_for_spec
def steps_for_spec(builder, spec, processed_modules=None): ''' Sets `builder` configuration, and returns all the builder steps necessary to build `spec` and its dependencies. Traverses the dependencies in depth-first order, honoring the sequencing in each 'depends_on' list. ''' if processed...
python
def steps_for_spec(builder, spec, processed_modules=None): ''' Sets `builder` configuration, and returns all the builder steps necessary to build `spec` and its dependencies. Traverses the dependencies in depth-first order, honoring the sequencing in each 'depends_on' list. ''' if processed...
[ "def", "steps_for_spec", "(", "builder", ",", "spec", ",", "processed_modules", "=", "None", ")", ":", "if", "processed_modules", "is", "None", ":", "processed_modules", "=", "set", "(", ")", "steps", "=", "[", "]", "for", "module", "in", "spec", ".", "g...
Sets `builder` configuration, and returns all the builder steps necessary to build `spec` and its dependencies. Traverses the dependencies in depth-first order, honoring the sequencing in each 'depends_on' list.
[ "Sets", "builder", "configuration", "and", "returns", "all", "the", "builder", "steps", "necessary", "to", "build", "spec", "and", "its", "dependencies", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/utils.py#L70-L90
train
facebook/watchman
getdeps.py
vcpkg_dir
def vcpkg_dir(): """ Figure out where vcpkg is installed. vcpkg-exported is populated in some flavors of FB internal builds. C:/tools/vcpkg is the appveyor location. C:/open/vcpkg is my local location. """ for p in ["vcpkg-exported", "C:/tools/vcpkg", "C:/open/vcpkg"]: if os.path.isdir(p...
python
def vcpkg_dir(): """ Figure out where vcpkg is installed. vcpkg-exported is populated in some flavors of FB internal builds. C:/tools/vcpkg is the appveyor location. C:/open/vcpkg is my local location. """ for p in ["vcpkg-exported", "C:/tools/vcpkg", "C:/open/vcpkg"]: if os.path.isdir(p...
[ "def", "vcpkg_dir", "(", ")", ":", "for", "p", "in", "[", "\"vcpkg-exported\"", ",", "\"C:/tools/vcpkg\"", ",", "\"C:/open/vcpkg\"", "]", ":", "if", "os", ".", "path", ".", "isdir", "(", "p", ")", ":", "return", "os", ".", "path", ".", "realpath", "(",...
Figure out where vcpkg is installed. vcpkg-exported is populated in some flavors of FB internal builds. C:/tools/vcpkg is the appveyor location. C:/open/vcpkg is my local location.
[ "Figure", "out", "where", "vcpkg", "is", "installed", ".", "vcpkg", "-", "exported", "is", "populated", "in", "some", "flavors", "of", "FB", "internal", "builds", ".", "C", ":", "/", "tools", "/", "vcpkg", "is", "the", "appveyor", "location", ".", "C", ...
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/getdeps.py#L285-L294
train
facebook/watchman
python/pywatchman/capabilities.py
synthesize
def synthesize(vers, opts): """ Synthesize a capability enabled version response This is a very limited emulation for relatively recent feature sets """ parsed_version = parse_version(vers["version"]) vers["capabilities"] = {} for name in opts["optional"]: vers["capabilities"][name] ...
python
def synthesize(vers, opts): """ Synthesize a capability enabled version response This is a very limited emulation for relatively recent feature sets """ parsed_version = parse_version(vers["version"]) vers["capabilities"] = {} for name in opts["optional"]: vers["capabilities"][name] ...
[ "def", "synthesize", "(", "vers", ",", "opts", ")", ":", "parsed_version", "=", "parse_version", "(", "vers", "[", "\"version\"", "]", ")", "vers", "[", "\"capabilities\"", "]", "=", "{", "}", "for", "name", "in", "opts", "[", "\"optional\"", "]", ":", ...
Synthesize a capability enabled version response This is a very limited emulation for relatively recent feature sets
[ "Synthesize", "a", "capability", "enabled", "version", "response", "This", "is", "a", "very", "limited", "emulation", "for", "relatively", "recent", "feature", "sets" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/capabilities.py#L59-L77
train
facebook/watchman
build/fbcode_builder/shell_quoting.py
shell_quote
def shell_quote(s): 'Quotes a string if it is not already quoted' return s if isinstance(s, ShellQuoted) \ else ShellQuoted("'" + str(s).replace("'", "'\\''") + "'")
python
def shell_quote(s): 'Quotes a string if it is not already quoted' return s if isinstance(s, ShellQuoted) \ else ShellQuoted("'" + str(s).replace("'", "'\\''") + "'")
[ "def", "shell_quote", "(", "s", ")", ":", "return", "s", "if", "isinstance", "(", "s", ",", "ShellQuoted", ")", "else", "ShellQuoted", "(", "\"'\"", "+", "str", "(", "s", ")", ".", "replace", "(", "\"'\"", ",", "\"'\\\\''\"", ")", "+", "\"'\"", ")" ]
Quotes a string if it is not already quoted
[ "Quotes", "a", "string", "if", "it", "is", "not", "already", "quoted" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/shell_quoting.py#L69-L72
train
facebook/watchman
build/fbcode_builder/shell_quoting.py
raw_shell
def raw_shell(s): 'Not a member of ShellQuoted so we get a useful error for raw strings' if isinstance(s, ShellQuoted): return s.do_not_use_raw_str raise RuntimeError('{0} should have been ShellQuoted'.format(s))
python
def raw_shell(s): 'Not a member of ShellQuoted so we get a useful error for raw strings' if isinstance(s, ShellQuoted): return s.do_not_use_raw_str raise RuntimeError('{0} should have been ShellQuoted'.format(s))
[ "def", "raw_shell", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "ShellQuoted", ")", ":", "return", "s", ".", "do_not_use_raw_str", "raise", "RuntimeError", "(", "'{0} should have been ShellQuoted'", ".", "format", "(", "s", ")", ")" ]
Not a member of ShellQuoted so we get a useful error for raw strings
[ "Not", "a", "member", "of", "ShellQuoted", "so", "we", "get", "a", "useful", "error", "for", "raw", "strings" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/shell_quoting.py#L75-L79
train
facebook/watchman
build/fbcode_builder/shell_quoting.py
shell_join
def shell_join(delim, it): 'Joins an iterable of ShellQuoted with a delimiter between each two' return ShellQuoted(delim.join(raw_shell(s) for s in it))
python
def shell_join(delim, it): 'Joins an iterable of ShellQuoted with a delimiter between each two' return ShellQuoted(delim.join(raw_shell(s) for s in it))
[ "def", "shell_join", "(", "delim", ",", "it", ")", ":", "return", "ShellQuoted", "(", "delim", ".", "join", "(", "raw_shell", "(", "s", ")", "for", "s", "in", "it", ")", ")" ]
Joins an iterable of ShellQuoted with a delimiter between each two
[ "Joins", "an", "iterable", "of", "ShellQuoted", "with", "a", "delimiter", "between", "each", "two" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/shell_quoting.py#L82-L84
train
facebook/watchman
build/fbcode_builder/shell_quoting.py
path_join
def path_join(*args): 'Joins ShellQuoted and raw pieces of paths to make a shell-quoted path' return ShellQuoted(os.path.join(*[ raw_shell(shell_quote(s)) for s in args ]))
python
def path_join(*args): 'Joins ShellQuoted and raw pieces of paths to make a shell-quoted path' return ShellQuoted(os.path.join(*[ raw_shell(shell_quote(s)) for s in args ]))
[ "def", "path_join", "(", "*", "args", ")", ":", "return", "ShellQuoted", "(", "os", ".", "path", ".", "join", "(", "*", "[", "raw_shell", "(", "shell_quote", "(", "s", ")", ")", "for", "s", "in", "args", "]", ")", ")" ]
Joins ShellQuoted and raw pieces of paths to make a shell-quoted path
[ "Joins", "ShellQuoted", "and", "raw", "pieces", "of", "paths", "to", "make", "a", "shell", "-", "quoted", "path" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/shell_quoting.py#L87-L91
train
facebook/watchman
build/fbcode_builder/shell_quoting.py
shell_comment
def shell_comment(c): 'Do not shell-escape raw strings in comments, but do handle line breaks.' return ShellQuoted('# {c}').format(c=ShellQuoted( (raw_shell(c) if isinstance(c, ShellQuoted) else c) .replace('\n', '\n# ') ))
python
def shell_comment(c): 'Do not shell-escape raw strings in comments, but do handle line breaks.' return ShellQuoted('# {c}').format(c=ShellQuoted( (raw_shell(c) if isinstance(c, ShellQuoted) else c) .replace('\n', '\n# ') ))
[ "def", "shell_comment", "(", "c", ")", ":", "return", "ShellQuoted", "(", "'# {c}'", ")", ".", "format", "(", "c", "=", "ShellQuoted", "(", "(", "raw_shell", "(", "c", ")", "if", "isinstance", "(", "c", ",", "ShellQuoted", ")", "else", "c", ")", ".",...
Do not shell-escape raw strings in comments, but do handle line breaks.
[ "Do", "not", "shell", "-", "escape", "raw", "strings", "in", "comments", "but", "do", "handle", "line", "breaks", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/shell_quoting.py#L94-L99
train
facebook/watchman
winbuild/copy-dyn-deps.py
State.resolve_dep
def resolve_dep(self, depname): """ Locate dep in the search path; if found, return its path. If not found in the search path, and the dep is not a system-provided dep, raise an error """ for d in self._search_path: name = os.path.join(d, depname) if self._mock: ...
python
def resolve_dep(self, depname): """ Locate dep in the search path; if found, return its path. If not found in the search path, and the dep is not a system-provided dep, raise an error """ for d in self._search_path: name = os.path.join(d, depname) if self._mock: ...
[ "def", "resolve_dep", "(", "self", ",", "depname", ")", ":", "for", "d", "in", "self", ".", "_search_path", ":", "name", "=", "os", ".", "path", ".", "join", "(", "d", ",", "depname", ")", "if", "self", ".", "_mock", ":", "return", "name", "if", ...
Locate dep in the search path; if found, return its path. If not found in the search path, and the dep is not a system-provided dep, raise an error
[ "Locate", "dep", "in", "the", "search", "path", ";", "if", "found", "return", "its", "path", ".", "If", "not", "found", "in", "the", "search", "path", "and", "the", "dep", "is", "not", "a", "system", "-", "provided", "dep", "raise", "an", "error" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/winbuild/copy-dyn-deps.py#L147-L166
train
facebook/watchman
winbuild/copy-dyn-deps.py
State.resolve_dep_from_path
def resolve_dep_from_path(self, depname): """ If we can find the dep in the PATH, then we consider it to be a system dependency that we should not bundle in the package """ if is_system_dep(depname): return True for d in self._path: name = os.path.join(d, depname...
python
def resolve_dep_from_path(self, depname): """ If we can find the dep in the PATH, then we consider it to be a system dependency that we should not bundle in the package """ if is_system_dep(depname): return True for d in self._path: name = os.path.join(d, depname...
[ "def", "resolve_dep_from_path", "(", "self", ",", "depname", ")", ":", "if", "is_system_dep", "(", "depname", ")", ":", "return", "True", "for", "d", "in", "self", ".", "_path", ":", "name", "=", "os", ".", "path", ".", "join", "(", "d", ",", "depnam...
If we can find the dep in the PATH, then we consider it to be a system dependency that we should not bundle in the package
[ "If", "we", "can", "find", "the", "dep", "in", "the", "PATH", "then", "we", "consider", "it", "to", "be", "a", "system", "dependency", "that", "we", "should", "not", "bundle", "in", "the", "package" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/winbuild/copy-dyn-deps.py#L168-L179
train
facebook/watchman
python/pywatchman_aio/__init__.py
AsyncBserCodec._loads
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, )
python
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", ")", ":", "return", "bser", ".", "loads", "(", "response", ",", "True", ",", "value_encoding", "=", "encoding", ".", "get_local_encoding", "(", ")", ",", "value_errors", "=", "encoding", ".", "default_local_erro...
Parse the BSER packet
[ "Parse", "the", "BSER", "packet" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L191-L198
train
facebook/watchman
python/pywatchman_aio/__init__.py
AIOClient.receive_bilateral_response
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
python
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", ")", ":", "self", ".", "_check_receive_loop", "(", ")", "resp", "=", "await", "self", ".", "bilateral_response_queue", ".", "get", "(", ")", "self", ".", "_check_error", "(", "resp", ")", "return", "...
Receive the response to a request made to the Watchman service.
[ "Receive", "the", "response", "to", "a", "request", "made", "to", "the", "Watchman", "service", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L240-L246
train
facebook/watchman
python/pywatchman_aio/__init__.py
AIOClient.query
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(...
python
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", ")", ":", "self", ".", "_check_receive_loop", "(", ")", "try", ":", "await", "self", ".", "connection", ".", "send", "(", "args", ")", "return", "await", "self", ".", "receive_bilateral_response", "...
Send a query to the Watchman service and return the response.
[ "Send", "a", "query", "to", "the", "Watchman", "service", "and", "return", "the", "response", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L248-L257
train
facebook/watchman
python/pywatchman_aio/__init__.py
AIOClient.capability_check
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...
python
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", ")", ":", "self", ".", "_check_receive_loop", "(", ")", "# If the returned response is an error, self.query will raise an error", "await", "self", ".", "query"...
Perform a server capability check.
[ "Perform", "a", "server", "capability", "check", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L259-L266
train
facebook/watchman
python/pywatchman_aio/__init__.py
AIOClient.get_subscription
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, ...
python
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", ")", ":", "self", ".", "_check_receive_loop", "(", ")", "self", ".", "_ensure_subscription_queue_exists", "(", "name", ",", "root", ")", "res", "=", "await", "self", ".", "sub_by_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, remove processing impacts both the unscoped and scoped sto...
[ "Retrieve", "the", "data", "associated", "with", "a", "named", "subscription" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L268-L282
train
facebook/watchman
python/pywatchman_aio/__init__.py
AIOClient.pop_log
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
python
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", ")", ":", "self", ".", "_check_receive_loop", "(", ")", "res", "=", "self", ".", "log_queue", ".", "get", "(", ")", "self", ".", "_check_error", "(", "res", ")", "return", "res" ]
Get one log from the log queue.
[ "Get", "one", "log", "from", "the", "log", "queue", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L284-L289
train
facebook/watchman
python/pywatchman_aio/__init__.py
AIOClient.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()
python
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", ")", ":", "self", ".", "_closed", "=", "True", "if", "self", ".", "receive_task", ":", "self", ".", "receive_task", ".", "cancel", "(", ")", "if", "self", ".", "connection", ":", "self", ".", "connection", ".", "close", "...
Close the underlying connection.
[ "Close", "the", "underlying", "connection", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L291-L297
train
facebook/watchman
python/pywatchman_aio/__init__.py
AIOClient.enable_receiving
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: ...
python
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", ")", ":", "self", ".", "receive_task", "=", "asyncio", ".", "ensure_future", "(", "self", ".", "_receive_loop", "(", ")", ",", "loop", "=", "loop", ")", "def", "do_if_done", "(", "fut", ...
Schedules the receive loop to run on the given loop.
[ "Schedules", "the", "receive", "loop", "to", "run", "on", "the", "given", "loop", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L299-L312
train
facebook/watchman
python/pywatchman_aio/__init__.py
AIOClient.from_socket
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...
python
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\"", ":", "if", "not", "sockname", ":", "sockname", "=", "await", "_resolve_sockname", "(", ")", "transport", ...
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.
[ "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", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L315-L330
train
facebook/watchman
python/pywatchman_aio/__init__.py
AIOClient._receive_loop
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...
python
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", ")", ":", "try", ":", "while", "True", ":", "response", "=", "await", "self", ".", "connection", ".", "receive", "(", ")", "if", "self", ".", "_is_unilateral", "(", "response", ")", ":", "await", "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 function only returns when a non-...
[ "Receive", "the", "response", "to", "a", "request", "made", "to", "the", "Watchman", "service", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman_aio/__init__.py#L332-L351
train
facebook/watchman
python/pywatchman/__init__.py
_win32_strerror
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, ...
python
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", ")", ":", "# 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...
expand a win32 error code into a human readable message
[ "expand", "a", "win32", "error", "code", "into", "a", "human", "readable", "message" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L211-L230
train
facebook/watchman
python/pywatchman/__init__.py
_get_overlapped_result_ex_impl
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...
python
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", ")", ":", "log", "(", "\"Preparing to wait for maximum %dms\"", ",", "millis", ")", "if", "millis", "!=", "0", ":", "waitReturnCode", "=", "WaitFor...
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...
[ "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...
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L397-L434
train
facebook/watchman
python/pywatchman/__init__.py
Transport.readLine
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...
python
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", ")", ":", "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", ")",...
read a line Maintains its own buffer, callers of the transport should not mix calls to readBytes and readLine.
[ "read", "a", "line", "Maintains", "its", "own", "buffer", "callers", "of", "the", "transport", "should", "not", "mix", "calls", "to", "readBytes", "and", "readLine", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L311-L333
train
facebook/watchman
python/pywatchman/__init__.py
WindowsNamedPipeTransport.readBytes
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...
python
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", ")", ":", "# try to satisfy the read from any buffered data", "if", "self", ".", "_iobuf", ":", "if", "size", ">=", "len", "(", "self", ".", "_iobuf", ")", ":", "res", "=", "self", ".", "_iobuf", "self", ".", ...
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
[ "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" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L496-L562
train
facebook/watchman
python/pywatchman/__init__.py
client._connect
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 ...
python
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", ")", ":", "if", "self", ".", "recvConn", ":", "if", "self", ".", "pid", "!=", "os", ".", "getpid", "(", ")", ":", "raise", "UseAfterFork", "(", "\"do not re-use a connection after fork; open a new client instead\"", ")", "return",...
establish transport connection
[ "establish", "transport", "connection" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L980-L1000
train
facebook/watchman
python/pywatchman/__init__.py
client.receive
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...
python
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", ")", ":", "self", ".", "_connect", "(", ")", "result", "=", "self", ".", "recvConn", ".", "receive", "(", ")", "if", "self", ".", "_hasprop", "(", "result", ",", "\"error\"", ")", ":", "raise", "CommandError", "(", "res...
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...
[ "receive", "the", "next", "PDU", "from", "the", "watchman", "service" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L1019-L1056
train
facebook/watchman
python/pywatchman/__init__.py
client.getLog
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
python
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", ")", ":", "res", "=", "self", ".", "logs", "if", "remove", ":", "self", ".", "logs", "=", "[", "]", "return", "res" ]
Retrieve buffered log data If remove is true the data will be removed from the buffer. Otherwise it will be left in the buffer
[ "Retrieve", "buffered", "log", "data" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L1067-L1076
train
facebook/watchman
python/pywatchman/__init__.py
client.getSubscription
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...
python
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", ")", ":", "if", "root", "is", "not", "None", ":", "root", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "normcase", ...
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...
[ "Retrieve", "the", "data", "associated", "with", "a", "named", "subscription" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L1078-L1111
train
facebook/watchman
python/pywatchman/__init__.py
client.query
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...
python
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", ")", ":", "log", "(", "\"calling client.query\"", ")", "self", ".", "_connect", "(", ")", "try", ":", "self", ".", "sendConn", ".", "send", "(", "args", ")", "res", "=", "self", ".", "receive", "(", ")...
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.
[ "Send", "a", "query", "to", "the", "watchman", "service", "and", "return", "the", "response" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L1113-L1143
train
facebook/watchman
python/pywatchman/__init__.py
client.capabilityCheck
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...
python
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", ")", ":", "res", "=", "self", ".", "query", "(", "\"version\"", ",", "{", "\"optional\"", ":", "optional", "or", "[", "]", ",", "\"required\"", ":", "req...
Perform a server capability check
[ "Perform", "a", "server", "capability", "check" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/__init__.py#L1145-L1158
train
facebook/watchman
python/pywatchman/load.py
_read_bytes
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 = ...
python
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", ")", ":", "# Do the first read without resizing the input buffer", "offset", "=", "0", "remaining", "=", "len", "(", "buf", ")", "while", "remaining", ">", "0", ":", "l", "=", "fp", ".", "readinto", "(", "(", "c...
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
[ "Read", "bytes", "from", "a", "file", "-", "like", "object" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/load.py#L44-L65
train
facebook/watchman
python/pywatchman/load.py
load
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. ...
python
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", ")", ":", "buf", "=", "ctypes", ".", "create_string_buffer", "(", "8192", ")", "SNIFF_BUFFER_SIZE", "=", "len", "(", "EMPTY_HEADER"...
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...
[ "Deserialize", "a", "BSER", "-", "encoded", "blob", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/python/pywatchman/load.py#L68-L107
train
facebook/watchman
build/fbcode_builder/make_docker_context.py
make_docker_context
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...
python
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", ")", ":", "if", "opts", "is", "None", ":", "opts", "=", "{", "}", "valid_versions", "=", "(", "(", "'ubuntu:16.04'", ...
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...
[ "Returns", "a", "path", "to", "the", "Docker", "context", "directory", ".", "See", "parse_args", ".", "py", "." ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/make_docker_context.py#L27-L164
train
facebook/watchman
build/fbcode_builder/fbcode_builder.py
FBCodeBuilder.diagnostics
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)...
python
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", ")", ":", "# 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...
Log some system diagnostics before/after setup for ease of debugging
[ "Log", "some", "system", "diagnostics", "before", "/", "after", "setup", "for", "ease", "of", "debugging" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/fbcode_builder.py#L151-L161
train
facebook/watchman
build/fbcode_builder/fbcode_builder.py
FBCodeBuilder.fb_github_project_workdir
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)
python
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'", ")", ":", "project", ",", "path", "=", "project_and_path", ".", "split", "(", "'/'", ",", "1", ")", "return", "self", ".", "github_project_workdir", ...
This helper lets Facebook-internal CI special-cases FB projects
[ "This", "helper", "lets", "Facebook", "-", "internal", "CI", "special", "-", "cases", "FB", "projects" ]
d416c249dd8f463dc69fc2691d0f890598c045a9
https://github.com/facebook/watchman/blob/d416c249dd8f463dc69fc2691d0f890598c045a9/build/fbcode_builder/fbcode_builder.py#L293-L296
train
HIPS/autograd
examples/gaussian_process.py
make_gp_funs
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...
python
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", ")", ":", "def", "unpack_kernel_params", "(", "params", ")", ":", "mean", "=", "params", "[", "0", "]", "cov_params", "=", "params", "[", "2", ":", "]", "noise_scale", "=", "np", ".", "exp", ...
Functions that perform Gaussian process regression. cov_func has signature (cov_params, x, x')
[ "Functions", "that", "perform", "Gaussian", "process", "regression", ".", "cov_func", "has", "signature", "(", "cov_params", "x", "x", ")" ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/gaussian_process.py#L13-L40
train
HIPS/autograd
autograd/core.py
def_linear
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))
python
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", ")", ":", "defjvp_argnum", "(", "fun", ",", "lambda", "argnum", ",", "g", ",", "ans", ",", "args", ",", "kwargs", ":", "fun", "(", "*", "subval", "(", "args", ",", "argnum", ",", "g", ")", ",", "*", "*", "kwargs",...
Flags that a function is linear wrt all args
[ "Flags", "that", "a", "function", "is", "linear", "wrt", "all", "args" ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/core.py#L151-L154
train
HIPS/autograd
examples/fluidsim/fluidsim.py
project
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(...
python
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", ")", ":", "p", "=", "np", ".", "zeros", "(", "vx", ".", "shape", ")", "h", "=", "1.0", "/", "vx", ".", "shape", "[", "0", "]", "div", "=", "-", "0.5", "*", "h", "*", "(", "np", ".", "roll", "(", "...
Project the velocity field to be approximately mass-conserving, using a few iterations of Gauss-Seidel.
[ "Project", "the", "velocity", "field", "to", "be", "approximately", "mass", "-", "conserving", "using", "a", "few", "iterations", "of", "Gauss", "-", "Seidel", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/fluidsim/fluidsim.py#L18-L32
train
HIPS/autograd
autograd/tracer.py
primitive
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: ...
python
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", "(", "f_raw", ")", "def", "f_wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "boxed_args", ",", "trace", ",", "node_constructor", "=", "find_top_boxed_args", "(", "args", ")", "if...
Wraps a function so that its gradient can be specified and its invocation can be recorded. For examples, see the docs.
[ "Wraps", "a", "function", "so", "that", "its", "gradient", "can", "be", "specified", "and", "its", "invocation", "can", "be", "recorded", ".", "For", "examples", "see", "the", "docs", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/tracer.py#L31-L51
train
HIPS/autograd
examples/define_gradient.py
logsumexp
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)))
python
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", ")", ":", "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
[ "Numerically", "stable", "log", "(", "sum", "(", "exp", "(", "x", ")))", "also", "defined", "in", "scipy", ".", "misc" ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/define_gradient.py#L19-L22
train
HIPS/autograd
examples/variational_autoencoder.py
init_net_params
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:])]
python
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", ")", ")", ":", "return", "[", "(", "scale", "*", "rs", ".", "randn", "(", "m", ",", "n", ")", ",", "# weight matrix", "scale", "*", "rs...
Build a (weights, biases) tuples for all layers.
[ "Build", "a", "(", "weights", "biases", ")", "tuples", "for", "all", "layers", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/variational_autoencoder.py#L34-L38
train
HIPS/autograd
examples/hmm_em.py
build_dataset
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...
python
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", ")", ":", "encodings", "=", "dict", "(", "list", "(", "map", "(", "reversed", ",", "enumerate", "(", "string", ".", "printable", ")", ")", ")", ")", "digitize", "=", "lambda", ...
Loads a text file, and turns each line into an encoded sequence.
[ "Loads", "a", "text", "file", "and", "turns", "each", "line", "into", "an", "encoded", "sequence", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/hmm_em.py#L57-L70
train
HIPS/autograd
examples/fluidsim/wing.py
project
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...
python
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", ")", ":", "p", "=", "np", ".", "zeros", "(", "vx", ".", "shape", ")", "div", "=", "-", "0.5", "*", "(", "np", ".", "roll", "(", "vx", ",", "-", "1", ",", "axis", "=", "1", ")", "-"...
Project the velocity field to be approximately mass-conserving, using a few iterations of Gauss-Seidel.
[ "Project", "the", "velocity", "field", "to", "be", "approximately", "mass", "-", "conserving", "using", "a", "few", "iterations", "of", "Gauss", "-", "Seidel", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/fluidsim/wing.py#L21-L39
train
HIPS/autograd
examples/fluidsim/wing.py
advect
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...
python
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", ")", ":", "rows", ",", "cols", "=", "f", ".", "shape", "cell_xs", ",", "cell_ys", "=", "np", ".", "meshgrid", "(", "np", ".", "arange", "(", "cols", ")", ",", "np", ".", "arange", "(", "rows", ...
Move field f according to x and y velocities (u and v) using an implicit Euler integrator.
[ "Move", "field", "f", "according", "to", "x", "and", "y", "velocities", "(", "u", "and", "v", ")", "using", "an", "implicit", "Euler", "integrator", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/fluidsim/wing.py#L41-L62
train
HIPS/autograd
autograd/misc/optimizers.py
unflatten_optimizer
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): ...
python
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", ")", ":", "@", "wraps", "(", "optimize", ")", "def", "_optimize", "(", "grad", ",", "x0", ",", "callback", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_x0", ",", "unflatten", "=", ...
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.
[ "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", ...
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/misc/optimizers.py#L16-L30
train
HIPS/autograd
autograd/misc/optimizers.py
sgd
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,...
python
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", ")", ":", "velocity", "=", "np", ".", "zeros", "(", "len", "(", "x", ")", ")", "for", "i", ...
Stochastic gradient descent with momentum. grad() must have signature grad(x, i), where i is the iteration number.
[ "Stochastic", "gradient", "descent", "with", "momentum", ".", "grad", "()", "must", "have", "signature", "grad", "(", "x", "i", ")", "where", "i", "is", "the", "iteration", "number", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/misc/optimizers.py#L33-L42
train
HIPS/autograd
autograd/misc/optimizers.py
rmsprop
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_...
python
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", ")", ":", "avg_sq_grad", "=", "np", ".", "ones", ...
Root mean squared prop: See Adagrad paper for details.
[ "Root", "mean", "squared", "prop", ":", "See", "Adagrad", "paper", "for", "details", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/misc/optimizers.py#L45-L54
train
HIPS/autograd
autograd/misc/optimizers.py
adam
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):...
python
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", ")", ":", "m", "=", "np",...
Adam as described in http://arxiv.org/pdf/1412.6980.pdf. It's basically RMSprop with momentum and some correction terms.
[ "Adam", "as", "described", "in", "http", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1412", ".", "6980", ".", "pdf", ".", "It", "s", "basically", "RMSprop", "with", "momentum", "and", "some", "correction", "terms", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/misc/optimizers.py#L57-L71
train
HIPS/autograd
examples/ica.py
make_ica_funs
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...
python
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", ")", ":", "def", "sample", "(", "weights", ",", "n_samples", ",", "noise_std", ",", "rs", ")", ":", "latents", "=", "rs", ".", "randn", "(", "latent_dimension", ",", "n_samples", ")"...
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.
[ "These", "functions", "implement", "independent", "component", "analysis", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/ica.py#L13-L41
train
HIPS/autograd
examples/neural_net.py
neural_net_predict
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 ...
python
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", ")", ":", "for", "W", ",", "b", "in", "params", ":", "outputs", "=", "np", ".", "dot", "(", "inputs", ",", "W", ")", "+", "b", "inputs", "=", "np", ".", "tanh", "(", "outputs", ")", "retu...
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.
[ "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", ...
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/neural_net.py#L20-L28
train
HIPS/autograd
examples/neural_net.py
l2_norm
def l2_norm(params): """Computes l2 norm of params by flattening them into a vector.""" flattened, _ = flatten(params) return np.dot(flattened, flattened)
python
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", ")", ":", "flattened", ",", "_", "=", "flatten", "(", "params", ")", "return", "np", ".", "dot", "(", "flattened", ",", "flattened", ")" ]
Computes l2 norm of params by flattening them into a vector.
[ "Computes", "l2", "norm", "of", "params", "by", "flattening", "them", "into", "a", "vector", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/neural_net.py#L30-L33
train
HIPS/autograd
examples/bayesian_neural_net.py
make_nn_funs
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) ...
python
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", ")", ":", "shapes", "=", "list", "(", "zip", "(", "layer_sizes", "[", ":", "-", "1", "]", ",", "layer_sizes", "[", "1", ":", ...
These functions implement a standard multi-layer perceptron, vectorized over both training examples and weight samples.
[ "These", "functions", "implement", "a", "standard", "multi", "-", "layer", "perceptron", "vectorized", "over", "both", "training", "examples", "and", "weight", "samples", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/bayesian_neural_net.py#L12-L40
train
HIPS/autograd
examples/generative_adversarial_net.py
neural_net_predict
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...
python
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", ")", ":", "inpW", ",", "inpb", "=", "params", "[", "0", "]", "inputs", "=", "relu", "(", "np", ".", "dot", "(", "inputs", ",", "inpW", ")", "+", "inpb", ")", "for", "W", ",", "b", "in", ...
Params is a list of (weights, bias) tuples. inputs is an (N x D) matrix.
[ "Params", "is", "a", "list", "of", "(", "weights", "bias", ")", "tuples", ".", "inputs", "is", "an", "(", "N", "x", "D", ")", "matrix", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/generative_adversarial_net.py#L33-L43
train
HIPS/autograd
examples/generative_adversarial_net.py
adam_minimax
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...
python
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", "...
Adam modified to do minimiax optimization, for instance to help with training generative adversarial networks.
[ "Adam", "modified", "to", "do", "minimiax", "optimization", "for", "instance", "to", "help", "with", "training", "generative", "adversarial", "networks", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/generative_adversarial_net.py#L59-L91
train
HIPS/autograd
autograd/differential_operators.py
elementwise_grad
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...
python
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", ")", ":", "vjp", ",", "ans", "=", "_make_vjp", "(", "fun", ",", "x", ")", "if", "vspace", "(", "ans", ")", ".", "iscomplex", ":", "raise", "TypeError", "(", "\"Elementwise_grad only applies to real-output func...
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.
[ "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...
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L32-L41
train
HIPS/autograd
autograd/differential_operators.py
jacobian
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...
python
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", ")", ":", "vjp", ",", "ans", "=", "_make_vjp", "(", "fun", ",", "x", ")", "ans_vspace", "=", "vspace", "(", "ans", ")", "jacobian_shape", "=", "ans_vspace", ".", "shape", "+", "vspace", "(", "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 types (like lists or dicts). If t...
[ "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...
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L48-L61
train
HIPS/autograd
autograd/differential_operators.py
grad_named
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)
python
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", ")", ":", "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.
[ "Takes", "gradients", "with", "respect", "to", "a", "named", "argument", ".", "Doesn", "t", "work", "on", "*", "args", "or", "**", "kwargs", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L69-L73
train
HIPS/autograd
autograd/differential_operators.py
hessian_tensor_product
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_...
python
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", ")", ":", "fun_grad", "=", "grad", "(", "fun", ",", "argnum", ")", "def", "vector_dot_grad", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", ",", "vector", "=", "args"...
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.
[ "Builds", "a", "function", "that", "returns", "the", "exact", "Hessian", "-", "tensor", "product", ".", "The", "returned", "function", "has", "arguments", "(", "*", "args", "tensor", "**", "kwargs", ")", "and", "for", "vectors", "takes", "roughly", "4x", "...
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L87-L95
train
HIPS/autograd
autograd/differential_operators.py
tensor_jacobian_product
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],...
python
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", ")", ":", "def", "vector_dot_fun", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", ",", "vector", "=", "args", "[", ":", "-", "1", "]", ",", "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, tensor, **kwargs).
[ "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"...
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L98-L105
train
HIPS/autograd
autograd/differential_operators.py
make_jvp_reversemode
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...
python
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", ")", ":", "vjp", ",", "y", "=", "_make_vjp", "(", "fun", ",", "x", ")", "vjp_vjp", ",", "_", "=", "_make_vjp", "(", "vjp", ",", "vspace", "(", "y", ")", ".", "zeros", "(", ")", ")", "return", ...
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.
[ "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...
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L109-L116
train
HIPS/autograd
autograd/differential_operators.py
make_ggnvp
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 =...
python
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", ")", ":", "@", "unary_to_nary", "def", "_make_ggnvp", "(...
Builds a function for evaluating generalized-Gauss-Newton-vector products at a point. Slightly more expensive than mixed-mode.
[ "Builds", "a", "function", "for", "evaluating", "generalized", "-", "Gauss", "-", "Newton", "-", "vector", "products", "at", "a", "point", ".", "Slightly", "more", "expensive", "than", "mixed", "-", "mode", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L119-L129
train
HIPS/autograd
autograd/differential_operators.py
value_and_grad
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...
python
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", ")", ":", "vjp", ",", "ans", "=", "_make_vjp", "(", "fun", ",", "x", ")", "if", "not", "vspace", "(", "ans", ")", ".", "size", "==", "1", ":", "raise", "TypeError", "(", "\"value_and_grad only applies to r...
Returns a function that returns both value and gradient. Suitable for use in scipy.optimize
[ "Returns", "a", "function", "that", "returns", "both", "value", "and", "gradient", ".", "Suitable", "for", "use", "in", "scipy", ".", "optimize" ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L132-L140
train
HIPS/autograd
autograd/differential_operators.py
grad_and_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
python
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", ")", ":", "vjp", ",", "(", "ans", ",", "aux", ")", "=", "_make_vjp", "(", "lambda", "x", ":", "atuple", "(", "fun", "(", "x", ")", ")", ",", "x", ")", "return", "vjp", "(", "(", "vspace", "(", "ans...
Builds a function that returns the gradient of the first output and the (unmodified) second output of a function that returns two outputs.
[ "Builds", "a", "function", "that", "returns", "the", "gradient", "of", "the", "first", "output", "and", "the", "(", "unmodified", ")", "second", "output", "of", "a", "function", "that", "returns", "two", "outputs", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L143-L147
train
HIPS/autograd
autograd/differential_operators.py
multigrad_dict
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...
python
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", ")", ":", "\"returns a dict mapping 'argname' to 'gradval'\"", "import", "funcsigs", "sig", "=", "funcsigs", ".", "signature", "(", "fun", ")", "def", "select", "(", "preds", ",", "lst", ")", ":", "idx", "=", "lambda", "ite...
Takes gradients wrt all arguments simultaneously,
[ "Takes", "gradients", "wrt", "all", "arguments", "simultaneously" ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L149-L190
train
HIPS/autograd
autograd/differential_operators.py
checkpoint
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...
python
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", ")", ":", "def", "wrapped_grad", "(", "argnum", ",", "ans", ",", "args", ",", "kwargs", ")", ":", "return", "make_vjp", "(", "fun", ",", "argnum", ")", "(", "*", "args", ",", "*", "*", "kwargs", ")", "[", "0", "]"...
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.
[ "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...
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/differential_operators.py#L192-L202
train
HIPS/autograd
examples/rnn.py
string_to_one_hot
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)
python
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", ")", ":", "ascii", "=", "np", ".", "array", "(", "[", "ord", "(", "c", ")", "for", "c", "in", "string", "]", ")", ".", "T", "return", "np", ".", "array", "(", "ascii", "[", ":", ",", "N...
Converts an ASCII string to a one-of-k encoding.
[ "Converts", "an", "ASCII", "string", "to", "a", "one", "-", "of", "-", "k", "encoding", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/rnn.py#L62-L65
train
HIPS/autograd
examples/rnn.py
build_dataset
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...
python
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", ")", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "content", "=", "f", ".", "readlines", "(", ")", "content", "=", "co...
Loads a text file, and turns each line into an encoded sequence.
[ "Loads", "a", "text", "file", "and", "turns", "each", "line", "into", "an", "encoded", "sequence", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/rnn.py#L70-L80
train
HIPS/autograd
examples/ode_net.py
init_nn_params
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]...
python
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", ")", ")", ":", "return", "[", "(", "rs", ".", "randn", "(", "insize", ",", "outsize", ")", "*", "scale", ",", "# weight matrix", "rs", "."...
Build a list of (weights, biases) tuples, one for each layer.
[ "Build", "a", "list", "of", "(", "weights", "biases", ")", "tuples", "one", "for", "each", "layer", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/ode_net.py#L32-L36
train
HIPS/autograd
autograd/numpy/fft.py
make_rfft_factors
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. ...
python
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", ")", ":", "N", "=", "1.0", "for", "n", "in", "normshape", ":", "N", "=", "N", "*", "n", "# inplace modification is fine because we produce a constant", "#...
make the compression factors and compute the normalization for irfft and rfft.
[ "make", "the", "compression", "factors", "and", "compute", "the", "normalization", "for", "irfft", "and", "rfft", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/numpy/fft.py#L128-L149
train
HIPS/autograd
examples/mixture_variational_inference.py
variational_lower_bound
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...
python
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", ")", ":", "samples", "=", "sampler", "(", "params", ",", "num_samples", ",", "rs", ")", "log_qs", "=", "log_densit...
Provides a stochastic estimate of the variational lower bound, for any variational family and model density.
[ "Provides", "a", "stochastic", "estimate", "of", "the", "variational", "lower", "bound", "for", "any", "variational", "family", "and", "model", "density", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/mixture_variational_inference.py#L37-L46
train
HIPS/autograd
autograd/numpy/linalg.py
grad_eigh
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]...
python
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'", ")", ":", "N", "=", "x", ".", "shape", "[", "-", "1", "]", "w", ",", "v", "=", "ans", "# Eigenvalues, eigenvectors.", "def", "vjp", "(", "g", ")", ":", "wg", ",", "vg", "=", "...
Gradient for eigenvalues and vectors of a symmetric matrix.
[ "Gradient", "for", "eigenvalues", "and", "vectors", "of", "a", "symmetric", "matrix", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/numpy/linalg.py#L104-L114
train
HIPS/autograd
examples/black_box_svi.py
black_box_variational_inference
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...
python
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", ")", ":", "def", "unpack_params", "(", "params", ")", ":", "# Variational dist is a diagonal Gaussian.", "mean", ",", "log_std", "=", "params", "[", ":", "D", "]", ",", "para...
Implements http://arxiv.org/abs/1401.0118, and uses the local reparameterization trick from http://arxiv.org/abs/1506.02557
[ "Implements", "http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1401", ".", "0118", "and", "uses", "the", "local", "reparameterization", "trick", "from", "http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1506", ".", "02557" ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/black_box_svi.py#L14-L36
train
HIPS/autograd
autograd/numpy/numpy_vjps.py
repeat_to_match_shape
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...
python
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", ")", ":", "if", "shape", "==", "(", ")", ":", "return", "g", ",", "1", "axis", "=", "list", "(", "axis", ")", "if", "isinstance", "(", "axis", ",", ...
Returns the array g repeated along axis to fit vector space vs. Also returns the number of repetitions of the array.
[ "Returns", "the", "array", "g", "repeated", "along", "axis", "to", "fit", "vector", "space", "vs", ".", "Also", "returns", "the", "number", "of", "repetitions", "of", "the", "array", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/autograd/numpy/numpy_vjps.py#L274-L285
train
HIPS/autograd
examples/data.py
plot_images
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())...
python
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", ","...
Images should be a (N_images x pixels) matrix.
[ "Images", "should", "be", "a", "(", "N_images", "x", "pixels", ")", "matrix", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/data.py#L22-L41
train
HIPS/autograd
examples/data.py
make_pinwheel
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...
python
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", ")", ")", ":", "rads", "=", "np", ".", "linspace", "(", "0", ",", "2", "*", ...
Based on code by Ryan P. Adams.
[ "Based", "on", "code", "by", "Ryan", "P", ".", "Adams", "." ]
e3b525302529d7490769d5c0bcfc7457e24e3b3e
https://github.com/HIPS/autograd/blob/e3b525302529d7490769d5c0bcfc7457e24e3b3e/examples/data.py#L53-L67
train
dxa4481/truffleHog
truffleHog/truffleHog.py
shannon_entropy
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_...
python
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", ")", ":", "if", "not", "data", ":", "return", "0", "entropy", "=", "0", "for", "x", "in", "iterator", ":", "p_x", "=", "float", "(", "data", ".", "count", "(", "x", ")", ")", "/", "len", "("...
Borrowed from http://blog.dkbza.org/2007/05/scanning-data-for-entropy-anomalies.html
[ "Borrowed", "from", "http", ":", "//", "blog", ".", "dkbza", ".", "org", "/", "2007", "/", "05", "/", "scanning", "-", "data", "-", "for", "-", "entropy", "-", "anomalies", ".", "html" ]
a4c69fa2f6b256bfe824ac82b96c77eb8c06b2d0
https://github.com/dxa4481/truffleHog/blob/a4c69fa2f6b256bfe824ac82b96c77eb8c06b2d0/truffleHog/truffleHog.py#L85-L96
train
agermanidis/autosub
autosub/formatters.py
srt_formatter
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...
python
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", ")", ":", "sub_rip_file", "=", "pysrt", ".", "SubRipFile", "(", ")", "for", "i", ",", "(", "(", "start", ",", "end", ")", ",", "text", ")", "in...
Serialize a list of subtitles according to the SRT format, with optional time padding.
[ "Serialize", "a", "list", "of", "subtitles", "according", "to", "the", "SRT", "format", "with", "optional", "time", "padding", "." ]
d32389cb76e63ec6959111c3f989a72f36f726fe
https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/formatters.py#L14-L26
train
agermanidis/autosub
autosub/formatters.py
vtt_formatter
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
python
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", ")", ":", "text", "=", "srt_formatter", "(", "subtitles", ",", "padding_before", ",", "padding_after", ")", "text", "=", "'WEBVTT\\n\\n'", "+", "text", ...
Serialize a list of subtitles according to the VTT format, with optional time padding.
[ "Serialize", "a", "list", "of", "subtitles", "according", "to", "the", "VTT", "format", "with", "optional", "time", "padding", "." ]
d32389cb76e63ec6959111c3f989a72f36f726fe
https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/formatters.py#L29-L35
train
agermanidis/autosub
autosub/formatters.py
json_formatter
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)
python
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", ")", ":", "subtitle_dicts", "=", "[", "{", "'start'", ":", "start", ",", "'end'", ":", "end", ",", "'content'", ":", "text", ",", "}", "for", "(", "(", "start", ",", "end", ")", ",", "text", ")", "in", "su...
Serialize a list of subtitles as a JSON blob.
[ "Serialize", "a", "list", "of", "subtitles", "as", "a", "JSON", "blob", "." ]
d32389cb76e63ec6959111c3f989a72f36f726fe
https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/formatters.py#L38-L51
train
agermanidis/autosub
autosub/__init__.py
percentile
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...
python
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", ")", ":", "arr", "=", "sorted", "(", "arr", ")", "index", "=", "(", "len", "(", "arr", ")", "-", "1", ")", "*", "percent", "floor", "=", "math", ".", "floor", "(", "index", ")", "ceil", "=", "mat...
Calculate the given percentile of arr.
[ "Calculate", "the", "given", "percentile", "of", "arr", "." ]
d32389cb76e63ec6959111c3f989a72f36f726fe
https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/__init__.py#L39-L51
train
agermanidis/autosub
autosub/__init__.py
extract_audio
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...
python
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", ")", ":", "temp", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.wav'", ",", "delete", "=", "False", ")", "if", "not", "os", ".", "path",...
Extract audio from an input file to a temporary WAV file.
[ "Extract", "audio", "from", "an", "input", "file", "to", "a", "temporary", "WAV", "file", "." ]
d32389cb76e63ec6959111c3f989a72f36f726fe
https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/__init__.py#L175-L191
train
agermanidis/autosub
autosub/__init__.py
find_speech_regions
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...
python
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", "reader", "=", "wave", ".", "open", "(", "filename", ")", "sample...
Perform voice activity detection on a given audio file.
[ "Perform", "voice", "activity", "detection", "on", "a", "given", "audio", "file", "." ]
d32389cb76e63ec6959111c3f989a72f36f726fe
https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/__init__.py#L194-L230
train
agermanidis/autosub
autosub/__init__.py
generate_subtitles
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...
python
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_LANGUA...
Given an input audio/video file, generate subtitles in the specified language and format.
[ "Given", "an", "input", "audio", "/", "video", "file", "generate", "subtitles", "in", "the", "specified", "language", "and", "format", "." ]
d32389cb76e63ec6959111c3f989a72f36f726fe
https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/__init__.py#L233-L318
train
agermanidis/autosub
autosub/__init__.py
validate
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...
python
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", ")", ":", "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...
Check that the CLI arguments passed to autosub are valid.
[ "Check", "that", "the", "CLI", "arguments", "passed", "to", "autosub", "are", "valid", "." ]
d32389cb76e63ec6959111c3f989a72f36f726fe
https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/__init__.py#L321-L350
train
agermanidis/autosub
autosub/__init__.py
main
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...
python
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", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'source_path'", ",", "help", "=", "\"Path to the video or audio file to subtitle\"", ",", "nargs", "=", "'?'", ")", "parser", ".", "a...
Run autosub as a command-line program.
[ "Run", "autosub", "as", "a", "command", "-", "line", "program", "." ]
d32389cb76e63ec6959111c3f989a72f36f726fe
https://github.com/agermanidis/autosub/blob/d32389cb76e63ec6959111c3f989a72f36f726fe/autosub/__init__.py#L353-L410
train
palantir/python-language-server
pyls/plugins/pylint_lint.py
PylintLinter.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, ...
python
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", "=", "''", ")", ":", "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 ...
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...
[ "Plugin", "interface", "to", "pyls", "linter", "." ]
96e08d85635382d17024c352306c4759f124195d
https://github.com/palantir/python-language-server/blob/96e08d85635382d17024c352306c4759f124195d/pyls/plugins/pylint_lint.py#L15-L131
train