desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
':type l1: ListNode :type l2: ListNode :rtype: ListNode'
def addTwoNumbers(self, l1, l2):
dummy = ListNode(0) (current, carry) = (dummy, 0) while (l1 or l2): val = carry if l1: val += l1.val l1 = l1.next if l2: val += l2.val l2 = l2.next (carry, val) = ((val / 10), (val % 10)) current.next = ListNode(val) ...
':type maxChoosableInteger: int :type desiredTotal: int :rtype: bool'
def canIWin(self, maxChoosableInteger, desiredTotal):
def canIWinHelper(maxChoosableInteger, desiredTotal, visited, lookup): if (visited in lookup): return lookup[visited] mask = 1 for i in xrange(maxChoosableInteger): if ((visited & mask) == 0): if (((i + 1) >= desiredTotal) or (not canIWinHelper(maxChoo...
':type root: TreeNode :rtype: List[List[int]]'
def findLeaves(self, root):
def findLeavesHelper(node, result): if (not node): return (-1) level = (1 + max(findLeavesHelper(node.left, result), findLeavesHelper(node.right, result))) if (len(result) < (level + 1)): result.append([]) result[level].append(node.val) return level ...
':type equation: str :rtype: str'
def solveEquation(self, equation):
(a, b, side) = (0, 0, 1) for (eq, sign, num, isx) in re.findall('(=)|([-+]?)(\\d*)(x?)', equation): if eq: side = (-1) elif isx: a += ((side * int((sign + '1'))) * int((num or 1))) elif num: b -= (side * int((sign + num))) return (('x=%d' % (b / a)...
':type matrix: List[List[int]] :rtype: List[List[int]]'
def updateMatrix(self, matrix):
queue = collections.deque([]) for i in xrange(len(matrix)): for j in xrange(len(matrix[0])): if (matrix[i][j] == 0): queue.append((i, j)) else: matrix[i][j] = float('inf') dirs = [((-1), 0), (1, 0), (0, (-1)), (0, 1)] while queue: c...
'initialize your data structure here. :type matrix: List[List[int]]'
def __init__(self, matrix):
if (not matrix): return self.__matrix = matrix self.__bit = [([0] * (len(self.__matrix[0]) + 1)) for _ in xrange((len(self.__matrix) + 1))] for i in xrange(1, len(self.__bit)): for j in xrange(1, len(self.__bit[0])): self.__bit[i][j] = (((matrix[(i - 1)][(j - 1)] + self.__bit...
'update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void'
def update(self, row, col, val):
if (val - self.__matrix[row][col]): self.__add(row, col, (val - self.__matrix[row][col])) self.__matrix[row][col] = val
'sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtype: int'
def sumRegion(self, row1, col1, row2, col2):
return (((self.__sum(row2, col2) - self.__sum(row2, (col1 - 1))) - self.__sum((row1 - 1), col2)) + self.__sum((row1 - 1), (col1 - 1)))
':type nums: List[int] :rtype: bool'
def PredictTheWinner(self, nums):
if (((len(nums) % 2) == 0) or (len(nums) == 1)): return True dp = ([0] * len(nums)) for i in reversed(xrange(len(nums))): dp[i] = nums[i] for j in xrange((i + 1), len(nums)): dp[j] = max((nums[i] - dp[j]), (nums[j] - dp[(j - 1)])) return (dp[(-1)] >= 0)
':type k: int :type W: int :type Profits: List[int] :type Capital: List[int] :rtype: int'
def findMaximizedCapital(self, k, W, Profits, Capital):
curr = [] future = sorted(zip(Capital, Profits), reverse=True) for _ in xrange(k): while (future and (future[(-1)][0] <= W)): heapq.heappush(curr, (- future.pop()[1])) if curr: W -= heapq.heappop(curr) return W
':type s: str :rtype: int'
def numDecodings(self, s):
if ((len(s) == 0) or (s[0] == '0')): return 0 (prev, prev_prev) = (1, 0) for i in xrange(len(s)): cur = 0 if (s[i] != '0'): cur = prev if ((i > 0) and ((s[(i - 1)] == '1') or ((s[(i - 1)] == '2') and (s[i] <= '6')))): cur += prev_prev (prev, pr...
'Encodes a tree to a single string. :type root: TreeNode :rtype: str'
def serialize(self, root):
def serializeHelper(node): if (not node): vals.append('#') else: vals.append(str(node.val)) serializeHelper(node.left) serializeHelper(node.right) vals = [] serializeHelper(root) return ' '.join(vals)
'Decodes your encoded data to tree. :type data: str :rtype: TreeNode'
def deserialize(self, data):
def deserializeHelper(): val = next(vals) if (val == '#'): return None else: node = TreeNode(int(val)) node.left = deserializeHelper() node.right = deserializeHelper() return node def isplit(source, sep): sepsize = len(s...
':type flowerbed: List[int] :type n: int :rtype: bool'
def canPlaceFlowers(self, flowerbed, n):
for i in xrange(len(flowerbed)): if ((flowerbed[i] == 0) and ((i == 0) or (flowerbed[(i - 1)] == 0)) and ((i == (len(flowerbed) - 1)) or (flowerbed[(i + 1)] == 0))): flowerbed[i] = 1 n -= 1 if (n <= 0): return True return False
':type transactions: List[List[int]] :rtype: int'
def minTransfers(self, transactions):
account = collections.defaultdict(int) for transaction in transactions: account[transaction[0]] += transaction[2] account[transaction[1]] -= transaction[2] debt = [] for v in account.values(): if v: debt.append(v) if (not debt): return 0 n = (1 << len(...
':type paths: List[str] :rtype: List[List[str]]'
def findDuplicate(self, paths):
files = collections.defaultdict(list) for path in paths: s = path.split(' ') for i in xrange(1, len(s)): file_name = ((s[0] + '/') + s[i][0:s[i].find('(')]) file_content = s[i][(s[i].find('(') + 1):s[i].find(')')] files[file_content].append(file_name) r...
':type nums: List[List[int]] :type r: int :type c: int :rtype: List[List[int]]'
def matrixReshape(self, nums, r, c):
if ((not nums) or ((r * c) != (len(nums) * len(nums[0])))): return nums result = [[0 for _ in xrange(c)] for _ in xrange(r)] count = 0 for i in xrange(len(nums)): for j in xrange(len(nums[0])): result[(count / c)][(count % c)] = nums[i][j] count += 1 return re...
':type words: List[str] :rtype: List[str]'
def findAllConcatenatedWordsInADict(self, words):
lookup = set(words) result = [] for word in words: dp = ([False] * (len(word) + 1)) dp[0] = True for i in xrange(len(word)): if (not dp[i]): continue for j in xrange((i + 1), (len(word) + 1)): if (((j - i) < len(word)) and (word...
':type a: int :type b: int :rtype: int'
def getSum(self, a, b):
bit_length = 32 (neg_bit, mask) = (((1 << bit_length) >> 1), (~ ((~ 0) << bit_length))) a = ((a | (~ mask)) if (a & neg_bit) else (a & mask)) b = ((b | (~ mask)) if (b & neg_bit) else (b & mask)) while b: carry = (a & b) a ^= b a = ((a | (~ mask)) if (a & neg_bit) else (a & m...
':type a: int :type b: int :rtype: int'
def getSum2(self, a, b):
MAX = 2147483647 MIN = 2147483648 mask = 4294967295 while b: (a, b) = (((a ^ b) & mask), (((a & b) << 1) & mask)) return (a if (a <= MAX) else (~ (a ^ mask)))
'initialize your data structure here. :type dictionary: List[str]'
def __init__(self, dictionary):
self.lookup_ = collections.defaultdict(set) for word in dictionary: abbr = self.abbreviation(word) self.lookup_[abbr].add(word)
'check if a word is unique. :type word: str :rtype: bool'
def isUnique(self, word):
abbr = self.abbreviation(word) return (self.lookup_[abbr] <= {word})
':type s: str :rtype: str'
def removeDuplicateLetters(self, s):
remaining = collections.defaultdict(int) for c in s: remaining[c] += 1 (in_stack, stk) = (set(), []) for c in s: if (c not in in_stack): while (stk and (stk[(-1)] > c) and remaining[stk[(-1)]]): in_stack.remove(stk.pop()) stk += c in_st...
':type s: str :type k: int :rtype: int'
def characterReplacement(self, s, k):
res = 0 cnts = ([0] * 26) (times, i, j) = (k, 0, 0) while (j < len(s)): cnts[(ord(s[j]) - ord('A'))] += 1 if (s[j] != s[i]): times -= 1 if (times < 0): res = max(res, (j - i)) while ((i < j) and (times < 0)): cnt...
':type str: str :type k: int :rtype: str'
def rearrangeString(self, str, k):
cnts = ([0] * 26) for c in str: cnts[(ord(c) - ord('a'))] += 1 sorted_cnts = [] for i in xrange(26): sorted_cnts.append((cnts[i], chr((i + ord('a'))))) sorted_cnts.sort(reverse=True) max_cnt = sorted_cnts[0][0] blocks = [[] for _ in xrange(max_cnt)] i = 0 for cnt in s...
':type str: str :type k: int :rtype: str'
def rearrangeString(self, str, k):
if (k == 0): return str cnts = defaultdict(int) for c in str: cnts[c] += 1 heap = [] for (c, cnt) in cnts.iteritems(): heappush(heap, [(- cnt), c]) result = [] while heap: used_cnt_chars = [] for _ in xrange(min(k, (len(str) - len(result)))): ...
':type nums: List[int] :rtype: int'
def jump(self, nums):
nums[(-1)] = (2 ** 31) (nums2, l) = ([(i + j) for (i, j) in enumerate(nums)], (len(nums) - 1)) def find_max_index(index): tmp = nums2[index:((index + nums[index]) + 1)] return (index + tmp.index(max(tmp))) (index, steps) = (0, 0) while True: index = find_max_index(index) ...
':type nums: List[int] :rtype: int'
def thirdMax(self, nums):
count = 0 top = ([float('-inf')] * 3) for num in nums: if (num > top[0]): (top[0], top[1], top[2]) = (num, top[0], top[1]) count += 1 elif ((num != top[0]) and (num > top[1])): (top[1], top[2]) = (num, top[1]) count += 1 elif ((num != t...
':type num: str :type target: int :rtype: List[str]'
def addOperators(self, num, target):
(result, expr) = ([], []) (val, i) = (0, 0) val_str = '' while (i < len(num)): val = (((val * 10) + ord(num[i])) - ord('0')) val_str += num[i] if (str(val) != val_str): break expr.append(val_str) self.addOperatorsDFS(num, target, (i + 1), 0, val, expr,...
':type root: TreeNode :rtype: List[int]'
def boundaryOfBinaryTree(self, root):
def leftBoundary(root, nodes): if ((not root) or ((not root.left) and (not root.right))): return nodes.append(root.val) if (not root.left): leftBoundary(root.right, nodes) else: leftBoundary(root.left, nodes) def rightBoundary(root, nodes): ...
':type findNums: List[int] :type nums: List[int] :rtype: List[int]'
def nextGreaterElement(self, findNums, nums):
(stk, lookup) = ([], {}) for num in nums: while (stk and (num > stk[(-1)])): lookup[stk.pop()] = num stk.append(num) while stk: lookup[stk.pop()] = (-1) return map((lambda x: lookup[x]), findNums)
':type root: TreeNode :type key: int :rtype: TreeNode'
def deleteNode(self, root, key):
if (not root): return root if (root.val > key): root.left = deleteNode(root.left, key) elif (root.val < key): root.right = deleteNode(root.right, key) elif (not root.left): right = root.right del root return right elif (not root.right): left = ...
':type nums: List[int] :rtype: int'
def rob2(self, nums):
(last, now) = (0, 0) for i in nums: (last, now) = (now, max((last + i), now)) return now
':type m: int :type n: int :type N: int :type x: int :type y: int :rtype: int'
def findPaths(self, m, n, N, x, y):
M = (1000000000 + 7) dp = [[[0 for _ in xrange(n)] for _ in xrange(m)] for _ in xrange(2)] for moves in xrange(N): for i in xrange(m): for j in xrange(n): dp[((moves + 1) % 2)][i][j] = (((((1 if (i == 0) else dp[(moves % 2)][(i - 1)][j]) + (1 if (i == (m - 1)) else dp[(mo...
'This is where the meat is. Basically the data_files list must now be a list of tuples of 3 entries. The first entry is one of \'base\', \'platbase\', etc, which indicates which base to install from. The second entry is the path to install too. The third entry is a list of files to install.'
def run(self):
for lof in self.data_files: if lof[0]: base = getattr(self, ('install_' + lof[0])) else: base = getattr(self, 'install_base') dir = convert_path(lof[1]) if (not os.path.isabs(dir)): dir = os.path.join(base, dir) elif self.root: ...
'Event handler for the button click.'
def OnTimeToClose(self, evt):
print 'See ya later!' self.Close()
'Event handler for the button click.'
def OnFunButton(self, evt):
print 'Having fun yet?'
'Initialize package for parsing Parameters package_name : string Name of the top-level package. *package_name* must be the name of an importable package rst_extension : string, optional Extension for reST files, default \'.rst\' package_skip_patterns : None or sequence of {strings, regexps} Sequence of strings giving ...
def __init__(self, package_name, rst_extension='.rst', package_skip_patterns=None, module_skip_patterns=None, names_from__all__=None):
if (package_skip_patterns is None): package_skip_patterns = ['\\.tests$'] if (module_skip_patterns is None): module_skip_patterns = ['\\.setup$', '\\._'] self.package_name = package_name self.rst_extension = rst_extension self.package_skip_patterns = package_skip_patterns self.mo...
'Set package_name >>> docwriter = ApiDocWriter(\'sphinx\') >>> import sphinx >>> docwriter.root_path == sphinx.__path__[0] True >>> docwriter.package_name = \'docutils\' >>> import docutils >>> docwriter.root_path == docutils.__path__[0] True'
def set_package_name(self, package_name):
self._package_name = package_name self.root_module = import_module(package_name) self.root_path = self.root_module.__path__[0] self.written_modules = None
'Convert uri to absolute filepath Parameters uri : string URI of python module to return path for Returns path : None or string Returns None if there is no valid path for this URI Otherwise returns absolute file system path for URI Examples >>> docwriter = ApiDocWriter(\'sphinx\') >>> import sphinx >>> modpath = sphinx...
def _uri2path(self, uri):
if (uri == self.package_name): return os.path.join(self.root_path, '__init__.py') path = uri.replace('.', os.path.sep) path = path.replace((self.package_name + os.path.sep), '') path = os.path.join(self.root_path, path) if os.path.exists((path + '.py')): path += '.py' elif os.pat...
'Convert directory path to uri'
def _path2uri(self, dirpath):
relpath = dirpath.replace(self.root_path, self.package_name) if relpath.startswith(os.path.sep): relpath = relpath[1:] return relpath.replace(os.path.sep, '.')
'Parse module defined in *uri*'
def _parse_module(self, uri):
filename = self._uri2path(uri) if (filename is None): return ([], []) with open(filename, 'rb') as f: mod = ast.parse(f.read()) return FuncClsScanner().scan(mod)
'Import * from uri, and separate out functions and classes.'
def _import_funcs_classes(self, uri):
ns = {} exec ('from %s import *' % uri) in ns (funcs, classes) = ([], []) for (name, obj) in ns.items(): if inspect.isclass(obj): cls = Obj(name=name, has_init=('__init__' in obj.__dict__)) classes.append(cls) elif inspect.isfunction(obj): fun...
'Find the functions and classes defined in the module ``uri``'
def find_funcs_classes(self, uri):
if (uri in self.names_from__all__): return self._import_funcs_classes(uri) else: return self._parse_module(uri)
'Make autodoc documentation template string for a module Parameters uri : string python location of module - e.g \'sphinx.builder\' Returns S : string Contents of API doc'
def generate_api_doc(self, uri):
(functions, classes) = self.find_funcs_classes(uri) if ((not len(functions)) and (not len(classes))): return '' uri_short = re.sub(('^%s\\.' % self.package_name), '', uri) ad = '.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n' if ('.' in uri): chap_title = (('Module: ...
'Returns True if *matchstr* does not match patterns ``self.package_name`` removed from front of string if present Examples >>> dw = ApiDocWriter(\'sphinx\') >>> dw._survives_exclude(\'sphinx.okpkg\', \'package\') True >>> dw.package_skip_patterns.append(\'^\.badpkg$\') >>> dw._survives_exclude(\'sphinx.badpkg\', \'pack...
def _survives_exclude(self, matchstr, match_type):
if (match_type == 'module'): patterns = self.module_skip_patterns elif (match_type == 'package'): patterns = self.package_skip_patterns else: raise ValueError(('Cannot interpret match type "%s"' % match_type)) L = len(self.package_name) if (matchstr[:L] == self.pa...
'Return module sequence discovered from ``self.package_name`` Parameters None Returns mods : sequence Sequence of module names within ``self.package_name`` Examples >>> dw = ApiDocWriter(\'sphinx\') >>> mods = dw.discover_modules() >>> \'sphinx.util\' in mods True >>> dw.package_skip_patterns.append(\'\.util$\') >>> \'...
def discover_modules(self):
modules = [self.package_name] for (dirpath, dirnames, filenames) in os.walk(self.root_path): root_uri = self._path2uri(os.path.join(self.root_path, dirpath)) for dirname in dirnames[:]: package_uri = '.'.join((root_uri, dirname)) if (self._uri2path(package_uri) and self._...
'Generate API reST files. Parameters outdir : string Directory name in which to store files We create automatic filenames for each module Returns None Notes Sets self.written_modules to list of written modules'
def write_api_docs(self, outdir):
if (not os.path.exists(outdir)): os.mkdir(outdir) modules = self.discover_modules() self.write_modules_api(modules, outdir)
'Make a reST API index file from written files Parameters outdir : string Directory to which to write generated index file path : string Filename to write index to relative_to : string path to which written filenames are relative. This component of the written file path will be removed from outdir, in the generated in...
def write_index(self, outdir, path='gen.rst', relative_to=None):
if (self.written_modules is None): raise ValueError('No modules written') path = os.path.join(outdir, path) if (relative_to is not None): relpath = outdir.replace((relative_to + os.path.sep), '') else: relpath = outdir idx = open(path, 'wt') w = idx.write w('.. ...
'Set the hook.'
def set(self):
if (sys.displayhook is not self.hook): self.old_hook = sys.displayhook sys.displayhook = self.hook
'Unset the hook.'
def unset(self):
sys.displayhook = self.old_hook
'Initialise the :class:`CallbackManager`. Parameters shell The :class:`~IPython.core.interactiveshell.InteractiveShell` instance available_callbacks An iterable of names for callback events.'
def __init__(self, shell, available_events):
self.shell = shell self.callbacks = {n: [] for n in available_events}
'Register a new event callback Parameters event : str The event for which to register this callback. function : callable A function to be called on the given event. It should take the same parameters as the appropriate callback prototype. Raises TypeError If ``function`` is not callable. KeyError If ``event`` is not on...
def register(self, event, function):
if (not callable(function)): raise TypeError(('Need a callable, got %r' % function)) self.callbacks[event].append(function)
'Remove a callback from the given event.'
def unregister(self, event, function):
self.callbacks[event].remove(function)
'Call callbacks for ``event``. Any additional arguments are passed to all callbacks registered for this event. Exceptions raised by callbacks are caught, and a message printed.'
def trigger(self, event, *args, **kwargs):
for func in self.callbacks[event][:]: try: func(*args, **kwargs) except Exception: print 'Error in callback {} (for {}):'.format(func, event) self.shell.showtraceback()
'Set up matplotlib to work interactively. This function lets you activate matplotlib interactive support at any point during an IPython session. It does not import anything into the interactive namespace. If you are using the inline matplotlib backend in the IPython Notebook you can set which figure formats are enabled...
@skip_doctest @line_magic @magic_arguments.magic_arguments() @magic_arguments.argument('-l', '--list', action='store_true', help='Show available matplotlib backends') @magic_gui_arg def matplotlib(self, line=''):
args = magic_arguments.parse_argstring(self.matplotlib, line) if args.list: backends_list = list(backends.keys()) print ('Available matplotlib backends: %s' % backends_list) else: (gui, backend) = self.shell.enable_matplotlib(args.gui) self._show_matplotlib_backend(a...
'Load numpy and matplotlib to work interactively. This function lets you activate pylab (matplotlib, numpy and interactive support) at any point during an IPython session. %pylab makes the following imports:: import numpy import matplotlib from matplotlib import pylab, mlab, pyplot np = numpy plt = pyplot from IPython....
@skip_doctest @line_magic @magic_arguments.magic_arguments() @magic_arguments.argument('--no-import-all', action='store_true', default=None, help='Prevent IPython from performing ``import *`` into the interactive namespace.\n \n Yo...
args = magic_arguments.parse_argstring(self.pylab, line) if (args.no_import_all is None): if Application.initialized(): app = Application.instance() try: import_all = app.pylab_import_all except AttributeError: import_all = True ...
'show matplotlib message backend message'
def _show_matplotlib_backend(self, gui, backend):
if ((not gui) or (gui == 'auto')): print ('Using matplotlib backend: %s' % backend)
'Start logging anywhere in a session. %logstart [-o|-r|-t|-q] [log_name [log_mode]] If no name is given, it defaults to a file named \'ipython_log.py\' in your current directory, in \'rotate\' mode (see below). \'%logstart name\' saves to file \'name\' in \'backup\' mode. It saves your history up to that point and the...
@line_magic def logstart(self, parameter_s=''):
(opts, par) = self.parse_options(parameter_s, 'ortq') log_output = ('o' in opts) log_raw_input = ('r' in opts) timestamp = ('t' in opts) quiet = ('q' in opts) logger = self.shell.logger if par: try: (logfname, logmode) = par.split() except: logfname = ...
'Fully stop logging and close log file. In order to start logging again, a new %logstart call needs to be made, possibly (though not necessarily) with a new filename, mode and other options.'
@line_magic def logstop(self, parameter_s=''):
self.shell.logger.logstop()
'Temporarily stop logging. You must have previously started logging.'
@line_magic def logoff(self, parameter_s=''):
self.shell.logger.switch_log(0)
'Restart logging. This function is for restarting logging which you\'ve temporarily stopped with %logoff. For starting logging for the first time, you must use the %logstart function, which allows you to specify an optional log filename.'
@line_magic def logon(self, parameter_s=''):
self.shell.logger.switch_log(1)
'Print the status of the logging system.'
@line_magic def logstate(self, parameter_s=''):
self.shell.logger.logstate()
'Run the cell block of Javascript code Alias of `%%javascript`'
@cell_magic def js(self, line, cell):
self.javascript(line, cell)
'Run the cell block of Javascript code'
@cell_magic def javascript(self, line, cell):
display(Javascript(cell))
'Render the cell as a block of latex The subset of latex which is support depends on the implementation in the client. In the Jupyter Notebook, this magic only renders the subset of latex defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).'
@cell_magic def latex(self, line, cell):
display(Latex(cell))
'Render the cell as an SVG literal'
@cell_magic def svg(self, line, cell):
display(SVG(cell))
'Render the cell as a block of HTML'
@cell_magic def html(self, line, cell):
display(HTML(cell))
'Render the cell as Markdown text block'
@cell_magic def markdown(self, line, cell):
display(Markdown(cell))
'configure IPython %config Class[.trait=value] This magic exposes most of the IPython config system. Any Configurable class should be able to be configured with the simple line:: %config Class.trait=value Where `value` will be resolved in the user\'s namespace, if it is an expression or variable name. Examples To see w...
@line_magic def config(self, s):
from traitlets.config.loader import Config configurables = sorted(set([c for c in self.shell.configurables if c.__class__.class_traits(config=True)]), key=(lambda x: x.__class__.__name__)) classnames = [c.__class__.__name__ for c in configurables] line = s.strip() if (not line): print 'Avail...
'default to a common list of programs'
@default('script_magics') def _script_magics_default(self):
defaults = ['sh', 'bash', 'perl', 'ruby', 'python', 'python2', 'python3', 'pypy'] if (os.name == 'nt'): defaults.extend(['cmd']) return defaults
'make a named magic, that calls %%script with a particular program'
def _make_script_magic(self, name):
script = self.script_paths.get(name, name) @magic_arguments.magic_arguments() @script_args def named_script_magic(line, cell): if line: line = ('%s %s' % (script, line)) else: line = script return self.shebang(line, cell) named_script_magic.__doc__ ...
'Run a cell via a shell command The `%%script` line is like the #! line of script, specifying a program (bash, perl, ruby, etc.) with which to run. The rest of the cell is run by that program. Examples In [1]: %%script bash ...: for i in 1 2 3; do ...: echo $i ...: done 1 2 3'
@magic_arguments.magic_arguments() @script_args @cell_magic('script') def shebang(self, line, cell):
argv = arg_split(line, posix=(not sys.platform.startswith('win'))) (args, cmd) = self.shebang.parser.parse_known_args(argv) try: p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE) except OSError as e: if (e.errno == errno.ENOENT): print ("Couldn't find program: %r"...
'callback for running the script in the background'
def _run_script(self, p, cell):
p.stdin.write(cell) p.stdin.close() p.wait()
'Kill all BG processes started by %%script and its family.'
@line_magic('killbgscripts') def killbgscripts(self, _nouse_=''):
self.kill_bg_processes() print 'All background processes were killed.'
'Kill all BG processes which are still running.'
def kill_bg_processes(self):
if (not self.bg_processes): return for p in self.bg_processes: if (p.poll() is None): try: p.send_signal(signal.SIGINT) except: pass time.sleep(0.1) self._gc_bg_processes() if (not self.bg_processes): return for p in...
'Load an IPython extension by its module name.'
@line_magic def load_ext(self, module_str):
if (not module_str): raise UsageError('Missing module name.') res = self.shell.extension_manager.load_extension(module_str) if (res == 'already loaded'): print ('The %s extension is already loaded. To reload it, use:' % module_str) print (' ...
'Unload an IPython extension by its module name. Not all extensions can be unloaded, only those which define an ``unload_ipython_extension`` function.'
@line_magic def unload_ext(self, module_str):
if (not module_str): raise UsageError('Missing module name.') res = self.shell.extension_manager.unload_extension(module_str) if (res == 'no unload function'): print ("The %s extension doesn't define how to unload it." % module_str) elif (res == 'not ...
'Reload an IPython extension by its module name.'
@line_magic def reload_ext(self, module_str):
if (not module_str): raise UsageError('Missing module name.') self.shell.extension_manager.reload_extension(module_str)
'Make magic functions callable without having to type the initial %. Without argumentsl toggles on/off (when off, you must call it as %automagic, of course). With arguments it sets the value, and you can use any of (case insensitive): - on, 1, True: to activate - off, 0, False: to deactivate. Note that magic functions...
@line_magic def automagic(self, parameter_s=''):
arg = parameter_s.lower() mman = self.shell.magics_manager if (arg in ('on', '1', 'true')): val = True elif (arg in ('off', '0', 'false')): val = False else: val = (not mman.auto_magic) mman.auto_magic = val print ('\n' + self.shell.magics_manager.auto_status())
'Make functions callable without having to type parentheses. Usage: %autocall [mode] The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the value is toggled on and off (remembering the previous state). In more detail, these values mean: 0 -> fully disabled 1 -> active, but do not apply if there are no ar...
@skip_doctest @line_magic def autocall(self, parameter_s=''):
if parameter_s: arg = int(parameter_s) else: arg = 'toggle' if (not (arg in (0, 1, 2, 'toggle'))): error('Valid modes: (0->Off, 1->Smart, 2->Full') return if (arg in (0, 1, 2)): self.shell.autocall = arg elif self.shell.autocall: self._magi...
'Define an alias for a system command. \'%alias alias_name cmd\' defines \'alias_name\' as an alias for \'cmd\' Then, typing \'alias_name params\' will execute the system command \'cmd params\' (from your underlying operating system). Aliases have lower precedence than magic functions and Python normal variables, so if...
@skip_doctest @line_magic def alias(self, parameter_s=''):
par = parameter_s.strip() if (not par): aliases = sorted(self.shell.alias_manager.aliases) print ('Total number of aliases:', len(aliases)) sys.stdout.flush() return aliases try: (alias, cmd) = par.split(None, 1) except TypeError: print oinspect.g...
'Remove an alias'
@line_magic def unalias(self, parameter_s=''):
aname = parameter_s.strip() try: self.shell.alias_manager.undefine_alias(aname) except ValueError as e: print e return stored = self.shell.db.get('stored_aliases', {}) if (aname in stored): print ('Removing %stored alias', aname) del stored[aname] ...
'Update the alias table with all executable files in $PATH. rehashx explicitly checks that every entry in $PATH is a file with execute access (os.X_OK). Under Windows, it checks executability as a match against a \'|\'-separated string of extensions, stored in the IPython config variable win_exec_ext. This defaults to...
@line_magic def rehashx(self, parameter_s=''):
from IPython.core.alias import InvalidAliasError del self.shell.db['rootmodules_cache'] path = [os.path.abspath(os.path.expanduser(p)) for p in os.environ.get('PATH', '').split(os.pathsep)] syscmdlist = [] if (os.name == 'posix'): isexec = (lambda fname: (os.path.isfile(fname) and os.access(...
'Return the current working directory path. Examples In [9]: pwd Out[9]: \'/home/tsuser/sprint/ipython\''
@skip_doctest @line_magic def pwd(self, parameter_s=''):
try: return os.getcwd() except FileNotFoundError: raise UsageError('CWD no longer exists - please use %cd to change directory.')
'Change the current working directory. This command automatically maintains an internal list of directories you visit during your IPython session, in the variable _dh. The command %dhist shows this history nicely formatted. You can also do \'cd -<tab>\' to see directory history conveniently. Usage: cd \'dir\': changes ...
@skip_doctest @line_magic def cd(self, parameter_s=''):
try: oldcwd = os.getcwd() except FileNotFoundError: oldcwd = None numcd = re.match('(-)(\\d+)$', parameter_s) if numcd: nn = int(numcd.group(2)) try: ps = self.shell.user_ns['_dh'][nn] except IndexError: print 'The requested directory...
'Get, set, or list environment variables. Usage:\ %env: lists all environment variables/values %env var: get value for var %env var val: set value for var %env var=val: set value for var %env var=$val: set value for var, using python expansion if possible'
@line_magic def env(self, parameter_s=''):
if parameter_s.strip(): split = ('=' if ('=' in parameter_s) else ' ') bits = parameter_s.split(split) if (len(bits) == 1): key = parameter_s.strip() if (key in os.environ): return os.environ[key] else: err = 'Environment...
'Set environment variables. Assumptions are that either "val" is a name in the user namespace, or val is something that evaluates to a string. Usage:\ %set_env var val: set value for var %set_env var=val: set value for var %set_env var=$val: set value for var, using python expansion if possible'
@line_magic def set_env(self, parameter_s):
split = ('=' if ('=' in parameter_s) else ' ') bits = parameter_s.split(split, 1) if ((not parameter_s.strip()) or (len(bits) < 2)): raise UsageError("usage is 'set_env var=val'") var = bits[0].strip() val = bits[1].strip() if re.match('.*\\s.*', var): err = "refusing...
'Place the current dir on stack and change directory. Usage:\ %pushd [\'dirname\']'
@line_magic def pushd(self, parameter_s=''):
dir_s = self.shell.dir_stack tgt = os.path.expanduser(parameter_s) cwd = os.getcwd().replace(self.shell.home_dir, '~') if tgt: self.cd(parameter_s) dir_s.insert(0, cwd) return self.shell.magic('dirs')
'Change to directory popped off the top of the stack.'
@line_magic def popd(self, parameter_s=''):
if (not self.shell.dir_stack): raise UsageError('%popd on empty stack') top = self.shell.dir_stack.pop(0) self.cd(top) print ('popd ->', top)
'Return the current directory stack.'
@line_magic def dirs(self, parameter_s=''):
return self.shell.dir_stack
'Print your history of visited directories. %dhist -> print full history\ %dhist n -> print last n entries only\ %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\ This history is automatically maintained by the %cd command, and always available as the global list variable _dh. You can use %cd...
@line_magic def dhist(self, parameter_s=''):
dh = self.shell.user_ns['_dh'] if parameter_s: try: args = map(int, parameter_s.split()) except: self.arg_err(self.dhist) return if (len(args) == 1): (ini, fin) = (max((len(dh) - args[0]), 0), len(dh)) elif (len(args) == 2): ...
'Shell capture - run shell command and capture output (DEPRECATED use !). DEPRECATED. Suboptimal, retained for backwards compatibility. You should use the form \'var = !command\' instead. Example: "%sc -l myfiles = ls ~" should now be written as "myfiles = !ls ~" myfiles.s, myfiles.l and myfiles.n still apply as docume...
@skip_doctest @line_magic def sc(self, parameter_s=''):
(opts, args) = self.parse_options(parameter_s, 'lv') try: (var, _) = args.split('=', 1) var = var.strip() (_, cmd) = parameter_s.split('=', 1) except ValueError: (var, cmd) = ('', '') split = ('l' in opts) out = self.shell.getoutput(cmd, split=split) if ('v' in op...
'Shell execute - run shell command and capture output (!! is short-hand). %sx command IPython will run the given command using commands.getoutput(), and return the result formatted as a list (split on \'\n\'). Since the output is _returned_, it will be stored in ipython\'s regular output cache Out[N] and in the \'_N\'...
@line_cell_magic def sx(self, line='', cell=None):
if (cell is None): return self.shell.getoutput(line) else: (opts, args) = self.parse_options(line, '', 'out=') output = self.shell.getoutput(cell) out_name = opts.get('out', opts.get('o')) if out_name: self.shell.user_ns[out_name] = output else: ...
'Manage IPython\'s bookmark system. %bookmark <name> - set bookmark to current dir %bookmark <name> <dir> - set bookmark to <dir> %bookmark -l - list all bookmarks %bookmark -d <name> - remove bookmark %bookmark -r - remove all bookmarks You can later on access a bookmarked folder with:: %c...
@line_magic def bookmark(self, parameter_s=''):
(opts, args) = self.parse_options(parameter_s, 'drl', mode='list') if (len(args) > 2): raise UsageError('%bookmark: too many arguments') bkms = self.shell.db.get('bookmarks', {}) if ('d' in opts): try: todel = args[0] except IndexError: raise Usag...
'Show a syntax-highlighted file through a pager. This magic is similar to the cat utility, but it will assume the file to be Python source and will show it with syntax highlighting. This magic command can either take a local filename, an url, an history range (see %history) or a macro as argument :: %pycat myscript.py ...
@line_magic def pycat(self, parameter_s=''):
if (not parameter_s): raise UsageError('Missing filename, URL, input history range, or macro.') try: cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False) except (ValueError, IOError): print 'Error: no such file, variable, URL, ...
'Write the contents of the cell to a file. The file will be overwritten unless the -a (--append) flag is specified.'
@magic_arguments.magic_arguments() @magic_arguments.argument('-a', '--append', action='store_true', default=False, help='Append contents of the cell to an existing file. The file will be created if it does not exist.') @magic_arguments.argument('filename', type=str,...
args = magic_arguments.parse_argstring(self.writefile, line) filename = os.path.expanduser(args.filename) if os.path.exists(filename): if args.append: print ('Appending to %s' % filename) else: print ('Overwriting %s' % filename) else: print ('Wri...
'The main implementation of the %lsmagic'
def _lsmagic(self):
mesc = magic_escapes['line'] cesc = magic_escapes['cell'] mman = self.magics_manager magics = mman.lsmagic() out = ['Available line magics:', (mesc + (' ' + mesc).join(sorted([m for (m, v) in magics['line'].items() if (v not in self.ignore)]))), '', 'Available cell magics:', (cesc...
'turn magics dict into jsonable dict of the same structure replaces object instances with their class names as strings'
def _jsonable(self):
magic_dict = {} mman = self.magics_manager magics = mman.lsmagic() for (key, subdict) in magics.items(): d = {} magic_dict[key] = d for (name, obj) in subdict.items(): try: classname = obj.__self__.__class__.__name__ except AttributeError: ...
'Create an alias for an existing line or cell magic. Examples In [1]: %alias_magic t timeit Created `%t` as an alias for `%timeit`. Created `%%t` as an alias for `%%timeit`. In [2]: %t -n1 pass 1 loops, best of 3: 954 ns per loop In [3]: %%t -n1 ...: pass 1 loops, best of 3: 954 ns per loop In [4]: %alias_magic --cell ...
@magic_arguments.magic_arguments() @magic_arguments.argument('-l', '--line', action='store_true', help='Create a line magic alias.') @magic_arguments.argument('-c', '--cell', action='store_true', help='Create a cell magic alias.') @magic_arguments.argument('name', help='Name of the magi...
args = magic_arguments.parse_argstring(self.alias_magic, line) shell = self.shell mman = self.shell.magics_manager escs = ''.join(magic_escapes.values()) target = args.target.lstrip(escs) name = args.name.lstrip(escs) params = args.params if (params and ((params.startswith('"') and param...