partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
Process.get_cpu_percent
Return a float representing the current process CPU utilization as a percentage. When interval is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls.
environment/lib/python2.7/site-packages/psutil/__init__.py
def get_cpu_percent(self, interval=0.1): """Return a float representing the current process CPU utilization as a percentage. When interval is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. """ blocking = interval is not None and interval > 0.0 if blocking: st1 = sum(cpu_times()) pt1 = self._platform_impl.get_cpu_times() time.sleep(interval) st2 = sum(cpu_times()) pt2 = self._platform_impl.get_cpu_times() else: st1 = self._last_sys_cpu_times pt1 = self._last_proc_cpu_times st2 = sum(cpu_times()) pt2 = self._platform_impl.get_cpu_times() if st1 is None or pt1 is None: self._last_sys_cpu_times = st2 self._last_proc_cpu_times = pt2 return 0.0 delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system) delta_time = st2 - st1 # reset values for next call in case of interval == None self._last_sys_cpu_times = st2 self._last_proc_cpu_times = pt2 try: # the utilization split between all CPUs overall_percent = (delta_proc / delta_time) * 100 except ZeroDivisionError: # interval was too low return 0.0 # the utilization of a single CPU single_cpu_percent = overall_percent * NUM_CPUS # on posix a percentage > 100 is legitimate # http://stackoverflow.com/questions/1032357/comprehending-top-cpu-usage # on windows we use this ugly hack to avoid troubles with float # precision issues if os.name != 'posix': if single_cpu_percent > 100.0: return 100.0 return round(single_cpu_percent, 1)
def get_cpu_percent(self, interval=0.1): """Return a float representing the current process CPU utilization as a percentage. When interval is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. """ blocking = interval is not None and interval > 0.0 if blocking: st1 = sum(cpu_times()) pt1 = self._platform_impl.get_cpu_times() time.sleep(interval) st2 = sum(cpu_times()) pt2 = self._platform_impl.get_cpu_times() else: st1 = self._last_sys_cpu_times pt1 = self._last_proc_cpu_times st2 = sum(cpu_times()) pt2 = self._platform_impl.get_cpu_times() if st1 is None or pt1 is None: self._last_sys_cpu_times = st2 self._last_proc_cpu_times = pt2 return 0.0 delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system) delta_time = st2 - st1 # reset values for next call in case of interval == None self._last_sys_cpu_times = st2 self._last_proc_cpu_times = pt2 try: # the utilization split between all CPUs overall_percent = (delta_proc / delta_time) * 100 except ZeroDivisionError: # interval was too low return 0.0 # the utilization of a single CPU single_cpu_percent = overall_percent * NUM_CPUS # on posix a percentage > 100 is legitimate # http://stackoverflow.com/questions/1032357/comprehending-top-cpu-usage # on windows we use this ugly hack to avoid troubles with float # precision issues if os.name != 'posix': if single_cpu_percent > 100.0: return 100.0 return round(single_cpu_percent, 1)
[ "Return", "a", "float", "representing", "the", "current", "process", "CPU", "utilization", "as", "a", "percentage", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L470-L520
[ "def", "get_cpu_percent", "(", "self", ",", "interval", "=", "0.1", ")", ":", "blocking", "=", "interval", "is", "not", "None", "and", "interval", ">", "0.0", "if", "blocking", ":", "st1", "=", "sum", "(", "cpu_times", "(", ")", ")", "pt1", "=", "self", ".", "_platform_impl", ".", "get_cpu_times", "(", ")", "time", ".", "sleep", "(", "interval", ")", "st2", "=", "sum", "(", "cpu_times", "(", ")", ")", "pt2", "=", "self", ".", "_platform_impl", ".", "get_cpu_times", "(", ")", "else", ":", "st1", "=", "self", ".", "_last_sys_cpu_times", "pt1", "=", "self", ".", "_last_proc_cpu_times", "st2", "=", "sum", "(", "cpu_times", "(", ")", ")", "pt2", "=", "self", ".", "_platform_impl", ".", "get_cpu_times", "(", ")", "if", "st1", "is", "None", "or", "pt1", "is", "None", ":", "self", ".", "_last_sys_cpu_times", "=", "st2", "self", ".", "_last_proc_cpu_times", "=", "pt2", "return", "0.0", "delta_proc", "=", "(", "pt2", ".", "user", "-", "pt1", ".", "user", ")", "+", "(", "pt2", ".", "system", "-", "pt1", ".", "system", ")", "delta_time", "=", "st2", "-", "st1", "# reset values for next call in case of interval == None", "self", ".", "_last_sys_cpu_times", "=", "st2", "self", ".", "_last_proc_cpu_times", "=", "pt2", "try", ":", "# the utilization split between all CPUs", "overall_percent", "=", "(", "delta_proc", "/", "delta_time", ")", "*", "100", "except", "ZeroDivisionError", ":", "# interval was too low", "return", "0.0", "# the utilization of a single CPU", "single_cpu_percent", "=", "overall_percent", "*", "NUM_CPUS", "# on posix a percentage > 100 is legitimate", "# http://stackoverflow.com/questions/1032357/comprehending-top-cpu-usage", "# on windows we use this ugly hack to avoid troubles with float", "# precision issues", "if", "os", ".", "name", "!=", "'posix'", ":", "if", "single_cpu_percent", ">", "100.0", ":", "return", "100.0", "return", "round", "(", "single_cpu_percent", ",", "1", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_memory_percent
Compare physical system memory to process resident memory and calculate process memory utilization as a percentage.
environment/lib/python2.7/site-packages/psutil/__init__.py
def get_memory_percent(self): """Compare physical system memory to process resident memory and calculate process memory utilization as a percentage. """ rss = self._platform_impl.get_memory_info()[0] try: return (rss / float(TOTAL_PHYMEM)) * 100 except ZeroDivisionError: return 0.0
def get_memory_percent(self): """Compare physical system memory to process resident memory and calculate process memory utilization as a percentage. """ rss = self._platform_impl.get_memory_info()[0] try: return (rss / float(TOTAL_PHYMEM)) * 100 except ZeroDivisionError: return 0.0
[ "Compare", "physical", "system", "memory", "to", "process", "resident", "memory", "and", "calculate", "process", "memory", "utilization", "as", "a", "percentage", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L546-L554
[ "def", "get_memory_percent", "(", "self", ")", ":", "rss", "=", "self", ".", "_platform_impl", ".", "get_memory_info", "(", ")", "[", "0", "]", "try", ":", "return", "(", "rss", "/", "float", "(", "TOTAL_PHYMEM", ")", ")", "*", "100", "except", "ZeroDivisionError", ":", "return", "0.0" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_memory_maps
Return process's mapped memory regions as a list of nameduples whose fields are variable depending on the platform. If 'grouped' is True the mapped regions with the same 'path' are grouped together and the different memory fields are summed. If 'grouped' is False every mapped region is shown as a single entity and the namedtuple will also include the mapped region's address space ('addr') and permission set ('perms').
environment/lib/python2.7/site-packages/psutil/__init__.py
def get_memory_maps(self, grouped=True): """Return process's mapped memory regions as a list of nameduples whose fields are variable depending on the platform. If 'grouped' is True the mapped regions with the same 'path' are grouped together and the different memory fields are summed. If 'grouped' is False every mapped region is shown as a single entity and the namedtuple will also include the mapped region's address space ('addr') and permission set ('perms'). """ it = self._platform_impl.get_memory_maps() if grouped: d = {} for tupl in it: path = tupl[2] nums = tupl[3:] try: d[path] = map(lambda x, y: x+y, d[path], nums) except KeyError: d[path] = nums nt = self._platform_impl.nt_mmap_grouped return [nt(path, *d[path]) for path in d] else: nt = self._platform_impl.nt_mmap_ext return [nt(*x) for x in it]
def get_memory_maps(self, grouped=True): """Return process's mapped memory regions as a list of nameduples whose fields are variable depending on the platform. If 'grouped' is True the mapped regions with the same 'path' are grouped together and the different memory fields are summed. If 'grouped' is False every mapped region is shown as a single entity and the namedtuple will also include the mapped region's address space ('addr') and permission set ('perms'). """ it = self._platform_impl.get_memory_maps() if grouped: d = {} for tupl in it: path = tupl[2] nums = tupl[3:] try: d[path] = map(lambda x, y: x+y, d[path], nums) except KeyError: d[path] = nums nt = self._platform_impl.nt_mmap_grouped return [nt(path, *d[path]) for path in d] else: nt = self._platform_impl.nt_mmap_ext return [nt(*x) for x in it]
[ "Return", "process", "s", "mapped", "memory", "regions", "as", "a", "list", "of", "nameduples", "whose", "fields", "are", "variable", "depending", "on", "the", "platform", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L556-L581
[ "def", "get_memory_maps", "(", "self", ",", "grouped", "=", "True", ")", ":", "it", "=", "self", ".", "_platform_impl", ".", "get_memory_maps", "(", ")", "if", "grouped", ":", "d", "=", "{", "}", "for", "tupl", "in", "it", ":", "path", "=", "tupl", "[", "2", "]", "nums", "=", "tupl", "[", "3", ":", "]", "try", ":", "d", "[", "path", "]", "=", "map", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "d", "[", "path", "]", ",", "nums", ")", "except", "KeyError", ":", "d", "[", "path", "]", "=", "nums", "nt", "=", "self", ".", "_platform_impl", ".", "nt_mmap_grouped", "return", "[", "nt", "(", "path", ",", "*", "d", "[", "path", "]", ")", "for", "path", "in", "d", "]", "else", ":", "nt", "=", "self", ".", "_platform_impl", ".", "nt_mmap_ext", "return", "[", "nt", "(", "*", "x", ")", "for", "x", "in", "it", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.is_running
Return whether this process is running.
environment/lib/python2.7/site-packages/psutil/__init__.py
def is_running(self): """Return whether this process is running.""" if self._gone: return False try: # Checking if pid is alive is not enough as the pid might # have been reused by another process. # pid + creation time, on the other hand, is supposed to # identify a process univocally. return self.create_time == \ self._platform_impl.get_process_create_time() except NoSuchProcess: self._gone = True return False
def is_running(self): """Return whether this process is running.""" if self._gone: return False try: # Checking if pid is alive is not enough as the pid might # have been reused by another process. # pid + creation time, on the other hand, is supposed to # identify a process univocally. return self.create_time == \ self._platform_impl.get_process_create_time() except NoSuchProcess: self._gone = True return False
[ "Return", "whether", "this", "process", "is", "running", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L609-L622
[ "def", "is_running", "(", "self", ")", ":", "if", "self", ".", "_gone", ":", "return", "False", "try", ":", "# Checking if pid is alive is not enough as the pid might", "# have been reused by another process.", "# pid + creation time, on the other hand, is supposed to", "# identify a process univocally.", "return", "self", ".", "create_time", "==", "self", ".", "_platform_impl", ".", "get_process_create_time", "(", ")", "except", "NoSuchProcess", ":", "self", ".", "_gone", "=", "True", "return", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.send_signal
Send a signal to process (see signal module constants). On Windows only SIGTERM is valid and is treated as an alias for kill().
environment/lib/python2.7/site-packages/psutil/__init__.py
def send_signal(self, sig): """Send a signal to process (see signal module constants). On Windows only SIGTERM is valid and is treated as an alias for kill(). """ # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) if os.name == 'posix': try: os.kill(self.pid, sig) except OSError: err = sys.exc_info()[1] name = self._platform_impl._process_name if err.errno == errno.ESRCH: raise NoSuchProcess(self.pid, name) if err.errno == errno.EPERM: raise AccessDenied(self.pid, name) raise else: if sig == signal.SIGTERM: self._platform_impl.kill_process() else: raise ValueError("only SIGTERM is supported on Windows")
def send_signal(self, sig): """Send a signal to process (see signal module constants). On Windows only SIGTERM is valid and is treated as an alias for kill(). """ # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) if os.name == 'posix': try: os.kill(self.pid, sig) except OSError: err = sys.exc_info()[1] name = self._platform_impl._process_name if err.errno == errno.ESRCH: raise NoSuchProcess(self.pid, name) if err.errno == errno.EPERM: raise AccessDenied(self.pid, name) raise else: if sig == signal.SIGTERM: self._platform_impl.kill_process() else: raise ValueError("only SIGTERM is supported on Windows")
[ "Send", "a", "signal", "to", "process", "(", "see", "signal", "module", "constants", ")", ".", "On", "Windows", "only", "SIGTERM", "is", "valid", "and", "is", "treated", "as", "an", "alias", "for", "kill", "()", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L624-L649
[ "def", "send_signal", "(", "self", ",", "sig", ")", ":", "# safety measure in case the current process has been killed in", "# meantime and the kernel reused its PID", "if", "not", "self", ".", "is_running", "(", ")", ":", "name", "=", "self", ".", "_platform_impl", ".", "_process_name", "raise", "NoSuchProcess", "(", "self", ".", "pid", ",", "name", ")", "if", "os", ".", "name", "==", "'posix'", ":", "try", ":", "os", ".", "kill", "(", "self", ".", "pid", ",", "sig", ")", "except", "OSError", ":", "err", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "name", "=", "self", ".", "_platform_impl", ".", "_process_name", "if", "err", ".", "errno", "==", "errno", ".", "ESRCH", ":", "raise", "NoSuchProcess", "(", "self", ".", "pid", ",", "name", ")", "if", "err", ".", "errno", "==", "errno", ".", "EPERM", ":", "raise", "AccessDenied", "(", "self", ".", "pid", ",", "name", ")", "raise", "else", ":", "if", "sig", "==", "signal", ".", "SIGTERM", ":", "self", ".", "_platform_impl", ".", "kill_process", "(", ")", "else", ":", "raise", "ValueError", "(", "\"only SIGTERM is supported on Windows\"", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.suspend
Suspend process execution.
environment/lib/python2.7/site-packages/psutil/__init__.py
def suspend(self): """Suspend process execution.""" # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) # windows if hasattr(self._platform_impl, "suspend_process"): self._platform_impl.suspend_process() else: # posix self.send_signal(signal.SIGSTOP)
def suspend(self): """Suspend process execution.""" # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) # windows if hasattr(self._platform_impl, "suspend_process"): self._platform_impl.suspend_process() else: # posix self.send_signal(signal.SIGSTOP)
[ "Suspend", "process", "execution", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L651-L663
[ "def", "suspend", "(", "self", ")", ":", "# safety measure in case the current process has been killed in", "# meantime and the kernel reused its PID", "if", "not", "self", ".", "is_running", "(", ")", ":", "name", "=", "self", ".", "_platform_impl", ".", "_process_name", "raise", "NoSuchProcess", "(", "self", ".", "pid", ",", "name", ")", "# windows", "if", "hasattr", "(", "self", ".", "_platform_impl", ",", "\"suspend_process\"", ")", ":", "self", ".", "_platform_impl", ".", "suspend_process", "(", ")", "else", ":", "# posix", "self", ".", "send_signal", "(", "signal", ".", "SIGSTOP", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.resume
Resume process execution.
environment/lib/python2.7/site-packages/psutil/__init__.py
def resume(self): """Resume process execution.""" # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) # windows if hasattr(self._platform_impl, "resume_process"): self._platform_impl.resume_process() else: # posix self.send_signal(signal.SIGCONT)
def resume(self): """Resume process execution.""" # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) # windows if hasattr(self._platform_impl, "resume_process"): self._platform_impl.resume_process() else: # posix self.send_signal(signal.SIGCONT)
[ "Resume", "process", "execution", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L665-L677
[ "def", "resume", "(", "self", ")", ":", "# safety measure in case the current process has been killed in", "# meantime and the kernel reused its PID", "if", "not", "self", ".", "is_running", "(", ")", ":", "name", "=", "self", ".", "_platform_impl", ".", "_process_name", "raise", "NoSuchProcess", "(", "self", ".", "pid", ",", "name", ")", "# windows", "if", "hasattr", "(", "self", ".", "_platform_impl", ",", "\"resume_process\"", ")", ":", "self", ".", "_platform_impl", ".", "resume_process", "(", ")", "else", ":", "# posix", "self", ".", "send_signal", "(", "signal", ".", "SIGCONT", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.kill
Kill the current process.
environment/lib/python2.7/site-packages/psutil/__init__.py
def kill(self): """Kill the current process.""" # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) if os.name == 'posix': self.send_signal(signal.SIGKILL) else: self._platform_impl.kill_process()
def kill(self): """Kill the current process.""" # safety measure in case the current process has been killed in # meantime and the kernel reused its PID if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) if os.name == 'posix': self.send_signal(signal.SIGKILL) else: self._platform_impl.kill_process()
[ "Kill", "the", "current", "process", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L685-L695
[ "def", "kill", "(", "self", ")", ":", "# safety measure in case the current process has been killed in", "# meantime and the kernel reused its PID", "if", "not", "self", ".", "is_running", "(", ")", ":", "name", "=", "self", ".", "_platform_impl", ".", "_process_name", "raise", "NoSuchProcess", "(", "self", ".", "pid", ",", "name", ")", "if", "os", ".", "name", "==", "'posix'", ":", "self", ".", "send_signal", "(", "signal", ".", "SIGKILL", ")", "else", ":", "self", ".", "_platform_impl", ".", "kill_process", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.wait
Wait for process to terminate and, if process is a children of the current one also return its exit code, else None.
environment/lib/python2.7/site-packages/psutil/__init__.py
def wait(self, timeout=None): """Wait for process to terminate and, if process is a children of the current one also return its exit code, else None. """ if timeout is not None and not timeout >= 0: raise ValueError("timeout must be a positive integer") return self._platform_impl.process_wait(timeout)
def wait(self, timeout=None): """Wait for process to terminate and, if process is a children of the current one also return its exit code, else None. """ if timeout is not None and not timeout >= 0: raise ValueError("timeout must be a positive integer") return self._platform_impl.process_wait(timeout)
[ "Wait", "for", "process", "to", "terminate", "and", "if", "process", "is", "a", "children", "of", "the", "current", "one", "also", "return", "its", "exit", "code", "else", "None", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L697-L703
[ "def", "wait", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", "is", "not", "None", "and", "not", "timeout", ">=", "0", ":", "raise", "ValueError", "(", "\"timeout must be a positive integer\"", ")", "return", "self", ".", "_platform_impl", ".", "process_wait", "(", "timeout", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.nice
Get or set process niceness (priority). Deprecated, use get_nice() instead.
environment/lib/python2.7/site-packages/psutil/__init__.py
def nice(self): """Get or set process niceness (priority). Deprecated, use get_nice() instead. """ msg = "this property is deprecated; use Process.get_nice() method instead" warnings.warn(msg, category=DeprecationWarning, stacklevel=2) return self.get_nice()
def nice(self): """Get or set process niceness (priority). Deprecated, use get_nice() instead. """ msg = "this property is deprecated; use Process.get_nice() method instead" warnings.warn(msg, category=DeprecationWarning, stacklevel=2) return self.get_nice()
[ "Get", "or", "set", "process", "niceness", "(", "priority", ")", ".", "Deprecated", "use", "get_nice", "()", "instead", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L708-L714
[ "def", "nice", "(", "self", ")", ":", "msg", "=", "\"this property is deprecated; use Process.get_nice() method instead\"", "warnings", ".", "warn", "(", "msg", ",", "category", "=", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "return", "self", ".", "get_nice", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
GTKEmbed._wire_kernel
Initializes the kernel inside GTK. This is meant to run only once at startup, so it does its job and returns False to ensure it doesn't get run again by GTK.
environment/lib/python2.7/site-packages/IPython/zmq/gui/gtkembed.py
def _wire_kernel(self): """Initializes the kernel inside GTK. This is meant to run only once at startup, so it does its job and returns False to ensure it doesn't get run again by GTK. """ self.gtk_main, self.gtk_main_quit = self._hijack_gtk() gobject.timeout_add(int(1000*self.kernel._poll_interval), self.iterate_kernel) return False
def _wire_kernel(self): """Initializes the kernel inside GTK. This is meant to run only once at startup, so it does its job and returns False to ensure it doesn't get run again by GTK. """ self.gtk_main, self.gtk_main_quit = self._hijack_gtk() gobject.timeout_add(int(1000*self.kernel._poll_interval), self.iterate_kernel) return False
[ "Initializes", "the", "kernel", "inside", "GTK", ".", "This", "is", "meant", "to", "run", "only", "once", "at", "startup", "so", "it", "does", "its", "job", "and", "returns", "False", "to", "ensure", "it", "doesn", "t", "get", "run", "again", "by", "GTK", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/gui/gtkembed.py#L40-L49
[ "def", "_wire_kernel", "(", "self", ")", ":", "self", ".", "gtk_main", ",", "self", ".", "gtk_main_quit", "=", "self", ".", "_hijack_gtk", "(", ")", "gobject", ".", "timeout_add", "(", "int", "(", "1000", "*", "self", ".", "kernel", ".", "_poll_interval", ")", ",", "self", ".", "iterate_kernel", ")", "return", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
GTKEmbed._hijack_gtk
Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt to start or stop Returns ------- The original functions that have been hijacked: - gtk.main - gtk.main_quit
environment/lib/python2.7/site-packages/IPython/zmq/gui/gtkembed.py
def _hijack_gtk(self): """Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt to start or stop Returns ------- The original functions that have been hijacked: - gtk.main - gtk.main_quit """ def dummy(*args, **kw): pass # save and trap main and main_quit from gtk orig_main, gtk.main = gtk.main, dummy orig_main_quit, gtk.main_quit = gtk.main_quit, dummy return orig_main, orig_main_quit
def _hijack_gtk(self): """Hijack a few key functions in GTK for IPython integration. Modifies pyGTK's main and main_quit with a dummy so user code does not block IPython. This allows us to use %run to run arbitrary pygtk scripts from a long-lived IPython session, and when they attempt to start or stop Returns ------- The original functions that have been hijacked: - gtk.main - gtk.main_quit """ def dummy(*args, **kw): pass # save and trap main and main_quit from gtk orig_main, gtk.main = gtk.main, dummy orig_main_quit, gtk.main_quit = gtk.main_quit, dummy return orig_main, orig_main_quit
[ "Hijack", "a", "few", "key", "functions", "in", "GTK", "for", "IPython", "integration", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/gui/gtkembed.py#L67-L86
[ "def", "_hijack_gtk", "(", "self", ")", ":", "def", "dummy", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "pass", "# save and trap main and main_quit from gtk", "orig_main", ",", "gtk", ".", "main", "=", "gtk", ".", "main", ",", "dummy", "orig_main_quit", ",", "gtk", ".", "main_quit", "=", "gtk", ".", "main_quit", ",", "dummy", "return", "orig_main", ",", "orig_main_quit" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
is_shadowed
Is the given identifier defined in one of the namespaces which shadow the alias and magic namespaces? Note that an identifier is different than ifun, because it can not contain a '.' character.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def is_shadowed(identifier, ip): """Is the given identifier defined in one of the namespaces which shadow the alias and magic namespaces? Note that an identifier is different than ifun, because it can not contain a '.' character.""" # This is much safer than calling ofind, which can change state return (identifier in ip.user_ns \ or identifier in ip.user_global_ns \ or identifier in ip.ns_table['builtin'])
def is_shadowed(identifier, ip): """Is the given identifier defined in one of the namespaces which shadow the alias and magic namespaces? Note that an identifier is different than ifun, because it can not contain a '.' character.""" # This is much safer than calling ofind, which can change state return (identifier in ip.user_ns \ or identifier in ip.user_global_ns \ or identifier in ip.ns_table['builtin'])
[ "Is", "the", "given", "identifier", "defined", "in", "one", "of", "the", "namespaces", "which", "shadow", "the", "alias", "and", "magic", "namespaces?", "Note", "that", "an", "identifier", "is", "different", "than", "ifun", "because", "it", "can", "not", "contain", "a", ".", "character", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L85-L92
[ "def", "is_shadowed", "(", "identifier", ",", "ip", ")", ":", "# This is much safer than calling ofind, which can change state", "return", "(", "identifier", "in", "ip", ".", "user_ns", "or", "identifier", "in", "ip", ".", "user_global_ns", "or", "identifier", "in", "ip", ".", "ns_table", "[", "'builtin'", "]", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.init_transformers
Create the default transformers.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def init_transformers(self): """Create the default transformers.""" self._transformers = [] for transformer_cls in _default_transformers: transformer_cls( shell=self.shell, prefilter_manager=self, config=self.config )
def init_transformers(self): """Create the default transformers.""" self._transformers = [] for transformer_cls in _default_transformers: transformer_cls( shell=self.shell, prefilter_manager=self, config=self.config )
[ "Create", "the", "default", "transformers", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L153-L159
[ "def", "init_transformers", "(", "self", ")", ":", "self", ".", "_transformers", "=", "[", "]", "for", "transformer_cls", "in", "_default_transformers", ":", "transformer_cls", "(", "shell", "=", "self", ".", "shell", ",", "prefilter_manager", "=", "self", ",", "config", "=", "self", ".", "config", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.register_transformer
Register a transformer instance.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def register_transformer(self, transformer): """Register a transformer instance.""" if transformer not in self._transformers: self._transformers.append(transformer) self.sort_transformers()
def register_transformer(self, transformer): """Register a transformer instance.""" if transformer not in self._transformers: self._transformers.append(transformer) self.sort_transformers()
[ "Register", "a", "transformer", "instance", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L174-L178
[ "def", "register_transformer", "(", "self", ",", "transformer", ")", ":", "if", "transformer", "not", "in", "self", ".", "_transformers", ":", "self", ".", "_transformers", ".", "append", "(", "transformer", ")", "self", ".", "sort_transformers", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.unregister_transformer
Unregister a transformer instance.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def unregister_transformer(self, transformer): """Unregister a transformer instance.""" if transformer in self._transformers: self._transformers.remove(transformer)
def unregister_transformer(self, transformer): """Unregister a transformer instance.""" if transformer in self._transformers: self._transformers.remove(transformer)
[ "Unregister", "a", "transformer", "instance", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L180-L183
[ "def", "unregister_transformer", "(", "self", ",", "transformer", ")", ":", "if", "transformer", "in", "self", ".", "_transformers", ":", "self", ".", "_transformers", ".", "remove", "(", "transformer", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.init_checkers
Create the default checkers.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def init_checkers(self): """Create the default checkers.""" self._checkers = [] for checker in _default_checkers: checker( shell=self.shell, prefilter_manager=self, config=self.config )
def init_checkers(self): """Create the default checkers.""" self._checkers = [] for checker in _default_checkers: checker( shell=self.shell, prefilter_manager=self, config=self.config )
[ "Create", "the", "default", "checkers", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L189-L195
[ "def", "init_checkers", "(", "self", ")", ":", "self", ".", "_checkers", "=", "[", "]", "for", "checker", "in", "_default_checkers", ":", "checker", "(", "shell", "=", "self", ".", "shell", ",", "prefilter_manager", "=", "self", ",", "config", "=", "self", ".", "config", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.register_checker
Register a checker instance.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def register_checker(self, checker): """Register a checker instance.""" if checker not in self._checkers: self._checkers.append(checker) self.sort_checkers()
def register_checker(self, checker): """Register a checker instance.""" if checker not in self._checkers: self._checkers.append(checker) self.sort_checkers()
[ "Register", "a", "checker", "instance", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L210-L214
[ "def", "register_checker", "(", "self", ",", "checker", ")", ":", "if", "checker", "not", "in", "self", ".", "_checkers", ":", "self", ".", "_checkers", ".", "append", "(", "checker", ")", "self", ".", "sort_checkers", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.unregister_checker
Unregister a checker instance.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def unregister_checker(self, checker): """Unregister a checker instance.""" if checker in self._checkers: self._checkers.remove(checker)
def unregister_checker(self, checker): """Unregister a checker instance.""" if checker in self._checkers: self._checkers.remove(checker)
[ "Unregister", "a", "checker", "instance", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L216-L219
[ "def", "unregister_checker", "(", "self", ",", "checker", ")", ":", "if", "checker", "in", "self", ".", "_checkers", ":", "self", ".", "_checkers", ".", "remove", "(", "checker", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.init_handlers
Create the default handlers.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def init_handlers(self): """Create the default handlers.""" self._handlers = {} self._esc_handlers = {} for handler in _default_handlers: handler( shell=self.shell, prefilter_manager=self, config=self.config )
def init_handlers(self): """Create the default handlers.""" self._handlers = {} self._esc_handlers = {} for handler in _default_handlers: handler( shell=self.shell, prefilter_manager=self, config=self.config )
[ "Create", "the", "default", "handlers", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L225-L232
[ "def", "init_handlers", "(", "self", ")", ":", "self", ".", "_handlers", "=", "{", "}", "self", ".", "_esc_handlers", "=", "{", "}", "for", "handler", "in", "_default_handlers", ":", "handler", "(", "shell", "=", "self", ".", "shell", ",", "prefilter_manager", "=", "self", ",", "config", "=", "self", ".", "config", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.register_handler
Register a handler instance by name with esc_strings.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def register_handler(self, name, handler, esc_strings): """Register a handler instance by name with esc_strings.""" self._handlers[name] = handler for esc_str in esc_strings: self._esc_handlers[esc_str] = handler
def register_handler(self, name, handler, esc_strings): """Register a handler instance by name with esc_strings.""" self._handlers[name] = handler for esc_str in esc_strings: self._esc_handlers[esc_str] = handler
[ "Register", "a", "handler", "instance", "by", "name", "with", "esc_strings", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L239-L243
[ "def", "register_handler", "(", "self", ",", "name", ",", "handler", ",", "esc_strings", ")", ":", "self", ".", "_handlers", "[", "name", "]", "=", "handler", "for", "esc_str", "in", "esc_strings", ":", "self", ".", "_esc_handlers", "[", "esc_str", "]", "=", "handler" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.unregister_handler
Unregister a handler instance by name with esc_strings.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def unregister_handler(self, name, handler, esc_strings): """Unregister a handler instance by name with esc_strings.""" try: del self._handlers[name] except KeyError: pass for esc_str in esc_strings: h = self._esc_handlers.get(esc_str) if h is handler: del self._esc_handlers[esc_str]
def unregister_handler(self, name, handler, esc_strings): """Unregister a handler instance by name with esc_strings.""" try: del self._handlers[name] except KeyError: pass for esc_str in esc_strings: h = self._esc_handlers.get(esc_str) if h is handler: del self._esc_handlers[esc_str]
[ "Unregister", "a", "handler", "instance", "by", "name", "with", "esc_strings", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L245-L254
[ "def", "unregister_handler", "(", "self", ",", "name", ",", "handler", ",", "esc_strings", ")", ":", "try", ":", "del", "self", ".", "_handlers", "[", "name", "]", "except", "KeyError", ":", "pass", "for", "esc_str", "in", "esc_strings", ":", "h", "=", "self", ".", "_esc_handlers", ".", "get", "(", "esc_str", ")", "if", "h", "is", "handler", ":", "del", "self", ".", "_esc_handlers", "[", "esc_str", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.prefilter_line_info
Prefilter a line that has been converted to a LineInfo object. This implements the checker/handler part of the prefilter pipe.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def prefilter_line_info(self, line_info): """Prefilter a line that has been converted to a LineInfo object. This implements the checker/handler part of the prefilter pipe. """ # print "prefilter_line_info: ", line_info handler = self.find_handler(line_info) return handler.handle(line_info)
def prefilter_line_info(self, line_info): """Prefilter a line that has been converted to a LineInfo object. This implements the checker/handler part of the prefilter pipe. """ # print "prefilter_line_info: ", line_info handler = self.find_handler(line_info) return handler.handle(line_info)
[ "Prefilter", "a", "line", "that", "has", "been", "converted", "to", "a", "LineInfo", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L268-L275
[ "def", "prefilter_line_info", "(", "self", ",", "line_info", ")", ":", "# print \"prefilter_line_info: \", line_info", "handler", "=", "self", ".", "find_handler", "(", "line_info", ")", "return", "handler", ".", "handle", "(", "line_info", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.find_handler
Find a handler for the line_info by trying checkers.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def find_handler(self, line_info): """Find a handler for the line_info by trying checkers.""" for checker in self.checkers: if checker.enabled: handler = checker.check(line_info) if handler: return handler return self.get_handler_by_name('normal')
def find_handler(self, line_info): """Find a handler for the line_info by trying checkers.""" for checker in self.checkers: if checker.enabled: handler = checker.check(line_info) if handler: return handler return self.get_handler_by_name('normal')
[ "Find", "a", "handler", "for", "the", "line_info", "by", "trying", "checkers", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L277-L284
[ "def", "find_handler", "(", "self", ",", "line_info", ")", ":", "for", "checker", "in", "self", ".", "checkers", ":", "if", "checker", ".", "enabled", ":", "handler", "=", "checker", ".", "check", "(", "line_info", ")", "if", "handler", ":", "return", "handler", "return", "self", ".", "get_handler_by_name", "(", "'normal'", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.transform_line
Calls the enabled transformers in order of increasing priority.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def transform_line(self, line, continue_prompt): """Calls the enabled transformers in order of increasing priority.""" for transformer in self.transformers: if transformer.enabled: line = transformer.transform(line, continue_prompt) return line
def transform_line(self, line, continue_prompt): """Calls the enabled transformers in order of increasing priority.""" for transformer in self.transformers: if transformer.enabled: line = transformer.transform(line, continue_prompt) return line
[ "Calls", "the", "enabled", "transformers", "in", "order", "of", "increasing", "priority", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L286-L291
[ "def", "transform_line", "(", "self", ",", "line", ",", "continue_prompt", ")", ":", "for", "transformer", "in", "self", ".", "transformers", ":", "if", "transformer", ".", "enabled", ":", "line", "=", "transformer", ".", "transform", "(", "line", ",", "continue_prompt", ")", "return", "line" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.prefilter_line
Prefilter a single input line as text. This method prefilters a single line of text by calling the transformers and then the checkers/handlers.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def prefilter_line(self, line, continue_prompt=False): """Prefilter a single input line as text. This method prefilters a single line of text by calling the transformers and then the checkers/handlers. """ # print "prefilter_line: ", line, continue_prompt # All handlers *must* return a value, even if it's blank (''). # save the line away in case we crash, so the post-mortem handler can # record it self.shell._last_input_line = line if not line: # Return immediately on purely empty lines, so that if the user # previously typed some whitespace that started a continuation # prompt, he can break out of that loop with just an empty line. # This is how the default python prompt works. return '' # At this point, we invoke our transformers. if not continue_prompt or (continue_prompt and self.multi_line_specials): line = self.transform_line(line, continue_prompt) # Now we compute line_info for the checkers and handlers line_info = LineInfo(line, continue_prompt) # the input history needs to track even empty lines stripped = line.strip() normal_handler = self.get_handler_by_name('normal') if not stripped: if not continue_prompt: self.shell.displayhook.prompt_count -= 1 return normal_handler.handle(line_info) # special handlers are only allowed for single line statements if continue_prompt and not self.multi_line_specials: return normal_handler.handle(line_info) prefiltered = self.prefilter_line_info(line_info) # print "prefiltered line: %r" % prefiltered return prefiltered
def prefilter_line(self, line, continue_prompt=False): """Prefilter a single input line as text. This method prefilters a single line of text by calling the transformers and then the checkers/handlers. """ # print "prefilter_line: ", line, continue_prompt # All handlers *must* return a value, even if it's blank (''). # save the line away in case we crash, so the post-mortem handler can # record it self.shell._last_input_line = line if not line: # Return immediately on purely empty lines, so that if the user # previously typed some whitespace that started a continuation # prompt, he can break out of that loop with just an empty line. # This is how the default python prompt works. return '' # At this point, we invoke our transformers. if not continue_prompt or (continue_prompt and self.multi_line_specials): line = self.transform_line(line, continue_prompt) # Now we compute line_info for the checkers and handlers line_info = LineInfo(line, continue_prompt) # the input history needs to track even empty lines stripped = line.strip() normal_handler = self.get_handler_by_name('normal') if not stripped: if not continue_prompt: self.shell.displayhook.prompt_count -= 1 return normal_handler.handle(line_info) # special handlers are only allowed for single line statements if continue_prompt and not self.multi_line_specials: return normal_handler.handle(line_info) prefiltered = self.prefilter_line_info(line_info) # print "prefiltered line: %r" % prefiltered return prefiltered
[ "Prefilter", "a", "single", "input", "line", "as", "text", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L293-L337
[ "def", "prefilter_line", "(", "self", ",", "line", ",", "continue_prompt", "=", "False", ")", ":", "# print \"prefilter_line: \", line, continue_prompt", "# All handlers *must* return a value, even if it's blank ('').", "# save the line away in case we crash, so the post-mortem handler can", "# record it", "self", ".", "shell", ".", "_last_input_line", "=", "line", "if", "not", "line", ":", "# Return immediately on purely empty lines, so that if the user", "# previously typed some whitespace that started a continuation", "# prompt, he can break out of that loop with just an empty line.", "# This is how the default python prompt works.", "return", "''", "# At this point, we invoke our transformers.", "if", "not", "continue_prompt", "or", "(", "continue_prompt", "and", "self", ".", "multi_line_specials", ")", ":", "line", "=", "self", ".", "transform_line", "(", "line", ",", "continue_prompt", ")", "# Now we compute line_info for the checkers and handlers", "line_info", "=", "LineInfo", "(", "line", ",", "continue_prompt", ")", "# the input history needs to track even empty lines", "stripped", "=", "line", ".", "strip", "(", ")", "normal_handler", "=", "self", ".", "get_handler_by_name", "(", "'normal'", ")", "if", "not", "stripped", ":", "if", "not", "continue_prompt", ":", "self", ".", "shell", ".", "displayhook", ".", "prompt_count", "-=", "1", "return", "normal_handler", ".", "handle", "(", "line_info", ")", "# special handlers are only allowed for single line statements", "if", "continue_prompt", "and", "not", "self", ".", "multi_line_specials", ":", "return", "normal_handler", ".", "handle", "(", "line_info", ")", "prefiltered", "=", "self", ".", "prefilter_line_info", "(", "line_info", ")", "# print \"prefiltered line: %r\" % prefiltered", "return", "prefiltered" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterManager.prefilter_lines
Prefilter multiple input lines of text. This is the main entry point for prefiltering multiple lines of input. This simply calls :meth:`prefilter_line` for each line of input. This covers cases where there are multiple lines in the user entry, which is the case when the user goes back to a multiline history entry and presses enter.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def prefilter_lines(self, lines, continue_prompt=False): """Prefilter multiple input lines of text. This is the main entry point for prefiltering multiple lines of input. This simply calls :meth:`prefilter_line` for each line of input. This covers cases where there are multiple lines in the user entry, which is the case when the user goes back to a multiline history entry and presses enter. """ llines = lines.rstrip('\n').split('\n') # We can get multiple lines in one shot, where multiline input 'blends' # into one line, in cases like recalling from the readline history # buffer. We need to make sure that in such cases, we correctly # communicate downstream which line is first and which are continuation # ones. if len(llines) > 1: out = '\n'.join([self.prefilter_line(line, lnum>0) for lnum, line in enumerate(llines) ]) else: out = self.prefilter_line(llines[0], continue_prompt) return out
def prefilter_lines(self, lines, continue_prompt=False): """Prefilter multiple input lines of text. This is the main entry point for prefiltering multiple lines of input. This simply calls :meth:`prefilter_line` for each line of input. This covers cases where there are multiple lines in the user entry, which is the case when the user goes back to a multiline history entry and presses enter. """ llines = lines.rstrip('\n').split('\n') # We can get multiple lines in one shot, where multiline input 'blends' # into one line, in cases like recalling from the readline history # buffer. We need to make sure that in such cases, we correctly # communicate downstream which line is first and which are continuation # ones. if len(llines) > 1: out = '\n'.join([self.prefilter_line(line, lnum>0) for lnum, line in enumerate(llines) ]) else: out = self.prefilter_line(llines[0], continue_prompt) return out
[ "Prefilter", "multiple", "input", "lines", "of", "text", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L339-L362
[ "def", "prefilter_lines", "(", "self", ",", "lines", ",", "continue_prompt", "=", "False", ")", ":", "llines", "=", "lines", ".", "rstrip", "(", "'\\n'", ")", ".", "split", "(", "'\\n'", ")", "# We can get multiple lines in one shot, where multiline input 'blends'", "# into one line, in cases like recalling from the readline history", "# buffer. We need to make sure that in such cases, we correctly", "# communicate downstream which line is first and which are continuation", "# ones.", "if", "len", "(", "llines", ")", ">", "1", ":", "out", "=", "'\\n'", ".", "join", "(", "[", "self", ".", "prefilter_line", "(", "line", ",", "lnum", ">", "0", ")", "for", "lnum", ",", "line", "in", "enumerate", "(", "llines", ")", "]", ")", "else", ":", "out", "=", "self", ".", "prefilter_line", "(", "llines", "[", "0", "]", ",", "continue_prompt", ")", "return", "out" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPyAutocallChecker.check
Instances of IPyAutocall in user_ns get autocalled immediately
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def check(self, line_info): "Instances of IPyAutocall in user_ns get autocalled immediately" obj = self.shell.user_ns.get(line_info.ifun, None) if isinstance(obj, IPyAutocall): obj.set_ip(self.shell) return self.prefilter_manager.get_handler_by_name('auto') else: return None
def check(self, line_info): "Instances of IPyAutocall in user_ns get autocalled immediately" obj = self.shell.user_ns.get(line_info.ifun, None) if isinstance(obj, IPyAutocall): obj.set_ip(self.shell) return self.prefilter_manager.get_handler_by_name('auto') else: return None
[ "Instances", "of", "IPyAutocall", "in", "user_ns", "get", "autocalled", "immediately" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L539-L546
[ "def", "check", "(", "self", ",", "line_info", ")", ":", "obj", "=", "self", ".", "shell", ".", "user_ns", ".", "get", "(", "line_info", ".", "ifun", ",", "None", ")", "if", "isinstance", "(", "obj", ",", "IPyAutocall", ")", ":", "obj", ".", "set_ip", "(", "self", ".", "shell", ")", "return", "self", ".", "prefilter_manager", ".", "get_handler_by_name", "(", "'auto'", ")", "else", ":", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MultiLineMagicChecker.check
Allow ! and !! in multi-line statements if multi_line_specials is on
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def check(self, line_info): "Allow ! and !! in multi-line statements if multi_line_specials is on" # Note that this one of the only places we check the first character of # ifun and *not* the pre_char. Also note that the below test matches # both ! and !!. if line_info.continue_prompt \ and self.prefilter_manager.multi_line_specials: if line_info.esc == ESC_MAGIC: return self.prefilter_manager.get_handler_by_name('magic') else: return None
def check(self, line_info): "Allow ! and !! in multi-line statements if multi_line_specials is on" # Note that this one of the only places we check the first character of # ifun and *not* the pre_char. Also note that the below test matches # both ! and !!. if line_info.continue_prompt \ and self.prefilter_manager.multi_line_specials: if line_info.esc == ESC_MAGIC: return self.prefilter_manager.get_handler_by_name('magic') else: return None
[ "Allow", "!", "and", "!!", "in", "multi", "-", "line", "statements", "if", "multi_line_specials", "is", "on" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L553-L563
[ "def", "check", "(", "self", ",", "line_info", ")", ":", "# Note that this one of the only places we check the first character of", "# ifun and *not* the pre_char. Also note that the below test matches", "# both ! and !!.", "if", "line_info", ".", "continue_prompt", "and", "self", ".", "prefilter_manager", ".", "multi_line_specials", ":", "if", "line_info", ".", "esc", "==", "ESC_MAGIC", ":", "return", "self", ".", "prefilter_manager", ".", "get_handler_by_name", "(", "'magic'", ")", "else", ":", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
EscCharsChecker.check
Check for escape character and return either a handler to handle it, or None if there is no escape char.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def check(self, line_info): """Check for escape character and return either a handler to handle it, or None if there is no escape char.""" if line_info.line[-1] == ESC_HELP \ and line_info.esc != ESC_SHELL \ and line_info.esc != ESC_SH_CAP: # the ? can be at the end, but *not* for either kind of shell escape, # because a ? can be a vaild final char in a shell cmd return self.prefilter_manager.get_handler_by_name('help') else: if line_info.pre: return None # This returns None like it should if no handler exists return self.prefilter_manager.get_handler_by_esc(line_info.esc)
def check(self, line_info): """Check for escape character and return either a handler to handle it, or None if there is no escape char.""" if line_info.line[-1] == ESC_HELP \ and line_info.esc != ESC_SHELL \ and line_info.esc != ESC_SH_CAP: # the ? can be at the end, but *not* for either kind of shell escape, # because a ? can be a vaild final char in a shell cmd return self.prefilter_manager.get_handler_by_name('help') else: if line_info.pre: return None # This returns None like it should if no handler exists return self.prefilter_manager.get_handler_by_esc(line_info.esc)
[ "Check", "for", "escape", "character", "and", "return", "either", "a", "handler", "to", "handle", "it", "or", "None", "if", "there", "is", "no", "escape", "char", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L570-L583
[ "def", "check", "(", "self", ",", "line_info", ")", ":", "if", "line_info", ".", "line", "[", "-", "1", "]", "==", "ESC_HELP", "and", "line_info", ".", "esc", "!=", "ESC_SHELL", "and", "line_info", ".", "esc", "!=", "ESC_SH_CAP", ":", "# the ? can be at the end, but *not* for either kind of shell escape,", "# because a ? can be a vaild final char in a shell cmd", "return", "self", ".", "prefilter_manager", ".", "get_handler_by_name", "(", "'help'", ")", "else", ":", "if", "line_info", ".", "pre", ":", "return", "None", "# This returns None like it should if no handler exists", "return", "self", ".", "prefilter_manager", ".", "get_handler_by_esc", "(", "line_info", ".", "esc", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AutoMagicChecker.check
If the ifun is magic, and automagic is on, run it. Note: normal, non-auto magic would already have been triggered via '%' in check_esc_chars. This just checks for automagic. Also, before triggering the magic handler, make sure that there is nothing in the user namespace which could shadow it.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def check(self, line_info): """If the ifun is magic, and automagic is on, run it. Note: normal, non-auto magic would already have been triggered via '%' in check_esc_chars. This just checks for automagic. Also, before triggering the magic handler, make sure that there is nothing in the user namespace which could shadow it.""" if not self.shell.automagic or not self.shell.find_magic(line_info.ifun): return None # We have a likely magic method. Make sure we should actually call it. if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: return None head = line_info.ifun.split('.',1)[0] if is_shadowed(head, self.shell): return None return self.prefilter_manager.get_handler_by_name('magic')
def check(self, line_info): """If the ifun is magic, and automagic is on, run it. Note: normal, non-auto magic would already have been triggered via '%' in check_esc_chars. This just checks for automagic. Also, before triggering the magic handler, make sure that there is nothing in the user namespace which could shadow it.""" if not self.shell.automagic or not self.shell.find_magic(line_info.ifun): return None # We have a likely magic method. Make sure we should actually call it. if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: return None head = line_info.ifun.split('.',1)[0] if is_shadowed(head, self.shell): return None return self.prefilter_manager.get_handler_by_name('magic')
[ "If", "the", "ifun", "is", "magic", "and", "automagic", "is", "on", "run", "it", ".", "Note", ":", "normal", "non", "-", "auto", "magic", "would", "already", "have", "been", "triggered", "via", "%", "in", "check_esc_chars", ".", "This", "just", "checks", "for", "automagic", ".", "Also", "before", "triggering", "the", "magic", "handler", "make", "sure", "that", "there", "is", "nothing", "in", "the", "user", "namespace", "which", "could", "shadow", "it", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L608-L625
[ "def", "check", "(", "self", ",", "line_info", ")", ":", "if", "not", "self", ".", "shell", ".", "automagic", "or", "not", "self", ".", "shell", ".", "find_magic", "(", "line_info", ".", "ifun", ")", ":", "return", "None", "# We have a likely magic method. Make sure we should actually call it.", "if", "line_info", ".", "continue_prompt", "and", "not", "self", ".", "prefilter_manager", ".", "multi_line_specials", ":", "return", "None", "head", "=", "line_info", ".", "ifun", ".", "split", "(", "'.'", ",", "1", ")", "[", "0", "]", "if", "is_shadowed", "(", "head", ",", "self", ".", "shell", ")", ":", "return", "None", "return", "self", ".", "prefilter_manager", ".", "get_handler_by_name", "(", "'magic'", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AliasChecker.check
Check if the initital identifier on the line is an alias.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def check(self, line_info): "Check if the initital identifier on the line is an alias." # Note: aliases can not contain '.' head = line_info.ifun.split('.',1)[0] if line_info.ifun not in self.shell.alias_manager \ or head not in self.shell.alias_manager \ or is_shadowed(head, self.shell): return None return self.prefilter_manager.get_handler_by_name('alias')
def check(self, line_info): "Check if the initital identifier on the line is an alias." # Note: aliases can not contain '.' head = line_info.ifun.split('.',1)[0] if line_info.ifun not in self.shell.alias_manager \ or head not in self.shell.alias_manager \ or is_shadowed(head, self.shell): return None return self.prefilter_manager.get_handler_by_name('alias')
[ "Check", "if", "the", "initital", "identifier", "on", "the", "line", "is", "an", "alias", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L632-L641
[ "def", "check", "(", "self", ",", "line_info", ")", ":", "# Note: aliases can not contain '.'", "head", "=", "line_info", ".", "ifun", ".", "split", "(", "'.'", ",", "1", ")", "[", "0", "]", "if", "line_info", ".", "ifun", "not", "in", "self", ".", "shell", ".", "alias_manager", "or", "head", "not", "in", "self", ".", "shell", ".", "alias_manager", "or", "is_shadowed", "(", "head", ",", "self", ".", "shell", ")", ":", "return", "None", "return", "self", ".", "prefilter_manager", ".", "get_handler_by_name", "(", "'alias'", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PythonOpsChecker.check
If the 'rest' of the line begins with a function call or pretty much any python operator, we should simply execute the line (regardless of whether or not there's a possible autocall expansion). This avoids spurious (and very confusing) geattr() accesses.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def check(self, line_info): """If the 'rest' of the line begins with a function call or pretty much any python operator, we should simply execute the line (regardless of whether or not there's a possible autocall expansion). This avoids spurious (and very confusing) geattr() accesses.""" if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': return self.prefilter_manager.get_handler_by_name('normal') else: return None
def check(self, line_info): """If the 'rest' of the line begins with a function call or pretty much any python operator, we should simply execute the line (regardless of whether or not there's a possible autocall expansion). This avoids spurious (and very confusing) geattr() accesses.""" if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': return self.prefilter_manager.get_handler_by_name('normal') else: return None
[ "If", "the", "rest", "of", "the", "line", "begins", "with", "a", "function", "call", "or", "pretty", "much", "any", "python", "operator", "we", "should", "simply", "execute", "the", "line", "(", "regardless", "of", "whether", "or", "not", "there", "s", "a", "possible", "autocall", "expansion", ")", ".", "This", "avoids", "spurious", "(", "and", "very", "confusing", ")", "geattr", "()", "accesses", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L648-L656
[ "def", "check", "(", "self", ",", "line_info", ")", ":", "if", "line_info", ".", "the_rest", "and", "line_info", ".", "the_rest", "[", "0", "]", "in", "'!=()<>,+*/%^&|'", ":", "return", "self", ".", "prefilter_manager", ".", "get_handler_by_name", "(", "'normal'", ")", "else", ":", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AutocallChecker.check
Check if the initial word/function is callable and autocall is on.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def check(self, line_info): "Check if the initial word/function is callable and autocall is on." if not self.shell.autocall: return None oinfo = line_info.ofind(self.shell) # This can mutate state via getattr if not oinfo['found']: return None if callable(oinfo['obj']) \ and (not self.exclude_regexp.match(line_info.the_rest)) \ and self.function_name_regexp.match(line_info.ifun): return self.prefilter_manager.get_handler_by_name('auto') else: return None
def check(self, line_info): "Check if the initial word/function is callable and autocall is on." if not self.shell.autocall: return None oinfo = line_info.ofind(self.shell) # This can mutate state via getattr if not oinfo['found']: return None if callable(oinfo['obj']) \ and (not self.exclude_regexp.match(line_info.the_rest)) \ and self.function_name_regexp.match(line_info.ifun): return self.prefilter_manager.get_handler_by_name('auto') else: return None
[ "Check", "if", "the", "initial", "word", "/", "function", "is", "callable", "and", "autocall", "is", "on", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L668-L682
[ "def", "check", "(", "self", ",", "line_info", ")", ":", "if", "not", "self", ".", "shell", ".", "autocall", ":", "return", "None", "oinfo", "=", "line_info", ".", "ofind", "(", "self", ".", "shell", ")", "# This can mutate state via getattr", "if", "not", "oinfo", "[", "'found'", "]", ":", "return", "None", "if", "callable", "(", "oinfo", "[", "'obj'", "]", ")", "and", "(", "not", "self", ".", "exclude_regexp", ".", "match", "(", "line_info", ".", "the_rest", ")", ")", "and", "self", ".", "function_name_regexp", ".", "match", "(", "line_info", ".", "ifun", ")", ":", "return", "self", ".", "prefilter_manager", ".", "get_handler_by_name", "(", "'auto'", ")", "else", ":", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PrefilterHandler.handle
Handle normal input lines. Use as a template for handlers.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def handle(self, line_info): # print "normal: ", line_info """Handle normal input lines. Use as a template for handlers.""" # With autoindent on, we need some way to exit the input loop, and I # don't want to force the user to have to backspace all the way to # clear the line. The rule will be in this case, that either two # lines of pure whitespace in a row, or a line of pure whitespace but # of a size different to the indent level, will exit the input loop. line = line_info.line continue_prompt = line_info.continue_prompt if (continue_prompt and self.shell.autoindent and line.isspace() and 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2): line = '' return line
def handle(self, line_info): # print "normal: ", line_info """Handle normal input lines. Use as a template for handlers.""" # With autoindent on, we need some way to exit the input loop, and I # don't want to force the user to have to backspace all the way to # clear the line. The rule will be in this case, that either two # lines of pure whitespace in a row, or a line of pure whitespace but # of a size different to the indent level, will exit the input loop. line = line_info.line continue_prompt = line_info.continue_prompt if (continue_prompt and self.shell.autoindent and line.isspace() and 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2): line = '' return line
[ "Handle", "normal", "input", "lines", ".", "Use", "as", "a", "template", "for", "handlers", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L707-L725
[ "def", "handle", "(", "self", ",", "line_info", ")", ":", "# print \"normal: \", line_info", "# With autoindent on, we need some way to exit the input loop, and I", "# don't want to force the user to have to backspace all the way to", "# clear the line. The rule will be in this case, that either two", "# lines of pure whitespace in a row, or a line of pure whitespace but", "# of a size different to the indent level, will exit the input loop.", "line", "=", "line_info", ".", "line", "continue_prompt", "=", "line_info", ".", "continue_prompt", "if", "(", "continue_prompt", "and", "self", ".", "shell", ".", "autoindent", "and", "line", ".", "isspace", "(", ")", "and", "0", "<", "abs", "(", "len", "(", "line", ")", "-", "self", ".", "shell", ".", "indent_current_nsp", ")", "<=", "2", ")", ":", "line", "=", "''", "return", "line" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AliasHandler.handle
Handle alias input lines.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def handle(self, line_info): """Handle alias input lines. """ transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) # pre is needed, because it carries the leading whitespace. Otherwise # aliases won't work in indented sections. line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, transformed) return line_out
def handle(self, line_info): """Handle alias input lines. """ transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) # pre is needed, because it carries the leading whitespace. Otherwise # aliases won't work in indented sections. line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, transformed) return line_out
[ "Handle", "alias", "input", "lines", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L735-L742
[ "def", "handle", "(", "self", ",", "line_info", ")", ":", "transformed", "=", "self", ".", "shell", ".", "alias_manager", ".", "expand_aliases", "(", "line_info", ".", "ifun", ",", "line_info", ".", "the_rest", ")", "# pre is needed, because it carries the leading whitespace. Otherwise", "# aliases won't work in indented sections.", "line_out", "=", "'%sget_ipython().system(%r)'", "%", "(", "line_info", ".", "pre_whitespace", ",", "transformed", ")", "return", "line_out" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ShellEscapeHandler.handle
Execute the line in a shell, empty return value
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def handle(self, line_info): """Execute the line in a shell, empty return value""" magic_handler = self.prefilter_manager.get_handler_by_name('magic') line = line_info.line if line.lstrip().startswith(ESC_SH_CAP): # rewrite LineInfo's line, ifun and the_rest to properly hold the # call to %sx and the actual command to be executed, so # handle_magic can work correctly. Note that this works even if # the line is indented, so it handles multi_line_specials # properly. new_rest = line.lstrip()[2:] line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest) line_info.ifun = 'sx' line_info.the_rest = new_rest return magic_handler.handle(line_info) else: cmd = line.lstrip().lstrip(ESC_SHELL) line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, cmd) return line_out
def handle(self, line_info): """Execute the line in a shell, empty return value""" magic_handler = self.prefilter_manager.get_handler_by_name('magic') line = line_info.line if line.lstrip().startswith(ESC_SH_CAP): # rewrite LineInfo's line, ifun and the_rest to properly hold the # call to %sx and the actual command to be executed, so # handle_magic can work correctly. Note that this works even if # the line is indented, so it handles multi_line_specials # properly. new_rest = line.lstrip()[2:] line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest) line_info.ifun = 'sx' line_info.the_rest = new_rest return magic_handler.handle(line_info) else: cmd = line.lstrip().lstrip(ESC_SHELL) line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, cmd) return line_out
[ "Execute", "the", "line", "in", "a", "shell", "empty", "return", "value" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L750-L769
[ "def", "handle", "(", "self", ",", "line_info", ")", ":", "magic_handler", "=", "self", ".", "prefilter_manager", ".", "get_handler_by_name", "(", "'magic'", ")", "line", "=", "line_info", ".", "line", "if", "line", ".", "lstrip", "(", ")", ".", "startswith", "(", "ESC_SH_CAP", ")", ":", "# rewrite LineInfo's line, ifun and the_rest to properly hold the", "# call to %sx and the actual command to be executed, so", "# handle_magic can work correctly. Note that this works even if", "# the line is indented, so it handles multi_line_specials", "# properly.", "new_rest", "=", "line", ".", "lstrip", "(", ")", "[", "2", ":", "]", "line_info", ".", "line", "=", "'%ssx %s'", "%", "(", "ESC_MAGIC", ",", "new_rest", ")", "line_info", ".", "ifun", "=", "'sx'", "line_info", ".", "the_rest", "=", "new_rest", "return", "magic_handler", ".", "handle", "(", "line_info", ")", "else", ":", "cmd", "=", "line", ".", "lstrip", "(", ")", ".", "lstrip", "(", "ESC_SHELL", ")", "line_out", "=", "'%sget_ipython().system(%r)'", "%", "(", "line_info", ".", "pre_whitespace", ",", "cmd", ")", "return", "line_out" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MagicHandler.handle
Execute magic functions.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def handle(self, line_info): """Execute magic functions.""" ifun = line_info.ifun the_rest = line_info.the_rest cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace, (ifun + " " + the_rest)) return cmd
def handle(self, line_info): """Execute magic functions.""" ifun = line_info.ifun the_rest = line_info.the_rest cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace, (ifun + " " + the_rest)) return cmd
[ "Execute", "magic", "functions", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L787-L793
[ "def", "handle", "(", "self", ",", "line_info", ")", ":", "ifun", "=", "line_info", ".", "ifun", "the_rest", "=", "line_info", ".", "the_rest", "cmd", "=", "'%sget_ipython().magic(%r)'", "%", "(", "line_info", ".", "pre_whitespace", ",", "(", "ifun", "+", "\" \"", "+", "the_rest", ")", ")", "return", "cmd" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AutoHandler.handle
Handle lines which can be auto-executed, quoting if requested.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def handle(self, line_info): """Handle lines which can be auto-executed, quoting if requested.""" line = line_info.line ifun = line_info.ifun the_rest = line_info.the_rest pre = line_info.pre esc = line_info.esc continue_prompt = line_info.continue_prompt obj = line_info.ofind(self.shell)['obj'] #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg # This should only be active for single-line input! if continue_prompt: return line force_auto = isinstance(obj, IPyAutocall) # User objects sometimes raise exceptions on attribute access other # than AttributeError (we've seen it in the past), so it's safest to be # ultra-conservative here and catch all. try: auto_rewrite = obj.rewrite except Exception: auto_rewrite = True if esc == ESC_QUOTE: # Auto-quote splitting on whitespace newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) elif esc == ESC_QUOTE2: # Auto-quote whole string newcmd = '%s("%s")' % (ifun,the_rest) elif esc == ESC_PAREN: newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) else: # Auto-paren. if force_auto: # Don't rewrite if it is already a call. do_rewrite = not the_rest.startswith('(') else: if not the_rest: # We only apply it to argument-less calls if the autocall # parameter is set to 2. do_rewrite = (self.shell.autocall >= 2) elif the_rest.startswith('[') and hasattr(obj, '__getitem__'): # Don't autocall in this case: item access for an object # which is BOTH callable and implements __getitem__. do_rewrite = False else: do_rewrite = True # Figure out the rewritten command if do_rewrite: if the_rest.endswith(';'): newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) else: newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) else: normal_handler = self.prefilter_manager.get_handler_by_name('normal') return normal_handler.handle(line_info) # Display the rewritten call if auto_rewrite: self.shell.auto_rewrite_input(newcmd) return newcmd
def handle(self, line_info): """Handle lines which can be auto-executed, quoting if requested.""" line = line_info.line ifun = line_info.ifun the_rest = line_info.the_rest pre = line_info.pre esc = line_info.esc continue_prompt = line_info.continue_prompt obj = line_info.ofind(self.shell)['obj'] #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg # This should only be active for single-line input! if continue_prompt: return line force_auto = isinstance(obj, IPyAutocall) # User objects sometimes raise exceptions on attribute access other # than AttributeError (we've seen it in the past), so it's safest to be # ultra-conservative here and catch all. try: auto_rewrite = obj.rewrite except Exception: auto_rewrite = True if esc == ESC_QUOTE: # Auto-quote splitting on whitespace newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) elif esc == ESC_QUOTE2: # Auto-quote whole string newcmd = '%s("%s")' % (ifun,the_rest) elif esc == ESC_PAREN: newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) else: # Auto-paren. if force_auto: # Don't rewrite if it is already a call. do_rewrite = not the_rest.startswith('(') else: if not the_rest: # We only apply it to argument-less calls if the autocall # parameter is set to 2. do_rewrite = (self.shell.autocall >= 2) elif the_rest.startswith('[') and hasattr(obj, '__getitem__'): # Don't autocall in this case: item access for an object # which is BOTH callable and implements __getitem__. do_rewrite = False else: do_rewrite = True # Figure out the rewritten command if do_rewrite: if the_rest.endswith(';'): newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) else: newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) else: normal_handler = self.prefilter_manager.get_handler_by_name('normal') return normal_handler.handle(line_info) # Display the rewritten call if auto_rewrite: self.shell.auto_rewrite_input(newcmd) return newcmd
[ "Handle", "lines", "which", "can", "be", "auto", "-", "executed", "quoting", "if", "requested", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L801-L865
[ "def", "handle", "(", "self", ",", "line_info", ")", ":", "line", "=", "line_info", ".", "line", "ifun", "=", "line_info", ".", "ifun", "the_rest", "=", "line_info", ".", "the_rest", "pre", "=", "line_info", ".", "pre", "esc", "=", "line_info", ".", "esc", "continue_prompt", "=", "line_info", ".", "continue_prompt", "obj", "=", "line_info", ".", "ofind", "(", "self", ".", "shell", ")", "[", "'obj'", "]", "#print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg", "# This should only be active for single-line input!", "if", "continue_prompt", ":", "return", "line", "force_auto", "=", "isinstance", "(", "obj", ",", "IPyAutocall", ")", "# User objects sometimes raise exceptions on attribute access other", "# than AttributeError (we've seen it in the past), so it's safest to be", "# ultra-conservative here and catch all.", "try", ":", "auto_rewrite", "=", "obj", ".", "rewrite", "except", "Exception", ":", "auto_rewrite", "=", "True", "if", "esc", "==", "ESC_QUOTE", ":", "# Auto-quote splitting on whitespace", "newcmd", "=", "'%s(\"%s\")'", "%", "(", "ifun", ",", "'\", \"'", ".", "join", "(", "the_rest", ".", "split", "(", ")", ")", ")", "elif", "esc", "==", "ESC_QUOTE2", ":", "# Auto-quote whole string", "newcmd", "=", "'%s(\"%s\")'", "%", "(", "ifun", ",", "the_rest", ")", "elif", "esc", "==", "ESC_PAREN", ":", "newcmd", "=", "'%s(%s)'", "%", "(", "ifun", ",", "\",\"", ".", "join", "(", "the_rest", ".", "split", "(", ")", ")", ")", "else", ":", "# Auto-paren. ", "if", "force_auto", ":", "# Don't rewrite if it is already a call.", "do_rewrite", "=", "not", "the_rest", ".", "startswith", "(", "'('", ")", "else", ":", "if", "not", "the_rest", ":", "# We only apply it to argument-less calls if the autocall", "# parameter is set to 2.", "do_rewrite", "=", "(", "self", ".", "shell", ".", "autocall", ">=", "2", ")", "elif", "the_rest", ".", "startswith", "(", "'['", ")", "and", "hasattr", "(", "obj", ",", "'__getitem__'", ")", ":", "# Don't autocall in this case: item access for an object", "# which is BOTH callable and implements __getitem__.", "do_rewrite", "=", "False", "else", ":", "do_rewrite", "=", "True", "# Figure out the rewritten command", "if", "do_rewrite", ":", "if", "the_rest", ".", "endswith", "(", "';'", ")", ":", "newcmd", "=", "'%s(%s);'", "%", "(", "ifun", ".", "rstrip", "(", ")", ",", "the_rest", "[", ":", "-", "1", "]", ")", "else", ":", "newcmd", "=", "'%s(%s)'", "%", "(", "ifun", ".", "rstrip", "(", ")", ",", "the_rest", ")", "else", ":", "normal_handler", "=", "self", ".", "prefilter_manager", ".", "get_handler_by_name", "(", "'normal'", ")", "return", "normal_handler", ".", "handle", "(", "line_info", ")", "# Display the rewritten call", "if", "auto_rewrite", ":", "self", ".", "shell", ".", "auto_rewrite_input", "(", "newcmd", ")", "return", "newcmd" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
HelpHandler.handle
Try to get some help for the object. obj? or ?obj -> basic information. obj?? or ??obj -> more details.
environment/lib/python2.7/site-packages/IPython/core/prefilter.py
def handle(self, line_info): """Try to get some help for the object. obj? or ?obj -> basic information. obj?? or ??obj -> more details. """ normal_handler = self.prefilter_manager.get_handler_by_name('normal') line = line_info.line # We need to make sure that we don't process lines which would be # otherwise valid python, such as "x=1 # what?" try: codeop.compile_command(line) except SyntaxError: # We should only handle as help stuff which is NOT valid syntax if line[0]==ESC_HELP: line = line[1:] elif line[-1]==ESC_HELP: line = line[:-1] if line: #print 'line:<%r>' % line # dbg self.shell.magic('pinfo %s' % line_info.ifun) else: self.shell.show_usage() return '' # Empty string is needed here! except: raise # Pass any other exceptions through to the normal handler return normal_handler.handle(line_info) else: # If the code compiles ok, we should handle it normally return normal_handler.handle(line_info)
def handle(self, line_info): """Try to get some help for the object. obj? or ?obj -> basic information. obj?? or ??obj -> more details. """ normal_handler = self.prefilter_manager.get_handler_by_name('normal') line = line_info.line # We need to make sure that we don't process lines which would be # otherwise valid python, such as "x=1 # what?" try: codeop.compile_command(line) except SyntaxError: # We should only handle as help stuff which is NOT valid syntax if line[0]==ESC_HELP: line = line[1:] elif line[-1]==ESC_HELP: line = line[:-1] if line: #print 'line:<%r>' % line # dbg self.shell.magic('pinfo %s' % line_info.ifun) else: self.shell.show_usage() return '' # Empty string is needed here! except: raise # Pass any other exceptions through to the normal handler return normal_handler.handle(line_info) else: # If the code compiles ok, we should handle it normally return normal_handler.handle(line_info)
[ "Try", "to", "get", "some", "help", "for", "the", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/prefilter.py#L873-L903
[ "def", "handle", "(", "self", ",", "line_info", ")", ":", "normal_handler", "=", "self", ".", "prefilter_manager", ".", "get_handler_by_name", "(", "'normal'", ")", "line", "=", "line_info", ".", "line", "# We need to make sure that we don't process lines which would be", "# otherwise valid python, such as \"x=1 # what?\"", "try", ":", "codeop", ".", "compile_command", "(", "line", ")", "except", "SyntaxError", ":", "# We should only handle as help stuff which is NOT valid syntax", "if", "line", "[", "0", "]", "==", "ESC_HELP", ":", "line", "=", "line", "[", "1", ":", "]", "elif", "line", "[", "-", "1", "]", "==", "ESC_HELP", ":", "line", "=", "line", "[", ":", "-", "1", "]", "if", "line", ":", "#print 'line:<%r>' % line # dbg", "self", ".", "shell", ".", "magic", "(", "'pinfo %s'", "%", "line_info", ".", "ifun", ")", "else", ":", "self", ".", "shell", ".", "show_usage", "(", ")", "return", "''", "# Empty string is needed here!", "except", ":", "raise", "# Pass any other exceptions through to the normal handler", "return", "normal_handler", ".", "handle", "(", "line_info", ")", "else", ":", "# If the code compiles ok, we should handle it normally", "return", "normal_handler", ".", "handle", "(", "line_info", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CallTipWidget.eventFilter
Reimplemented to hide on certain key presses and on text edit focus changes.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py
def eventFilter(self, obj, event): """ Reimplemented to hide on certain key presses and on text edit focus changes. """ if obj == self._text_edit: etype = event.type() if etype == QtCore.QEvent.KeyPress: key = event.key() if key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return): self.hide() elif key == QtCore.Qt.Key_Escape: self.hide() return True elif etype == QtCore.QEvent.FocusOut: self.hide() elif etype == QtCore.QEvent.Enter: self._hide_timer.stop() elif etype == QtCore.QEvent.Leave: self._leave_event_hide() return super(CallTipWidget, self).eventFilter(obj, event)
def eventFilter(self, obj, event): """ Reimplemented to hide on certain key presses and on text edit focus changes. """ if obj == self._text_edit: etype = event.type() if etype == QtCore.QEvent.KeyPress: key = event.key() if key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return): self.hide() elif key == QtCore.Qt.Key_Escape: self.hide() return True elif etype == QtCore.QEvent.FocusOut: self.hide() elif etype == QtCore.QEvent.Enter: self._hide_timer.stop() elif etype == QtCore.QEvent.Leave: self._leave_event_hide() return super(CallTipWidget, self).eventFilter(obj, event)
[ "Reimplemented", "to", "hide", "on", "certain", "key", "presses", "and", "on", "text", "edit", "focus", "changes", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py#L41-L65
[ "def", "eventFilter", "(", "self", ",", "obj", ",", "event", ")", ":", "if", "obj", "==", "self", ".", "_text_edit", ":", "etype", "=", "event", ".", "type", "(", ")", "if", "etype", "==", "QtCore", ".", "QEvent", ".", "KeyPress", ":", "key", "=", "event", ".", "key", "(", ")", "if", "key", "in", "(", "QtCore", ".", "Qt", ".", "Key_Enter", ",", "QtCore", ".", "Qt", ".", "Key_Return", ")", ":", "self", ".", "hide", "(", ")", "elif", "key", "==", "QtCore", ".", "Qt", ".", "Key_Escape", ":", "self", ".", "hide", "(", ")", "return", "True", "elif", "etype", "==", "QtCore", ".", "QEvent", ".", "FocusOut", ":", "self", ".", "hide", "(", ")", "elif", "etype", "==", "QtCore", ".", "QEvent", ".", "Enter", ":", "self", ".", "_hide_timer", ".", "stop", "(", ")", "elif", "etype", "==", "QtCore", ".", "QEvent", ".", "Leave", ":", "self", ".", "_leave_event_hide", "(", ")", "return", "super", "(", "CallTipWidget", ",", "self", ")", ".", "eventFilter", "(", "obj", ",", "event", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CallTipWidget.enterEvent
Reimplemented to cancel the hide timer.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py
def enterEvent(self, event): """ Reimplemented to cancel the hide timer. """ super(CallTipWidget, self).enterEvent(event) self._hide_timer.stop()
def enterEvent(self, event): """ Reimplemented to cancel the hide timer. """ super(CallTipWidget, self).enterEvent(event) self._hide_timer.stop()
[ "Reimplemented", "to", "cancel", "the", "hide", "timer", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py#L78-L82
[ "def", "enterEvent", "(", "self", ",", "event", ")", ":", "super", "(", "CallTipWidget", ",", "self", ")", ".", "enterEvent", "(", "event", ")", "self", ".", "_hide_timer", ".", "stop", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CallTipWidget.paintEvent
Reimplemented to paint the background panel.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py
def paintEvent(self, event): """ Reimplemented to paint the background panel. """ painter = QtGui.QStylePainter(self) option = QtGui.QStyleOptionFrame() option.initFrom(self) painter.drawPrimitive(QtGui.QStyle.PE_PanelTipLabel, option) painter.end() super(CallTipWidget, self).paintEvent(event)
def paintEvent(self, event): """ Reimplemented to paint the background panel. """ painter = QtGui.QStylePainter(self) option = QtGui.QStyleOptionFrame() option.initFrom(self) painter.drawPrimitive(QtGui.QStyle.PE_PanelTipLabel, option) painter.end() super(CallTipWidget, self).paintEvent(event)
[ "Reimplemented", "to", "paint", "the", "background", "panel", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py#L98-L107
[ "def", "paintEvent", "(", "self", ",", "event", ")", ":", "painter", "=", "QtGui", ".", "QStylePainter", "(", "self", ")", "option", "=", "QtGui", ".", "QStyleOptionFrame", "(", ")", "option", ".", "initFrom", "(", "self", ")", "painter", ".", "drawPrimitive", "(", "QtGui", ".", "QStyle", ".", "PE_PanelTipLabel", ",", "option", ")", "painter", ".", "end", "(", ")", "super", "(", "CallTipWidget", ",", "self", ")", ".", "paintEvent", "(", "event", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CallTipWidget.show_call_info
Attempts to show the specified call line and docstring at the current cursor location. The docstring is possibly truncated for length.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py
def show_call_info(self, call_line=None, doc=None, maxlines=20): """ Attempts to show the specified call line and docstring at the current cursor location. The docstring is possibly truncated for length. """ if doc: match = re.match("(?:[^\n]*\n){%i}" % maxlines, doc) if match: doc = doc[:match.end()] + '\n[Documentation continues...]' else: doc = '' if call_line: doc = '\n\n'.join([call_line, doc]) return self.show_tip(doc)
def show_call_info(self, call_line=None, doc=None, maxlines=20): """ Attempts to show the specified call line and docstring at the current cursor location. The docstring is possibly truncated for length. """ if doc: match = re.match("(?:[^\n]*\n){%i}" % maxlines, doc) if match: doc = doc[:match.end()] + '\n[Documentation continues...]' else: doc = '' if call_line: doc = '\n\n'.join([call_line, doc]) return self.show_tip(doc)
[ "Attempts", "to", "show", "the", "specified", "call", "line", "and", "docstring", "at", "the", "current", "cursor", "location", ".", "The", "docstring", "is", "possibly", "truncated", "for", "length", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py#L126-L140
[ "def", "show_call_info", "(", "self", ",", "call_line", "=", "None", ",", "doc", "=", "None", ",", "maxlines", "=", "20", ")", ":", "if", "doc", ":", "match", "=", "re", ".", "match", "(", "\"(?:[^\\n]*\\n){%i}\"", "%", "maxlines", ",", "doc", ")", "if", "match", ":", "doc", "=", "doc", "[", ":", "match", ".", "end", "(", ")", "]", "+", "'\\n[Documentation continues...]'", "else", ":", "doc", "=", "''", "if", "call_line", ":", "doc", "=", "'\\n\\n'", ".", "join", "(", "[", "call_line", ",", "doc", "]", ")", "return", "self", ".", "show_tip", "(", "doc", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CallTipWidget.show_tip
Attempts to show the specified tip at the current cursor location.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py
def show_tip(self, tip): """ Attempts to show the specified tip at the current cursor location. """ # Attempt to find the cursor position at which to show the call tip. text_edit = self._text_edit document = text_edit.document() cursor = text_edit.textCursor() search_pos = cursor.position() - 1 self._start_position, _ = self._find_parenthesis(search_pos, forward=False) if self._start_position == -1: return False # Set the text and resize the widget accordingly. self.setText(tip) self.resize(self.sizeHint()) # Locate and show the widget. Place the tip below the current line # unless it would be off the screen. In that case, decide the best # location based trying to minimize the area that goes off-screen. padding = 3 # Distance in pixels between cursor bounds and tip box. cursor_rect = text_edit.cursorRect(cursor) screen_rect = QtGui.qApp.desktop().screenGeometry(text_edit) point = text_edit.mapToGlobal(cursor_rect.bottomRight()) point.setY(point.y() + padding) tip_height = self.size().height() tip_width = self.size().width() vertical = 'bottom' horizontal = 'Right' if point.y() + tip_height > screen_rect.height(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off screen, check if point is in top or bottom # half of screen. if point_.y() - tip_height < padding: # If point is in upper half of screen, show tip below it. # otherwise above it. if 2*point.y() < screen_rect.height(): vertical = 'bottom' else: vertical = 'top' else: vertical = 'top' if point.x() + tip_width > screen_rect.width(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off-screen, check if point is in the right or # left half of the screen. if point_.x() - tip_width < padding: if 2*point.x() < screen_rect.width(): horizontal = 'Right' else: horizontal = 'Left' else: horizontal = 'Left' pos = getattr(cursor_rect, '%s%s' %(vertical, horizontal)) point = text_edit.mapToGlobal(pos()) if vertical == 'top': point.setY(point.y() - tip_height - padding) if horizontal == 'Left': point.setX(point.x() - tip_width - padding) self.move(point) self.show() return True
def show_tip(self, tip): """ Attempts to show the specified tip at the current cursor location. """ # Attempt to find the cursor position at which to show the call tip. text_edit = self._text_edit document = text_edit.document() cursor = text_edit.textCursor() search_pos = cursor.position() - 1 self._start_position, _ = self._find_parenthesis(search_pos, forward=False) if self._start_position == -1: return False # Set the text and resize the widget accordingly. self.setText(tip) self.resize(self.sizeHint()) # Locate and show the widget. Place the tip below the current line # unless it would be off the screen. In that case, decide the best # location based trying to minimize the area that goes off-screen. padding = 3 # Distance in pixels between cursor bounds and tip box. cursor_rect = text_edit.cursorRect(cursor) screen_rect = QtGui.qApp.desktop().screenGeometry(text_edit) point = text_edit.mapToGlobal(cursor_rect.bottomRight()) point.setY(point.y() + padding) tip_height = self.size().height() tip_width = self.size().width() vertical = 'bottom' horizontal = 'Right' if point.y() + tip_height > screen_rect.height(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off screen, check if point is in top or bottom # half of screen. if point_.y() - tip_height < padding: # If point is in upper half of screen, show tip below it. # otherwise above it. if 2*point.y() < screen_rect.height(): vertical = 'bottom' else: vertical = 'top' else: vertical = 'top' if point.x() + tip_width > screen_rect.width(): point_ = text_edit.mapToGlobal(cursor_rect.topRight()) # If tip is still off-screen, check if point is in the right or # left half of the screen. if point_.x() - tip_width < padding: if 2*point.x() < screen_rect.width(): horizontal = 'Right' else: horizontal = 'Left' else: horizontal = 'Left' pos = getattr(cursor_rect, '%s%s' %(vertical, horizontal)) point = text_edit.mapToGlobal(pos()) if vertical == 'top': point.setY(point.y() - tip_height - padding) if horizontal == 'Left': point.setX(point.x() - tip_width - padding) self.move(point) self.show() return True
[ "Attempts", "to", "show", "the", "specified", "tip", "at", "the", "current", "cursor", "location", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py#L142-L205
[ "def", "show_tip", "(", "self", ",", "tip", ")", ":", "# Attempt to find the cursor position at which to show the call tip.", "text_edit", "=", "self", ".", "_text_edit", "document", "=", "text_edit", ".", "document", "(", ")", "cursor", "=", "text_edit", ".", "textCursor", "(", ")", "search_pos", "=", "cursor", ".", "position", "(", ")", "-", "1", "self", ".", "_start_position", ",", "_", "=", "self", ".", "_find_parenthesis", "(", "search_pos", ",", "forward", "=", "False", ")", "if", "self", ".", "_start_position", "==", "-", "1", ":", "return", "False", "# Set the text and resize the widget accordingly.", "self", ".", "setText", "(", "tip", ")", "self", ".", "resize", "(", "self", ".", "sizeHint", "(", ")", ")", "# Locate and show the widget. Place the tip below the current line", "# unless it would be off the screen. In that case, decide the best", "# location based trying to minimize the area that goes off-screen.", "padding", "=", "3", "# Distance in pixels between cursor bounds and tip box.", "cursor_rect", "=", "text_edit", ".", "cursorRect", "(", "cursor", ")", "screen_rect", "=", "QtGui", ".", "qApp", ".", "desktop", "(", ")", ".", "screenGeometry", "(", "text_edit", ")", "point", "=", "text_edit", ".", "mapToGlobal", "(", "cursor_rect", ".", "bottomRight", "(", ")", ")", "point", ".", "setY", "(", "point", ".", "y", "(", ")", "+", "padding", ")", "tip_height", "=", "self", ".", "size", "(", ")", ".", "height", "(", ")", "tip_width", "=", "self", ".", "size", "(", ")", ".", "width", "(", ")", "vertical", "=", "'bottom'", "horizontal", "=", "'Right'", "if", "point", ".", "y", "(", ")", "+", "tip_height", ">", "screen_rect", ".", "height", "(", ")", ":", "point_", "=", "text_edit", ".", "mapToGlobal", "(", "cursor_rect", ".", "topRight", "(", ")", ")", "# If tip is still off screen, check if point is in top or bottom", "# half of screen.", "if", "point_", ".", "y", "(", ")", "-", "tip_height", "<", "padding", ":", "# If point is in upper half of screen, show tip below it.", "# otherwise above it.", "if", "2", "*", "point", ".", "y", "(", ")", "<", "screen_rect", ".", "height", "(", ")", ":", "vertical", "=", "'bottom'", "else", ":", "vertical", "=", "'top'", "else", ":", "vertical", "=", "'top'", "if", "point", ".", "x", "(", ")", "+", "tip_width", ">", "screen_rect", ".", "width", "(", ")", ":", "point_", "=", "text_edit", ".", "mapToGlobal", "(", "cursor_rect", ".", "topRight", "(", ")", ")", "# If tip is still off-screen, check if point is in the right or", "# left half of the screen.", "if", "point_", ".", "x", "(", ")", "-", "tip_width", "<", "padding", ":", "if", "2", "*", "point", ".", "x", "(", ")", "<", "screen_rect", ".", "width", "(", ")", ":", "horizontal", "=", "'Right'", "else", ":", "horizontal", "=", "'Left'", "else", ":", "horizontal", "=", "'Left'", "pos", "=", "getattr", "(", "cursor_rect", ",", "'%s%s'", "%", "(", "vertical", ",", "horizontal", ")", ")", "point", "=", "text_edit", ".", "mapToGlobal", "(", "pos", "(", ")", ")", "if", "vertical", "==", "'top'", ":", "point", ".", "setY", "(", "point", ".", "y", "(", ")", "-", "tip_height", "-", "padding", ")", "if", "horizontal", "==", "'Left'", ":", "point", ".", "setX", "(", "point", ".", "x", "(", ")", "-", "tip_width", "-", "padding", ")", "self", ".", "move", "(", "point", ")", "self", ".", "show", "(", ")", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CallTipWidget._find_parenthesis
If 'forward' is True (resp. False), proceed forwards (resp. backwards) through the line that contains 'position' until an unmatched closing (resp. opening) parenthesis is found. Returns a tuple containing the position of this parenthesis (or -1 if it is not found) and the number commas (at depth 0) found along the way.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py
def _find_parenthesis(self, position, forward=True): """ If 'forward' is True (resp. False), proceed forwards (resp. backwards) through the line that contains 'position' until an unmatched closing (resp. opening) parenthesis is found. Returns a tuple containing the position of this parenthesis (or -1 if it is not found) and the number commas (at depth 0) found along the way. """ commas = depth = 0 document = self._text_edit.document() char = document.characterAt(position) # Search until a match is found or a non-printable character is # encountered. while category(char) != 'Cc' and position > 0: if char == ',' and depth == 0: commas += 1 elif char == ')': if forward and depth == 0: break depth += 1 elif char == '(': if not forward and depth == 0: break depth -= 1 position += 1 if forward else -1 char = document.characterAt(position) else: position = -1 return position, commas
def _find_parenthesis(self, position, forward=True): """ If 'forward' is True (resp. False), proceed forwards (resp. backwards) through the line that contains 'position' until an unmatched closing (resp. opening) parenthesis is found. Returns a tuple containing the position of this parenthesis (or -1 if it is not found) and the number commas (at depth 0) found along the way. """ commas = depth = 0 document = self._text_edit.document() char = document.characterAt(position) # Search until a match is found or a non-printable character is # encountered. while category(char) != 'Cc' and position > 0: if char == ',' and depth == 0: commas += 1 elif char == ')': if forward and depth == 0: break depth += 1 elif char == '(': if not forward and depth == 0: break depth -= 1 position += 1 if forward else -1 char = document.characterAt(position) else: position = -1 return position, commas
[ "If", "forward", "is", "True", "(", "resp", ".", "False", ")", "proceed", "forwards", "(", "resp", ".", "backwards", ")", "through", "the", "line", "that", "contains", "position", "until", "an", "unmatched", "closing", "(", "resp", ".", "opening", ")", "parenthesis", "is", "found", ".", "Returns", "a", "tuple", "containing", "the", "position", "of", "this", "parenthesis", "(", "or", "-", "1", "if", "it", "is", "not", "found", ")", "and", "the", "number", "commas", "(", "at", "depth", "0", ")", "found", "along", "the", "way", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py#L211-L238
[ "def", "_find_parenthesis", "(", "self", ",", "position", ",", "forward", "=", "True", ")", ":", "commas", "=", "depth", "=", "0", "document", "=", "self", ".", "_text_edit", ".", "document", "(", ")", "char", "=", "document", ".", "characterAt", "(", "position", ")", "# Search until a match is found or a non-printable character is", "# encountered.", "while", "category", "(", "char", ")", "!=", "'Cc'", "and", "position", ">", "0", ":", "if", "char", "==", "','", "and", "depth", "==", "0", ":", "commas", "+=", "1", "elif", "char", "==", "')'", ":", "if", "forward", "and", "depth", "==", "0", ":", "break", "depth", "+=", "1", "elif", "char", "==", "'('", ":", "if", "not", "forward", "and", "depth", "==", "0", ":", "break", "depth", "-=", "1", "position", "+=", "1", "if", "forward", "else", "-", "1", "char", "=", "document", ".", "characterAt", "(", "position", ")", "else", ":", "position", "=", "-", "1", "return", "position", ",", "commas" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CallTipWidget._leave_event_hide
Hides the tooltip after some time has passed (assuming the cursor is not over the tooltip).
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py
def _leave_event_hide(self): """ Hides the tooltip after some time has passed (assuming the cursor is not over the tooltip). """ if (not self._hide_timer.isActive() and # If Enter events always came after Leave events, we wouldn't need # this check. But on Mac OS, it sometimes happens the other way # around when the tooltip is created. QtGui.qApp.topLevelAt(QtGui.QCursor.pos()) != self): self._hide_timer.start(300, self)
def _leave_event_hide(self): """ Hides the tooltip after some time has passed (assuming the cursor is not over the tooltip). """ if (not self._hide_timer.isActive() and # If Enter events always came after Leave events, we wouldn't need # this check. But on Mac OS, it sometimes happens the other way # around when the tooltip is created. QtGui.qApp.topLevelAt(QtGui.QCursor.pos()) != self): self._hide_timer.start(300, self)
[ "Hides", "the", "tooltip", "after", "some", "time", "has", "passed", "(", "assuming", "the", "cursor", "is", "not", "over", "the", "tooltip", ")", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py#L240-L249
[ "def", "_leave_event_hide", "(", "self", ")", ":", "if", "(", "not", "self", ".", "_hide_timer", ".", "isActive", "(", ")", "and", "# If Enter events always came after Leave events, we wouldn't need", "# this check. But on Mac OS, it sometimes happens the other way", "# around when the tooltip is created.", "QtGui", ".", "qApp", ".", "topLevelAt", "(", "QtGui", ".", "QCursor", ".", "pos", "(", ")", ")", "!=", "self", ")", ":", "self", ".", "_hide_timer", ".", "start", "(", "300", ",", "self", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CallTipWidget._cursor_position_changed
Updates the tip based on user cursor movement.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py
def _cursor_position_changed(self): """ Updates the tip based on user cursor movement. """ cursor = self._text_edit.textCursor() if cursor.position() <= self._start_position: self.hide() else: position, commas = self._find_parenthesis(self._start_position + 1) if position != -1: self.hide()
def _cursor_position_changed(self): """ Updates the tip based on user cursor movement. """ cursor = self._text_edit.textCursor() if cursor.position() <= self._start_position: self.hide() else: position, commas = self._find_parenthesis(self._start_position + 1) if position != -1: self.hide()
[ "Updates", "the", "tip", "based", "on", "user", "cursor", "movement", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/call_tip_widget.py#L253-L262
[ "def", "_cursor_position_changed", "(", "self", ")", ":", "cursor", "=", "self", ".", "_text_edit", ".", "textCursor", "(", ")", "if", "cursor", ".", "position", "(", ")", "<=", "self", ".", "_start_position", ":", "self", ".", "hide", "(", ")", "else", ":", "position", ",", "commas", "=", "self", ".", "_find_parenthesis", "(", "self", ".", "_start_position", "+", "1", ")", "if", "position", "!=", "-", "1", ":", "self", ".", "hide", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
proxied_attribute
Create a property that proxies attribute ``proxied_attr`` through the local attribute ``local_attr``.
environment/lib/python2.7/site-packages/nose/proxy.py
def proxied_attribute(local_attr, proxied_attr, doc): """Create a property that proxies attribute ``proxied_attr`` through the local attribute ``local_attr``. """ def fget(self): return getattr(getattr(self, local_attr), proxied_attr) def fset(self, value): setattr(getattr(self, local_attr), proxied_attr, value) def fdel(self): delattr(getattr(self, local_attr), proxied_attr) return property(fget, fset, fdel, doc)
def proxied_attribute(local_attr, proxied_attr, doc): """Create a property that proxies attribute ``proxied_attr`` through the local attribute ``local_attr``. """ def fget(self): return getattr(getattr(self, local_attr), proxied_attr) def fset(self, value): setattr(getattr(self, local_attr), proxied_attr, value) def fdel(self): delattr(getattr(self, local_attr), proxied_attr) return property(fget, fset, fdel, doc)
[ "Create", "a", "property", "that", "proxies", "attribute", "proxied_attr", "through", "the", "local", "attribute", "local_attr", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/proxy.py#L25-L35
[ "def", "proxied_attribute", "(", "local_attr", ",", "proxied_attr", ",", "doc", ")", ":", "def", "fget", "(", "self", ")", ":", "return", "getattr", "(", "getattr", "(", "self", ",", "local_attr", ")", ",", "proxied_attr", ")", "def", "fset", "(", "self", ",", "value", ")", ":", "setattr", "(", "getattr", "(", "self", ",", "local_attr", ")", ",", "proxied_attr", ",", "value", ")", "def", "fdel", "(", "self", ")", ":", "delattr", "(", "getattr", "(", "self", ",", "local_attr", ")", ",", "proxied_attr", ")", "return", "property", "(", "fget", ",", "fset", ",", "fdel", ",", "doc", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
canonicalize_path
Canonicalizes a path relative to a given working directory. That is, the path, if not absolute, is interpreted relative to the working directory, then converted to absolute form. :param cwd: The working directory. :param path: The path to canonicalize. :returns: The absolute path.
timid/utils.py
def canonicalize_path(cwd, path): """ Canonicalizes a path relative to a given working directory. That is, the path, if not absolute, is interpreted relative to the working directory, then converted to absolute form. :param cwd: The working directory. :param path: The path to canonicalize. :returns: The absolute path. """ if not os.path.isabs(path): path = os.path.join(cwd, path) return os.path.abspath(path)
def canonicalize_path(cwd, path): """ Canonicalizes a path relative to a given working directory. That is, the path, if not absolute, is interpreted relative to the working directory, then converted to absolute form. :param cwd: The working directory. :param path: The path to canonicalize. :returns: The absolute path. """ if not os.path.isabs(path): path = os.path.join(cwd, path) return os.path.abspath(path)
[ "Canonicalizes", "a", "path", "relative", "to", "a", "given", "working", "directory", ".", "That", "is", "the", "path", "if", "not", "absolute", "is", "interpreted", "relative", "to", "the", "working", "directory", "then", "converted", "to", "absolute", "form", "." ]
rackerlabs/timid
python
https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/utils.py#L28-L43
[ "def", "canonicalize_path", "(", "cwd", ",", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "cwd", ",", "path", ")", "return", "os", ".", "path", ".", "abspath", "(", "path", ")" ]
b1c6aa159ab380a033740f4aa392cf0d125e0ac6
test
schema_validate
Schema validation helper. Performs JSONSchema validation. If a schema validation error is encountered, an exception of the designated class is raised with the validation error message appropriately simplified and passed as the sole positional argument. :param instance: The object to schema validate. :param schema: The schema to use for validation. :param exc_class: The exception class to raise instead of the ``jsonschema.ValidationError`` exception. :param prefix: Positional arguments are interpreted as a list of keys to prefix to the path contained in the validation error. :param kwargs: Keyword arguments to pass to the exception constructor.
timid/utils.py
def schema_validate(instance, schema, exc_class, *prefix, **kwargs): """ Schema validation helper. Performs JSONSchema validation. If a schema validation error is encountered, an exception of the designated class is raised with the validation error message appropriately simplified and passed as the sole positional argument. :param instance: The object to schema validate. :param schema: The schema to use for validation. :param exc_class: The exception class to raise instead of the ``jsonschema.ValidationError`` exception. :param prefix: Positional arguments are interpreted as a list of keys to prefix to the path contained in the validation error. :param kwargs: Keyword arguments to pass to the exception constructor. """ try: # Do the validation jsonschema.validate(instance, schema) except jsonschema.ValidationError as exc: # Assemble the path path = '/'.join((a if isinstance(a, six.string_types) else '[%d]' % a) for a in itertools.chain(prefix, exc.path)) # Construct the message message = 'Failed to validate "%s": %s' % (path, exc.message) # Raise the target exception raise exc_class(message, **kwargs)
def schema_validate(instance, schema, exc_class, *prefix, **kwargs): """ Schema validation helper. Performs JSONSchema validation. If a schema validation error is encountered, an exception of the designated class is raised with the validation error message appropriately simplified and passed as the sole positional argument. :param instance: The object to schema validate. :param schema: The schema to use for validation. :param exc_class: The exception class to raise instead of the ``jsonschema.ValidationError`` exception. :param prefix: Positional arguments are interpreted as a list of keys to prefix to the path contained in the validation error. :param kwargs: Keyword arguments to pass to the exception constructor. """ try: # Do the validation jsonschema.validate(instance, schema) except jsonschema.ValidationError as exc: # Assemble the path path = '/'.join((a if isinstance(a, six.string_types) else '[%d]' % a) for a in itertools.chain(prefix, exc.path)) # Construct the message message = 'Failed to validate "%s": %s' % (path, exc.message) # Raise the target exception raise exc_class(message, **kwargs)
[ "Schema", "validation", "helper", ".", "Performs", "JSONSchema", "validation", ".", "If", "a", "schema", "validation", "error", "is", "encountered", "an", "exception", "of", "the", "designated", "class", "is", "raised", "with", "the", "validation", "error", "message", "appropriately", "simplified", "and", "passed", "as", "the", "sole", "positional", "argument", "." ]
rackerlabs/timid
python
https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/utils.py#L285-L316
[ "def", "schema_validate", "(", "instance", ",", "schema", ",", "exc_class", ",", "*", "prefix", ",", "*", "*", "kwargs", ")", ":", "try", ":", "# Do the validation", "jsonschema", ".", "validate", "(", "instance", ",", "schema", ")", "except", "jsonschema", ".", "ValidationError", "as", "exc", ":", "# Assemble the path", "path", "=", "'/'", ".", "join", "(", "(", "a", "if", "isinstance", "(", "a", ",", "six", ".", "string_types", ")", "else", "'[%d]'", "%", "a", ")", "for", "a", "in", "itertools", ".", "chain", "(", "prefix", ",", "exc", ".", "path", ")", ")", "# Construct the message", "message", "=", "'Failed to validate \"%s\": %s'", "%", "(", "path", ",", "exc", ".", "message", ")", "# Raise the target exception", "raise", "exc_class", "(", "message", ",", "*", "*", "kwargs", ")" ]
b1c6aa159ab380a033740f4aa392cf0d125e0ac6
test
iter_prio_dict
Iterate over a priority dictionary. A priority dictionary is a dictionary keyed by integer priority, with the values being lists of objects. This generator will iterate over the dictionary in priority order (from lowest integer value to highest integer value), yielding each object in the lists in turn. :param prio_dict: A priority dictionary, as described above. :returns: An iterator that yields each object in the correct order, based on priority and ordering within the priority values.
timid/utils.py
def iter_prio_dict(prio_dict): """ Iterate over a priority dictionary. A priority dictionary is a dictionary keyed by integer priority, with the values being lists of objects. This generator will iterate over the dictionary in priority order (from lowest integer value to highest integer value), yielding each object in the lists in turn. :param prio_dict: A priority dictionary, as described above. :returns: An iterator that yields each object in the correct order, based on priority and ordering within the priority values. """ for _prio, objs in sorted(prio_dict.items(), key=lambda x: x[0]): for obj in objs: yield obj
def iter_prio_dict(prio_dict): """ Iterate over a priority dictionary. A priority dictionary is a dictionary keyed by integer priority, with the values being lists of objects. This generator will iterate over the dictionary in priority order (from lowest integer value to highest integer value), yielding each object in the lists in turn. :param prio_dict: A priority dictionary, as described above. :returns: An iterator that yields each object in the correct order, based on priority and ordering within the priority values. """ for _prio, objs in sorted(prio_dict.items(), key=lambda x: x[0]): for obj in objs: yield obj
[ "Iterate", "over", "a", "priority", "dictionary", ".", "A", "priority", "dictionary", "is", "a", "dictionary", "keyed", "by", "integer", "priority", "with", "the", "values", "being", "lists", "of", "objects", ".", "This", "generator", "will", "iterate", "over", "the", "dictionary", "in", "priority", "order", "(", "from", "lowest", "integer", "value", "to", "highest", "integer", "value", ")", "yielding", "each", "object", "in", "the", "lists", "in", "turn", "." ]
rackerlabs/timid
python
https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/utils.py#L319-L336
[ "def", "iter_prio_dict", "(", "prio_dict", ")", ":", "for", "_prio", ",", "objs", "in", "sorted", "(", "prio_dict", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", ":", "for", "obj", "in", "objs", ":", "yield", "obj" ]
b1c6aa159ab380a033740f4aa392cf0d125e0ac6
test
SensitiveDict.masked
Retrieve a read-only subordinate mapping. All values are stringified, and sensitive values are masked. The subordinate mapping implements the context manager protocol for convenience.
timid/utils.py
def masked(self): """ Retrieve a read-only subordinate mapping. All values are stringified, and sensitive values are masked. The subordinate mapping implements the context manager protocol for convenience. """ if self._masked is None: self._masked = MaskedDict(self) return self._masked
def masked(self): """ Retrieve a read-only subordinate mapping. All values are stringified, and sensitive values are masked. The subordinate mapping implements the context manager protocol for convenience. """ if self._masked is None: self._masked = MaskedDict(self) return self._masked
[ "Retrieve", "a", "read", "-", "only", "subordinate", "mapping", ".", "All", "values", "are", "stringified", "and", "sensitive", "values", "are", "masked", ".", "The", "subordinate", "mapping", "implements", "the", "context", "manager", "protocol", "for", "convenience", "." ]
rackerlabs/timid
python
https://github.com/rackerlabs/timid/blob/b1c6aa159ab380a033740f4aa392cf0d125e0ac6/timid/utils.py#L157-L168
[ "def", "masked", "(", "self", ")", ":", "if", "self", ".", "_masked", "is", "None", ":", "self", ".", "_masked", "=", "MaskedDict", "(", "self", ")", "return", "self", ".", "_masked" ]
b1c6aa159ab380a033740f4aa392cf0d125e0ac6
test
read
Build a file path from *paths* and return the contents.
setup.py
def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as file_handler: return file_handler.read()
def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as file_handler: return file_handler.read()
[ "Build", "a", "file", "path", "from", "*", "paths", "*", "and", "return", "the", "contents", "." ]
bkosciow/python_iot-1
python
https://github.com/bkosciow/python_iot-1/blob/32880760e0d218a686ebdb0b6ee3ce07e5cbf018/setup.py#L9-L12
[ "def", "read", "(", "*", "paths", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "*", "paths", ")", ",", "'r'", ")", "as", "file_handler", ":", "return", "file_handler", ".", "read", "(", ")" ]
32880760e0d218a686ebdb0b6ee3ce07e5cbf018
test
virtualenv_no_global
Return True if in a venv and no system site packages.
environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/locations.py
def virtualenv_no_global(): """ Return True if in a venv and no system site packages. """ #this mirrors the logic in virtualenv.py for locating the no-global-site-packages.txt file site_mod_dir = os.path.dirname(os.path.abspath(site.__file__)) no_global_file = os.path.join(site_mod_dir, 'no-global-site-packages.txt') if running_under_virtualenv() and os.path.isfile(no_global_file): return True
def virtualenv_no_global(): """ Return True if in a venv and no system site packages. """ #this mirrors the logic in virtualenv.py for locating the no-global-site-packages.txt file site_mod_dir = os.path.dirname(os.path.abspath(site.__file__)) no_global_file = os.path.join(site_mod_dir, 'no-global-site-packages.txt') if running_under_virtualenv() and os.path.isfile(no_global_file): return True
[ "Return", "True", "if", "in", "a", "venv", "and", "no", "system", "site", "packages", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/locations.py#L18-L26
[ "def", "virtualenv_no_global", "(", ")", ":", "#this mirrors the logic in virtualenv.py for locating the no-global-site-packages.txt file", "site_mod_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "site", ".", "__file__", ")", ")", "no_global_file", "=", "os", ".", "path", ".", "join", "(", "site_mod_dir", ",", "'no-global-site-packages.txt'", ")", "if", "running_under_virtualenv", "(", ")", "and", "os", ".", "path", ".", "isfile", "(", "no_global_file", ")", ":", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
pwordfreq
Parallel word frequency counter. view - An IPython DirectView fnames - The filenames containing the split data.
environment/share/doc/ipython/examples/parallel/davinci/pwordfreq.py
def pwordfreq(view, fnames): """Parallel word frequency counter. view - An IPython DirectView fnames - The filenames containing the split data. """ assert len(fnames) == len(view.targets) view.scatter('fname', fnames, flatten=True) ar = view.apply(wordfreq, Reference('fname')) freqs_list = ar.get() word_set = set() for f in freqs_list: word_set.update(f.keys()) freqs = dict(zip(word_set, repeat(0))) for f in freqs_list: for word, count in f.iteritems(): freqs[word] += count return freqs
def pwordfreq(view, fnames): """Parallel word frequency counter. view - An IPython DirectView fnames - The filenames containing the split data. """ assert len(fnames) == len(view.targets) view.scatter('fname', fnames, flatten=True) ar = view.apply(wordfreq, Reference('fname')) freqs_list = ar.get() word_set = set() for f in freqs_list: word_set.update(f.keys()) freqs = dict(zip(word_set, repeat(0))) for f in freqs_list: for word, count in f.iteritems(): freqs[word] += count return freqs
[ "Parallel", "word", "frequency", "counter", ".", "view", "-", "An", "IPython", "DirectView", "fnames", "-", "The", "filenames", "containing", "the", "split", "data", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/davinci/pwordfreq.py#L20-L37
[ "def", "pwordfreq", "(", "view", ",", "fnames", ")", ":", "assert", "len", "(", "fnames", ")", "==", "len", "(", "view", ".", "targets", ")", "view", ".", "scatter", "(", "'fname'", ",", "fnames", ",", "flatten", "=", "True", ")", "ar", "=", "view", ".", "apply", "(", "wordfreq", ",", "Reference", "(", "'fname'", ")", ")", "freqs_list", "=", "ar", ".", "get", "(", ")", "word_set", "=", "set", "(", ")", "for", "f", "in", "freqs_list", ":", "word_set", ".", "update", "(", "f", ".", "keys", "(", ")", ")", "freqs", "=", "dict", "(", "zip", "(", "word_set", ",", "repeat", "(", "0", ")", ")", ")", "for", "f", "in", "freqs_list", ":", "for", "word", ",", "count", "in", "f", ".", "iteritems", "(", ")", ":", "freqs", "[", "word", "]", "+=", "count", "return", "freqs" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
view_decorator
Convert a function based decorator into a class based decorator usable on class based Views. Can't subclass the `View` as it breaks inheritance (super in particular), so we monkey-patch instead. Based on http://stackoverflow.com/a/8429311
django_libretto/decorators.py
def view_decorator(function_decorator): """Convert a function based decorator into a class based decorator usable on class based Views. Can't subclass the `View` as it breaks inheritance (super in particular), so we monkey-patch instead. Based on http://stackoverflow.com/a/8429311 """ def simple_decorator(View): View.dispatch = method_decorator(function_decorator)(View.dispatch) return View return simple_decorator
def view_decorator(function_decorator): """Convert a function based decorator into a class based decorator usable on class based Views. Can't subclass the `View` as it breaks inheritance (super in particular), so we monkey-patch instead. Based on http://stackoverflow.com/a/8429311 """ def simple_decorator(View): View.dispatch = method_decorator(function_decorator)(View.dispatch) return View return simple_decorator
[ "Convert", "a", "function", "based", "decorator", "into", "a", "class", "based", "decorator", "usable", "on", "class", "based", "Views", "." ]
ze-phyr-us/django-libretto
python
https://github.com/ze-phyr-us/django-libretto/blob/b19d8aa21b9579ee91e81967a44d1c40f5588b17/django_libretto/decorators.py#L5-L19
[ "def", "view_decorator", "(", "function_decorator", ")", ":", "def", "simple_decorator", "(", "View", ")", ":", "View", ".", "dispatch", "=", "method_decorator", "(", "function_decorator", ")", "(", "View", ".", "dispatch", ")", "return", "View", "return", "simple_decorator" ]
b19d8aa21b9579ee91e81967a44d1c40f5588b17
test
default_aliases
Return list of shell aliases to auto-define.
environment/lib/python2.7/site-packages/IPython/core/alias.py
def default_aliases(): """Return list of shell aliases to auto-define. """ # Note: the aliases defined here should be safe to use on a kernel # regardless of what frontend it is attached to. Frontends that use a # kernel in-process can define additional aliases that will only work in # their case. For example, things like 'less' or 'clear' that manipulate # the terminal should NOT be declared here, as they will only work if the # kernel is running inside a true terminal, and not over the network. if os.name == 'posix': default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'), ('mv', 'mv -i'), ('rm', 'rm -i'), ('cp', 'cp -i'), ('cat', 'cat'), ] # Useful set of ls aliases. The GNU and BSD options are a little # different, so we make aliases that provide as similar as possible # behavior in ipython, by passing the right flags for each platform if sys.platform.startswith('linux'): ls_aliases = [('ls', 'ls -F --color'), # long ls ('ll', 'ls -F -o --color'), # ls normal files only ('lf', 'ls -F -o --color %l | grep ^-'), # ls symbolic links ('lk', 'ls -F -o --color %l | grep ^l'), # directories or links to directories, ('ldir', 'ls -F -o --color %l | grep /$'), # things which are executable ('lx', 'ls -F -o --color %l | grep ^-..x'), ] else: # BSD, OSX, etc. ls_aliases = [('ls', 'ls -F'), # long ls ('ll', 'ls -F -l'), # ls normal files only ('lf', 'ls -F -l %l | grep ^-'), # ls symbolic links ('lk', 'ls -F -l %l | grep ^l'), # directories or links to directories, ('ldir', 'ls -F -l %l | grep /$'), # things which are executable ('lx', 'ls -F -l %l | grep ^-..x'), ] default_aliases = default_aliases + ls_aliases elif os.name in ['nt', 'dos']: default_aliases = [('ls', 'dir /on'), ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'), ('mkdir', 'mkdir'), ('rmdir', 'rmdir'), ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'), ] else: default_aliases = [] return default_aliases
def default_aliases(): """Return list of shell aliases to auto-define. """ # Note: the aliases defined here should be safe to use on a kernel # regardless of what frontend it is attached to. Frontends that use a # kernel in-process can define additional aliases that will only work in # their case. For example, things like 'less' or 'clear' that manipulate # the terminal should NOT be declared here, as they will only work if the # kernel is running inside a true terminal, and not over the network. if os.name == 'posix': default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'), ('mv', 'mv -i'), ('rm', 'rm -i'), ('cp', 'cp -i'), ('cat', 'cat'), ] # Useful set of ls aliases. The GNU and BSD options are a little # different, so we make aliases that provide as similar as possible # behavior in ipython, by passing the right flags for each platform if sys.platform.startswith('linux'): ls_aliases = [('ls', 'ls -F --color'), # long ls ('ll', 'ls -F -o --color'), # ls normal files only ('lf', 'ls -F -o --color %l | grep ^-'), # ls symbolic links ('lk', 'ls -F -o --color %l | grep ^l'), # directories or links to directories, ('ldir', 'ls -F -o --color %l | grep /$'), # things which are executable ('lx', 'ls -F -o --color %l | grep ^-..x'), ] else: # BSD, OSX, etc. ls_aliases = [('ls', 'ls -F'), # long ls ('ll', 'ls -F -l'), # ls normal files only ('lf', 'ls -F -l %l | grep ^-'), # ls symbolic links ('lk', 'ls -F -l %l | grep ^l'), # directories or links to directories, ('ldir', 'ls -F -l %l | grep /$'), # things which are executable ('lx', 'ls -F -l %l | grep ^-..x'), ] default_aliases = default_aliases + ls_aliases elif os.name in ['nt', 'dos']: default_aliases = [('ls', 'dir /on'), ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'), ('mkdir', 'mkdir'), ('rmdir', 'rmdir'), ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'), ] else: default_aliases = [] return default_aliases
[ "Return", "list", "of", "shell", "aliases", "to", "auto", "-", "define", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/alias.py#L43-L98
[ "def", "default_aliases", "(", ")", ":", "# Note: the aliases defined here should be safe to use on a kernel", "# regardless of what frontend it is attached to. Frontends that use a", "# kernel in-process can define additional aliases that will only work in", "# their case. For example, things like 'less' or 'clear' that manipulate", "# the terminal should NOT be declared here, as they will only work if the", "# kernel is running inside a true terminal, and not over the network.", "if", "os", ".", "name", "==", "'posix'", ":", "default_aliases", "=", "[", "(", "'mkdir'", ",", "'mkdir'", ")", ",", "(", "'rmdir'", ",", "'rmdir'", ")", ",", "(", "'mv'", ",", "'mv -i'", ")", ",", "(", "'rm'", ",", "'rm -i'", ")", ",", "(", "'cp'", ",", "'cp -i'", ")", ",", "(", "'cat'", ",", "'cat'", ")", ",", "]", "# Useful set of ls aliases. The GNU and BSD options are a little", "# different, so we make aliases that provide as similar as possible", "# behavior in ipython, by passing the right flags for each platform", "if", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "ls_aliases", "=", "[", "(", "'ls'", ",", "'ls -F --color'", ")", ",", "# long ls", "(", "'ll'", ",", "'ls -F -o --color'", ")", ",", "# ls normal files only", "(", "'lf'", ",", "'ls -F -o --color %l | grep ^-'", ")", ",", "# ls symbolic links", "(", "'lk'", ",", "'ls -F -o --color %l | grep ^l'", ")", ",", "# directories or links to directories,", "(", "'ldir'", ",", "'ls -F -o --color %l | grep /$'", ")", ",", "# things which are executable", "(", "'lx'", ",", "'ls -F -o --color %l | grep ^-..x'", ")", ",", "]", "else", ":", "# BSD, OSX, etc.", "ls_aliases", "=", "[", "(", "'ls'", ",", "'ls -F'", ")", ",", "# long ls", "(", "'ll'", ",", "'ls -F -l'", ")", ",", "# ls normal files only", "(", "'lf'", ",", "'ls -F -l %l | grep ^-'", ")", ",", "# ls symbolic links", "(", "'lk'", ",", "'ls -F -l %l | grep ^l'", ")", ",", "# directories or links to directories,", "(", "'ldir'", ",", "'ls -F -l %l | grep /$'", ")", ",", "# things which are executable", "(", "'lx'", ",", "'ls -F -l %l | grep ^-..x'", ")", ",", "]", "default_aliases", "=", "default_aliases", "+", "ls_aliases", "elif", "os", ".", "name", "in", "[", "'nt'", ",", "'dos'", "]", ":", "default_aliases", "=", "[", "(", "'ls'", ",", "'dir /on'", ")", ",", "(", "'ddir'", ",", "'dir /ad /on'", ")", ",", "(", "'ldir'", ",", "'dir /ad /on'", ")", ",", "(", "'mkdir'", ",", "'mkdir'", ")", ",", "(", "'rmdir'", ",", "'rmdir'", ")", ",", "(", "'echo'", ",", "'echo'", ")", ",", "(", "'ren'", ",", "'ren'", ")", ",", "(", "'copy'", ",", "'copy'", ")", ",", "]", "else", ":", "default_aliases", "=", "[", "]", "return", "default_aliases" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AliasManager.soft_define_alias
Define an alias, but don't raise on an AliasError.
environment/lib/python2.7/site-packages/IPython/core/alias.py
def soft_define_alias(self, name, cmd): """Define an alias, but don't raise on an AliasError.""" try: self.define_alias(name, cmd) except AliasError, e: error("Invalid alias: %s" % e)
def soft_define_alias(self, name, cmd): """Define an alias, but don't raise on an AliasError.""" try: self.define_alias(name, cmd) except AliasError, e: error("Invalid alias: %s" % e)
[ "Define", "an", "alias", "but", "don", "t", "raise", "on", "an", "AliasError", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/alias.py#L150-L155
[ "def", "soft_define_alias", "(", "self", ",", "name", ",", "cmd", ")", ":", "try", ":", "self", ".", "define_alias", "(", "name", ",", "cmd", ")", "except", "AliasError", ",", "e", ":", "error", "(", "\"Invalid alias: %s\"", "%", "e", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AliasManager.define_alias
Define a new alias after validating it. This will raise an :exc:`AliasError` if there are validation problems.
environment/lib/python2.7/site-packages/IPython/core/alias.py
def define_alias(self, name, cmd): """Define a new alias after validating it. This will raise an :exc:`AliasError` if there are validation problems. """ nargs = self.validate_alias(name, cmd) self.alias_table[name] = (nargs, cmd)
def define_alias(self, name, cmd): """Define a new alias after validating it. This will raise an :exc:`AliasError` if there are validation problems. """ nargs = self.validate_alias(name, cmd) self.alias_table[name] = (nargs, cmd)
[ "Define", "a", "new", "alias", "after", "validating", "it", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/alias.py#L157-L164
[ "def", "define_alias", "(", "self", ",", "name", ",", "cmd", ")", ":", "nargs", "=", "self", ".", "validate_alias", "(", "name", ",", "cmd", ")", "self", ".", "alias_table", "[", "name", "]", "=", "(", "nargs", ",", "cmd", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AliasManager.validate_alias
Validate an alias and return the its number of arguments.
environment/lib/python2.7/site-packages/IPython/core/alias.py
def validate_alias(self, name, cmd): """Validate an alias and return the its number of arguments.""" if name in self.no_alias: raise InvalidAliasError("The name %s can't be aliased " "because it is a keyword or builtin." % name) if not (isinstance(cmd, basestring)): raise InvalidAliasError("An alias command must be a string, " "got: %r" % cmd) nargs = cmd.count('%s') if nargs>0 and cmd.find('%l')>=0: raise InvalidAliasError('The %s and %l specifiers are mutually ' 'exclusive in alias definitions.') return nargs
def validate_alias(self, name, cmd): """Validate an alias and return the its number of arguments.""" if name in self.no_alias: raise InvalidAliasError("The name %s can't be aliased " "because it is a keyword or builtin." % name) if not (isinstance(cmd, basestring)): raise InvalidAliasError("An alias command must be a string, " "got: %r" % cmd) nargs = cmd.count('%s') if nargs>0 and cmd.find('%l')>=0: raise InvalidAliasError('The %s and %l specifiers are mutually ' 'exclusive in alias definitions.') return nargs
[ "Validate", "an", "alias", "and", "return", "the", "its", "number", "of", "arguments", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/alias.py#L170-L182
[ "def", "validate_alias", "(", "self", ",", "name", ",", "cmd", ")", ":", "if", "name", "in", "self", ".", "no_alias", ":", "raise", "InvalidAliasError", "(", "\"The name %s can't be aliased \"", "\"because it is a keyword or builtin.\"", "%", "name", ")", "if", "not", "(", "isinstance", "(", "cmd", ",", "basestring", ")", ")", ":", "raise", "InvalidAliasError", "(", "\"An alias command must be a string, \"", "\"got: %r\"", "%", "cmd", ")", "nargs", "=", "cmd", ".", "count", "(", "'%s'", ")", "if", "nargs", ">", "0", "and", "cmd", ".", "find", "(", "'%l'", ")", ">=", "0", ":", "raise", "InvalidAliasError", "(", "'The %s and %l specifiers are mutually '", "'exclusive in alias definitions.'", ")", "return", "nargs" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AliasManager.call_alias
Call an alias given its name and the rest of the line.
environment/lib/python2.7/site-packages/IPython/core/alias.py
def call_alias(self, alias, rest=''): """Call an alias given its name and the rest of the line.""" cmd = self.transform_alias(alias, rest) try: self.shell.system(cmd) except: self.shell.showtraceback()
def call_alias(self, alias, rest=''): """Call an alias given its name and the rest of the line.""" cmd = self.transform_alias(alias, rest) try: self.shell.system(cmd) except: self.shell.showtraceback()
[ "Call", "an", "alias", "given", "its", "name", "and", "the", "rest", "of", "the", "line", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/alias.py#L184-L190
[ "def", "call_alias", "(", "self", ",", "alias", ",", "rest", "=", "''", ")", ":", "cmd", "=", "self", ".", "transform_alias", "(", "alias", ",", "rest", ")", "try", ":", "self", ".", "shell", ".", "system", "(", "cmd", ")", "except", ":", "self", ".", "shell", ".", "showtraceback", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AliasManager.transform_alias
Transform alias to system command string.
environment/lib/python2.7/site-packages/IPython/core/alias.py
def transform_alias(self, alias,rest=''): """Transform alias to system command string.""" nargs, cmd = self.alias_table[alias] if ' ' in cmd and os.path.isfile(cmd): cmd = '"%s"' % cmd # Expand the %l special to be the user's input line if cmd.find('%l') >= 0: cmd = cmd.replace('%l', rest) rest = '' if nargs==0: # Simple, argument-less aliases cmd = '%s %s' % (cmd, rest) else: # Handle aliases with positional arguments args = rest.split(None, nargs) if len(args) < nargs: raise AliasError('Alias <%s> requires %s arguments, %s given.' % (alias, nargs, len(args))) cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) return cmd
def transform_alias(self, alias,rest=''): """Transform alias to system command string.""" nargs, cmd = self.alias_table[alias] if ' ' in cmd and os.path.isfile(cmd): cmd = '"%s"' % cmd # Expand the %l special to be the user's input line if cmd.find('%l') >= 0: cmd = cmd.replace('%l', rest) rest = '' if nargs==0: # Simple, argument-less aliases cmd = '%s %s' % (cmd, rest) else: # Handle aliases with positional arguments args = rest.split(None, nargs) if len(args) < nargs: raise AliasError('Alias <%s> requires %s arguments, %s given.' % (alias, nargs, len(args))) cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:])) return cmd
[ "Transform", "alias", "to", "system", "command", "string", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/alias.py#L192-L213
[ "def", "transform_alias", "(", "self", ",", "alias", ",", "rest", "=", "''", ")", ":", "nargs", ",", "cmd", "=", "self", ".", "alias_table", "[", "alias", "]", "if", "' '", "in", "cmd", "and", "os", ".", "path", ".", "isfile", "(", "cmd", ")", ":", "cmd", "=", "'\"%s\"'", "%", "cmd", "# Expand the %l special to be the user's input line", "if", "cmd", ".", "find", "(", "'%l'", ")", ">=", "0", ":", "cmd", "=", "cmd", ".", "replace", "(", "'%l'", ",", "rest", ")", "rest", "=", "''", "if", "nargs", "==", "0", ":", "# Simple, argument-less aliases", "cmd", "=", "'%s %s'", "%", "(", "cmd", ",", "rest", ")", "else", ":", "# Handle aliases with positional arguments", "args", "=", "rest", ".", "split", "(", "None", ",", "nargs", ")", "if", "len", "(", "args", ")", "<", "nargs", ":", "raise", "AliasError", "(", "'Alias <%s> requires %s arguments, %s given.'", "%", "(", "alias", ",", "nargs", ",", "len", "(", "args", ")", ")", ")", "cmd", "=", "'%s %s'", "%", "(", "cmd", "%", "tuple", "(", "args", "[", ":", "nargs", "]", ")", ",", "' '", ".", "join", "(", "args", "[", "nargs", ":", "]", ")", ")", "return", "cmd" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AliasManager.expand_alias
Expand an alias in the command line Returns the provided command line, possibly with the first word (command) translated according to alias expansion rules. [ipython]|16> _ip.expand_aliases("np myfile.txt") <16> 'q:/opt/np/notepad++.exe myfile.txt'
environment/lib/python2.7/site-packages/IPython/core/alias.py
def expand_alias(self, line): """ Expand an alias in the command line Returns the provided command line, possibly with the first word (command) translated according to alias expansion rules. [ipython]|16> _ip.expand_aliases("np myfile.txt") <16> 'q:/opt/np/notepad++.exe myfile.txt' """ pre,_,fn,rest = split_user_input(line) res = pre + self.expand_aliases(fn, rest) return res
def expand_alias(self, line): """ Expand an alias in the command line Returns the provided command line, possibly with the first word (command) translated according to alias expansion rules. [ipython]|16> _ip.expand_aliases("np myfile.txt") <16> 'q:/opt/np/notepad++.exe myfile.txt' """ pre,_,fn,rest = split_user_input(line) res = pre + self.expand_aliases(fn, rest) return res
[ "Expand", "an", "alias", "in", "the", "command", "line" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/alias.py#L215-L227
[ "def", "expand_alias", "(", "self", ",", "line", ")", ":", "pre", ",", "_", ",", "fn", ",", "rest", "=", "split_user_input", "(", "line", ")", "res", "=", "pre", "+", "self", ".", "expand_aliases", "(", "fn", ",", "rest", ")", "return", "res" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AliasManager.expand_aliases
Expand multiple levels of aliases: if: alias foo bar /tmp alias baz foo then: baz huhhahhei -> bar /tmp huhhahhei
environment/lib/python2.7/site-packages/IPython/core/alias.py
def expand_aliases(self, fn, rest): """Expand multiple levels of aliases: if: alias foo bar /tmp alias baz foo then: baz huhhahhei -> bar /tmp huhhahhei """ line = fn + " " + rest done = set() while 1: pre,_,fn,rest = split_user_input(line, shell_line_split) if fn in self.alias_table: if fn in done: warn("Cyclic alias definition, repeated '%s'" % fn) return "" done.add(fn) l2 = self.transform_alias(fn, rest) if l2 == line: break # ls -> ls -F should not recurse forever if l2.split(None,1)[0] == line.split(None,1)[0]: line = l2 break line=l2 else: break return line
def expand_aliases(self, fn, rest): """Expand multiple levels of aliases: if: alias foo bar /tmp alias baz foo then: baz huhhahhei -> bar /tmp huhhahhei """ line = fn + " " + rest done = set() while 1: pre,_,fn,rest = split_user_input(line, shell_line_split) if fn in self.alias_table: if fn in done: warn("Cyclic alias definition, repeated '%s'" % fn) return "" done.add(fn) l2 = self.transform_alias(fn, rest) if l2 == line: break # ls -> ls -F should not recurse forever if l2.split(None,1)[0] == line.split(None,1)[0]: line = l2 break line=l2 else: break return line
[ "Expand", "multiple", "levels", "of", "aliases", ":" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/alias.py#L229-L263
[ "def", "expand_aliases", "(", "self", ",", "fn", ",", "rest", ")", ":", "line", "=", "fn", "+", "\" \"", "+", "rest", "done", "=", "set", "(", ")", "while", "1", ":", "pre", ",", "_", ",", "fn", ",", "rest", "=", "split_user_input", "(", "line", ",", "shell_line_split", ")", "if", "fn", "in", "self", ".", "alias_table", ":", "if", "fn", "in", "done", ":", "warn", "(", "\"Cyclic alias definition, repeated '%s'\"", "%", "fn", ")", "return", "\"\"", "done", ".", "add", "(", "fn", ")", "l2", "=", "self", ".", "transform_alias", "(", "fn", ",", "rest", ")", "if", "l2", "==", "line", ":", "break", "# ls -> ls -F should not recurse forever", "if", "l2", ".", "split", "(", "None", ",", "1", ")", "[", "0", "]", "==", "line", ".", "split", "(", "None", ",", "1", ")", "[", "0", "]", ":", "line", "=", "l2", "break", "line", "=", "l2", "else", ":", "break", "return", "line" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
shquote
Quote an argument for later parsing by shlex.split()
environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/alias.py
def shquote(arg): """Quote an argument for later parsing by shlex.split()""" for c in '"', "'", "\\", "#": if c in arg: return repr(arg) if arg.split()<>[arg]: return repr(arg) return arg
def shquote(arg): """Quote an argument for later parsing by shlex.split()""" for c in '"', "'", "\\", "#": if c in arg: return repr(arg) if arg.split()<>[arg]: return repr(arg) return arg
[ "Quote", "an", "argument", "for", "later", "parsing", "by", "shlex", ".", "split", "()" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/alias.py#L8-L14
[ "def", "shquote", "(", "arg", ")", ":", "for", "c", "in", "'\"'", ",", "\"'\"", ",", "\"\\\\\"", ",", "\"#\"", ":", "if", "c", "in", "arg", ":", "return", "repr", "(", "arg", ")", "if", "arg", ".", "split", "(", ")", "<>", "[", "arg", "]", ":", "return", "repr", "(", "arg", ")", "return", "arg" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
autohelp_directive
produces rst from nose help
environment/lib/python2.7/site-packages/nose/sphinx/pluginopts.py
def autohelp_directive(dirname, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """produces rst from nose help""" config = Config(parserClass=OptBucket, plugins=BuiltinPluginManager()) parser = config.getParser(TestProgram.usage()) rst = ViewList() for line in parser.format_help().split('\n'): rst.append(line, '<autodoc>') rst.append('Options', '<autodoc>') rst.append('-------', '<autodoc>') rst.append('', '<autodoc>') for opt in parser: rst.append(opt.options(), '<autodoc>') rst.append(' \n', '<autodoc>') rst.append(' ' + opt.help + '\n', '<autodoc>') rst.append('\n', '<autodoc>') node = nodes.section() node.document = state.document surrounding_title_styles = state.memo.title_styles surrounding_section_level = state.memo.section_level state.memo.title_styles = [] state.memo.section_level = 0 state.nested_parse(rst, 0, node, match_titles=1) state.memo.title_styles = surrounding_title_styles state.memo.section_level = surrounding_section_level return node.children
def autohelp_directive(dirname, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """produces rst from nose help""" config = Config(parserClass=OptBucket, plugins=BuiltinPluginManager()) parser = config.getParser(TestProgram.usage()) rst = ViewList() for line in parser.format_help().split('\n'): rst.append(line, '<autodoc>') rst.append('Options', '<autodoc>') rst.append('-------', '<autodoc>') rst.append('', '<autodoc>') for opt in parser: rst.append(opt.options(), '<autodoc>') rst.append(' \n', '<autodoc>') rst.append(' ' + opt.help + '\n', '<autodoc>') rst.append('\n', '<autodoc>') node = nodes.section() node.document = state.document surrounding_title_styles = state.memo.title_styles surrounding_section_level = state.memo.section_level state.memo.title_styles = [] state.memo.section_level = 0 state.nested_parse(rst, 0, node, match_titles=1) state.memo.title_styles = surrounding_title_styles state.memo.section_level = surrounding_section_level return node.children
[ "produces", "rst", "from", "nose", "help" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/sphinx/pluginopts.py#L113-L141
[ "def", "autohelp_directive", "(", "dirname", ",", "arguments", ",", "options", ",", "content", ",", "lineno", ",", "content_offset", ",", "block_text", ",", "state", ",", "state_machine", ")", ":", "config", "=", "Config", "(", "parserClass", "=", "OptBucket", ",", "plugins", "=", "BuiltinPluginManager", "(", ")", ")", "parser", "=", "config", ".", "getParser", "(", "TestProgram", ".", "usage", "(", ")", ")", "rst", "=", "ViewList", "(", ")", "for", "line", "in", "parser", ".", "format_help", "(", ")", ".", "split", "(", "'\\n'", ")", ":", "rst", ".", "append", "(", "line", ",", "'<autodoc>'", ")", "rst", ".", "append", "(", "'Options'", ",", "'<autodoc>'", ")", "rst", ".", "append", "(", "'-------'", ",", "'<autodoc>'", ")", "rst", ".", "append", "(", "''", ",", "'<autodoc>'", ")", "for", "opt", "in", "parser", ":", "rst", ".", "append", "(", "opt", ".", "options", "(", ")", ",", "'<autodoc>'", ")", "rst", ".", "append", "(", "' \\n'", ",", "'<autodoc>'", ")", "rst", ".", "append", "(", "' '", "+", "opt", ".", "help", "+", "'\\n'", ",", "'<autodoc>'", ")", "rst", ".", "append", "(", "'\\n'", ",", "'<autodoc>'", ")", "node", "=", "nodes", ".", "section", "(", ")", "node", ".", "document", "=", "state", ".", "document", "surrounding_title_styles", "=", "state", ".", "memo", ".", "title_styles", "surrounding_section_level", "=", "state", ".", "memo", ".", "section_level", "state", ".", "memo", ".", "title_styles", "=", "[", "]", "state", ".", "memo", ".", "section_level", "=", "0", "state", ".", "nested_parse", "(", "rst", ",", "0", ",", "node", ",", "match_titles", "=", "1", ")", "state", ".", "memo", ".", "title_styles", "=", "surrounding_title_styles", "state", ".", "memo", ".", "section_level", "=", "surrounding_section_level", "return", "node", ".", "children" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AnsiCodeProcessor.reset_sgr
Reset graphics attributs to their default values.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py
def reset_sgr(self): """ Reset graphics attributs to their default values. """ self.intensity = 0 self.italic = False self.bold = False self.underline = False self.foreground_color = None self.background_color = None
def reset_sgr(self): """ Reset graphics attributs to their default values. """ self.intensity = 0 self.italic = False self.bold = False self.underline = False self.foreground_color = None self.background_color = None
[ "Reset", "graphics", "attributs", "to", "their", "default", "values", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py#L76-L84
[ "def", "reset_sgr", "(", "self", ")", ":", "self", ".", "intensity", "=", "0", "self", ".", "italic", "=", "False", "self", ".", "bold", "=", "False", "self", ".", "underline", "=", "False", "self", ".", "foreground_color", "=", "None", "self", ".", "background_color", "=", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AnsiCodeProcessor.split_string
Yields substrings for which the same escape code applies.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py
def split_string(self, string): """ Yields substrings for which the same escape code applies. """ self.actions = [] start = 0 # strings ending with \r are assumed to be ending in \r\n since # \n is appended to output strings automatically. Accounting # for that, here. last_char = '\n' if len(string) > 0 and string[-1] == '\n' else None string = string[:-1] if last_char is not None else string for match in ANSI_OR_SPECIAL_PATTERN.finditer(string): raw = string[start:match.start()] substring = SPECIAL_PATTERN.sub(self._replace_special, raw) if substring or self.actions: yield substring self.actions = [] start = match.end() groups = filter(lambda x: x is not None, match.groups()) g0 = groups[0] if g0 == '\a': self.actions.append(BeepAction('beep')) yield None self.actions = [] elif g0 == '\r': self.actions.append(CarriageReturnAction('carriage-return')) yield None self.actions = [] elif g0 == '\b': self.actions.append(BackSpaceAction('backspace')) yield None self.actions = [] elif g0 == '\n' or g0 == '\r\n': self.actions.append(NewLineAction('newline')) yield g0 self.actions = [] else: params = [ param for param in groups[1].split(';') if param ] if g0.startswith('['): # Case 1: CSI code. try: params = map(int, params) except ValueError: # Silently discard badly formed codes. pass else: self.set_csi_code(groups[2], params) elif g0.startswith(']'): # Case 2: OSC code. self.set_osc_code(params) raw = string[start:] substring = SPECIAL_PATTERN.sub(self._replace_special, raw) if substring or self.actions: yield substring if last_char is not None: self.actions.append(NewLineAction('newline')) yield last_char
def split_string(self, string): """ Yields substrings for which the same escape code applies. """ self.actions = [] start = 0 # strings ending with \r are assumed to be ending in \r\n since # \n is appended to output strings automatically. Accounting # for that, here. last_char = '\n' if len(string) > 0 and string[-1] == '\n' else None string = string[:-1] if last_char is not None else string for match in ANSI_OR_SPECIAL_PATTERN.finditer(string): raw = string[start:match.start()] substring = SPECIAL_PATTERN.sub(self._replace_special, raw) if substring or self.actions: yield substring self.actions = [] start = match.end() groups = filter(lambda x: x is not None, match.groups()) g0 = groups[0] if g0 == '\a': self.actions.append(BeepAction('beep')) yield None self.actions = [] elif g0 == '\r': self.actions.append(CarriageReturnAction('carriage-return')) yield None self.actions = [] elif g0 == '\b': self.actions.append(BackSpaceAction('backspace')) yield None self.actions = [] elif g0 == '\n' or g0 == '\r\n': self.actions.append(NewLineAction('newline')) yield g0 self.actions = [] else: params = [ param for param in groups[1].split(';') if param ] if g0.startswith('['): # Case 1: CSI code. try: params = map(int, params) except ValueError: # Silently discard badly formed codes. pass else: self.set_csi_code(groups[2], params) elif g0.startswith(']'): # Case 2: OSC code. self.set_osc_code(params) raw = string[start:] substring = SPECIAL_PATTERN.sub(self._replace_special, raw) if substring or self.actions: yield substring if last_char is not None: self.actions.append(NewLineAction('newline')) yield last_char
[ "Yields", "substrings", "for", "which", "the", "same", "escape", "code", "applies", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py#L86-L147
[ "def", "split_string", "(", "self", ",", "string", ")", ":", "self", ".", "actions", "=", "[", "]", "start", "=", "0", "# strings ending with \\r are assumed to be ending in \\r\\n since", "# \\n is appended to output strings automatically. Accounting", "# for that, here.", "last_char", "=", "'\\n'", "if", "len", "(", "string", ")", ">", "0", "and", "string", "[", "-", "1", "]", "==", "'\\n'", "else", "None", "string", "=", "string", "[", ":", "-", "1", "]", "if", "last_char", "is", "not", "None", "else", "string", "for", "match", "in", "ANSI_OR_SPECIAL_PATTERN", ".", "finditer", "(", "string", ")", ":", "raw", "=", "string", "[", "start", ":", "match", ".", "start", "(", ")", "]", "substring", "=", "SPECIAL_PATTERN", ".", "sub", "(", "self", ".", "_replace_special", ",", "raw", ")", "if", "substring", "or", "self", ".", "actions", ":", "yield", "substring", "self", ".", "actions", "=", "[", "]", "start", "=", "match", ".", "end", "(", ")", "groups", "=", "filter", "(", "lambda", "x", ":", "x", "is", "not", "None", ",", "match", ".", "groups", "(", ")", ")", "g0", "=", "groups", "[", "0", "]", "if", "g0", "==", "'\\a'", ":", "self", ".", "actions", ".", "append", "(", "BeepAction", "(", "'beep'", ")", ")", "yield", "None", "self", ".", "actions", "=", "[", "]", "elif", "g0", "==", "'\\r'", ":", "self", ".", "actions", ".", "append", "(", "CarriageReturnAction", "(", "'carriage-return'", ")", ")", "yield", "None", "self", ".", "actions", "=", "[", "]", "elif", "g0", "==", "'\\b'", ":", "self", ".", "actions", ".", "append", "(", "BackSpaceAction", "(", "'backspace'", ")", ")", "yield", "None", "self", ".", "actions", "=", "[", "]", "elif", "g0", "==", "'\\n'", "or", "g0", "==", "'\\r\\n'", ":", "self", ".", "actions", ".", "append", "(", "NewLineAction", "(", "'newline'", ")", ")", "yield", "g0", "self", ".", "actions", "=", "[", "]", "else", ":", "params", "=", "[", "param", "for", "param", "in", "groups", "[", "1", "]", ".", "split", "(", "';'", ")", "if", "param", "]", "if", "g0", ".", "startswith", "(", "'['", ")", ":", "# Case 1: CSI code.", "try", ":", "params", "=", "map", "(", "int", ",", "params", ")", "except", "ValueError", ":", "# Silently discard badly formed codes.", "pass", "else", ":", "self", ".", "set_csi_code", "(", "groups", "[", "2", "]", ",", "params", ")", "elif", "g0", ".", "startswith", "(", "']'", ")", ":", "# Case 2: OSC code.", "self", ".", "set_osc_code", "(", "params", ")", "raw", "=", "string", "[", "start", ":", "]", "substring", "=", "SPECIAL_PATTERN", ".", "sub", "(", "self", ".", "_replace_special", ",", "raw", ")", "if", "substring", "or", "self", ".", "actions", ":", "yield", "substring", "if", "last_char", "is", "not", "None", ":", "self", ".", "actions", ".", "append", "(", "NewLineAction", "(", "'newline'", ")", ")", "yield", "last_char" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AnsiCodeProcessor.set_csi_code
Set attributes based on CSI (Control Sequence Introducer) code. Parameters ---------- command : str The code identifier, i.e. the final character in the sequence. params : sequence of integers, optional The parameter codes for the command.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py
def set_csi_code(self, command, params=[]): """ Set attributes based on CSI (Control Sequence Introducer) code. Parameters ---------- command : str The code identifier, i.e. the final character in the sequence. params : sequence of integers, optional The parameter codes for the command. """ if command == 'm': # SGR - Select Graphic Rendition if params: self.set_sgr_code(params) else: self.set_sgr_code([0]) elif (command == 'J' or # ED - Erase Data command == 'K'): # EL - Erase in Line code = params[0] if params else 0 if 0 <= code <= 2: area = 'screen' if command == 'J' else 'line' if code == 0: erase_to = 'end' elif code == 1: erase_to = 'start' elif code == 2: erase_to = 'all' self.actions.append(EraseAction('erase', area, erase_to)) elif (command == 'S' or # SU - Scroll Up command == 'T'): # SD - Scroll Down dir = 'up' if command == 'S' else 'down' count = params[0] if params else 1 self.actions.append(ScrollAction('scroll', dir, 'line', count))
def set_csi_code(self, command, params=[]): """ Set attributes based on CSI (Control Sequence Introducer) code. Parameters ---------- command : str The code identifier, i.e. the final character in the sequence. params : sequence of integers, optional The parameter codes for the command. """ if command == 'm': # SGR - Select Graphic Rendition if params: self.set_sgr_code(params) else: self.set_sgr_code([0]) elif (command == 'J' or # ED - Erase Data command == 'K'): # EL - Erase in Line code = params[0] if params else 0 if 0 <= code <= 2: area = 'screen' if command == 'J' else 'line' if code == 0: erase_to = 'end' elif code == 1: erase_to = 'start' elif code == 2: erase_to = 'all' self.actions.append(EraseAction('erase', area, erase_to)) elif (command == 'S' or # SU - Scroll Up command == 'T'): # SD - Scroll Down dir = 'up' if command == 'S' else 'down' count = params[0] if params else 1 self.actions.append(ScrollAction('scroll', dir, 'line', count))
[ "Set", "attributes", "based", "on", "CSI", "(", "Control", "Sequence", "Introducer", ")", "code", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py#L149-L183
[ "def", "set_csi_code", "(", "self", ",", "command", ",", "params", "=", "[", "]", ")", ":", "if", "command", "==", "'m'", ":", "# SGR - Select Graphic Rendition", "if", "params", ":", "self", ".", "set_sgr_code", "(", "params", ")", "else", ":", "self", ".", "set_sgr_code", "(", "[", "0", "]", ")", "elif", "(", "command", "==", "'J'", "or", "# ED - Erase Data", "command", "==", "'K'", ")", ":", "# EL - Erase in Line", "code", "=", "params", "[", "0", "]", "if", "params", "else", "0", "if", "0", "<=", "code", "<=", "2", ":", "area", "=", "'screen'", "if", "command", "==", "'J'", "else", "'line'", "if", "code", "==", "0", ":", "erase_to", "=", "'end'", "elif", "code", "==", "1", ":", "erase_to", "=", "'start'", "elif", "code", "==", "2", ":", "erase_to", "=", "'all'", "self", ".", "actions", ".", "append", "(", "EraseAction", "(", "'erase'", ",", "area", ",", "erase_to", ")", ")", "elif", "(", "command", "==", "'S'", "or", "# SU - Scroll Up", "command", "==", "'T'", ")", ":", "# SD - Scroll Down", "dir", "=", "'up'", "if", "command", "==", "'S'", "else", "'down'", "count", "=", "params", "[", "0", "]", "if", "params", "else", "1", "self", ".", "actions", ".", "append", "(", "ScrollAction", "(", "'scroll'", ",", "dir", ",", "'line'", ",", "count", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AnsiCodeProcessor.set_osc_code
Set attributes based on OSC (Operating System Command) parameters. Parameters ---------- params : sequence of str The parameters for the command.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py
def set_osc_code(self, params): """ Set attributes based on OSC (Operating System Command) parameters. Parameters ---------- params : sequence of str The parameters for the command. """ try: command = int(params.pop(0)) except (IndexError, ValueError): return if command == 4: # xterm-specific: set color number to color spec. try: color = int(params.pop(0)) spec = params.pop(0) self.color_map[color] = self._parse_xterm_color_spec(spec) except (IndexError, ValueError): pass
def set_osc_code(self, params): """ Set attributes based on OSC (Operating System Command) parameters. Parameters ---------- params : sequence of str The parameters for the command. """ try: command = int(params.pop(0)) except (IndexError, ValueError): return if command == 4: # xterm-specific: set color number to color spec. try: color = int(params.pop(0)) spec = params.pop(0) self.color_map[color] = self._parse_xterm_color_spec(spec) except (IndexError, ValueError): pass
[ "Set", "attributes", "based", "on", "OSC", "(", "Operating", "System", "Command", ")", "parameters", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py#L185-L205
[ "def", "set_osc_code", "(", "self", ",", "params", ")", ":", "try", ":", "command", "=", "int", "(", "params", ".", "pop", "(", "0", ")", ")", "except", "(", "IndexError", ",", "ValueError", ")", ":", "return", "if", "command", "==", "4", ":", "# xterm-specific: set color number to color spec.", "try", ":", "color", "=", "int", "(", "params", ".", "pop", "(", "0", ")", ")", "spec", "=", "params", ".", "pop", "(", "0", ")", "self", ".", "color_map", "[", "color", "]", "=", "self", ".", "_parse_xterm_color_spec", "(", "spec", ")", "except", "(", "IndexError", ",", "ValueError", ")", ":", "pass" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
AnsiCodeProcessor.set_sgr_code
Set attributes based on SGR (Select Graphic Rendition) codes. Parameters ---------- params : sequence of ints A list of SGR codes for one or more SGR commands. Usually this sequence will have one element per command, although certain xterm-specific commands requires multiple elements.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py
def set_sgr_code(self, params): """ Set attributes based on SGR (Select Graphic Rendition) codes. Parameters ---------- params : sequence of ints A list of SGR codes for one or more SGR commands. Usually this sequence will have one element per command, although certain xterm-specific commands requires multiple elements. """ # Always consume the first parameter. if not params: return code = params.pop(0) if code == 0: self.reset_sgr() elif code == 1: if self.bold_text_enabled: self.bold = True else: self.intensity = 1 elif code == 2: self.intensity = 0 elif code == 3: self.italic = True elif code == 4: self.underline = True elif code == 22: self.intensity = 0 self.bold = False elif code == 23: self.italic = False elif code == 24: self.underline = False elif code >= 30 and code <= 37: self.foreground_color = code - 30 elif code == 38 and params and params.pop(0) == 5: # xterm-specific: 256 color support. if params: self.foreground_color = params.pop(0) elif code == 39: self.foreground_color = None elif code >= 40 and code <= 47: self.background_color = code - 40 elif code == 48 and params and params.pop(0) == 5: # xterm-specific: 256 color support. if params: self.background_color = params.pop(0) elif code == 49: self.background_color = None # Recurse with unconsumed parameters. self.set_sgr_code(params)
def set_sgr_code(self, params): """ Set attributes based on SGR (Select Graphic Rendition) codes. Parameters ---------- params : sequence of ints A list of SGR codes for one or more SGR commands. Usually this sequence will have one element per command, although certain xterm-specific commands requires multiple elements. """ # Always consume the first parameter. if not params: return code = params.pop(0) if code == 0: self.reset_sgr() elif code == 1: if self.bold_text_enabled: self.bold = True else: self.intensity = 1 elif code == 2: self.intensity = 0 elif code == 3: self.italic = True elif code == 4: self.underline = True elif code == 22: self.intensity = 0 self.bold = False elif code == 23: self.italic = False elif code == 24: self.underline = False elif code >= 30 and code <= 37: self.foreground_color = code - 30 elif code == 38 and params and params.pop(0) == 5: # xterm-specific: 256 color support. if params: self.foreground_color = params.pop(0) elif code == 39: self.foreground_color = None elif code >= 40 and code <= 47: self.background_color = code - 40 elif code == 48 and params and params.pop(0) == 5: # xterm-specific: 256 color support. if params: self.background_color = params.pop(0) elif code == 49: self.background_color = None # Recurse with unconsumed parameters. self.set_sgr_code(params)
[ "Set", "attributes", "based", "on", "SGR", "(", "Select", "Graphic", "Rendition", ")", "codes", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py#L207-L260
[ "def", "set_sgr_code", "(", "self", ",", "params", ")", ":", "# Always consume the first parameter.", "if", "not", "params", ":", "return", "code", "=", "params", ".", "pop", "(", "0", ")", "if", "code", "==", "0", ":", "self", ".", "reset_sgr", "(", ")", "elif", "code", "==", "1", ":", "if", "self", ".", "bold_text_enabled", ":", "self", ".", "bold", "=", "True", "else", ":", "self", ".", "intensity", "=", "1", "elif", "code", "==", "2", ":", "self", ".", "intensity", "=", "0", "elif", "code", "==", "3", ":", "self", ".", "italic", "=", "True", "elif", "code", "==", "4", ":", "self", ".", "underline", "=", "True", "elif", "code", "==", "22", ":", "self", ".", "intensity", "=", "0", "self", ".", "bold", "=", "False", "elif", "code", "==", "23", ":", "self", ".", "italic", "=", "False", "elif", "code", "==", "24", ":", "self", ".", "underline", "=", "False", "elif", "code", ">=", "30", "and", "code", "<=", "37", ":", "self", ".", "foreground_color", "=", "code", "-", "30", "elif", "code", "==", "38", "and", "params", "and", "params", ".", "pop", "(", "0", ")", "==", "5", ":", "# xterm-specific: 256 color support.", "if", "params", ":", "self", ".", "foreground_color", "=", "params", ".", "pop", "(", "0", ")", "elif", "code", "==", "39", ":", "self", ".", "foreground_color", "=", "None", "elif", "code", ">=", "40", "and", "code", "<=", "47", ":", "self", ".", "background_color", "=", "code", "-", "40", "elif", "code", "==", "48", "and", "params", "and", "params", ".", "pop", "(", "0", ")", "==", "5", ":", "# xterm-specific: 256 color support.", "if", "params", ":", "self", ".", "background_color", "=", "params", ".", "pop", "(", "0", ")", "elif", "code", "==", "49", ":", "self", ".", "background_color", "=", "None", "# Recurse with unconsumed parameters.", "self", ".", "set_sgr_code", "(", "params", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
QtAnsiCodeProcessor.get_color
Returns a QColor for a given color code, or None if one cannot be constructed.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py
def get_color(self, color, intensity=0): """ Returns a QColor for a given color code, or None if one cannot be constructed. """ if color is None: return None # Adjust for intensity, if possible. if color < 8 and intensity > 0: color += 8 constructor = self.color_map.get(color, None) if isinstance(constructor, basestring): # If this is an X11 color name, we just hope there is a close SVG # color name. We could use QColor's static method # 'setAllowX11ColorNames()', but this is global and only available # on X11. It seems cleaner to aim for uniformity of behavior. return QtGui.QColor(constructor) elif isinstance(constructor, (tuple, list)): return QtGui.QColor(*constructor) return None
def get_color(self, color, intensity=0): """ Returns a QColor for a given color code, or None if one cannot be constructed. """ if color is None: return None # Adjust for intensity, if possible. if color < 8 and intensity > 0: color += 8 constructor = self.color_map.get(color, None) if isinstance(constructor, basestring): # If this is an X11 color name, we just hope there is a close SVG # color name. We could use QColor's static method # 'setAllowX11ColorNames()', but this is global and only available # on X11. It seems cleaner to aim for uniformity of behavior. return QtGui.QColor(constructor) elif isinstance(constructor, (tuple, list)): return QtGui.QColor(*constructor) return None
[ "Returns", "a", "QColor", "for", "a", "given", "color", "code", "or", "None", "if", "one", "cannot", "be", "constructed", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py#L309-L331
[ "def", "get_color", "(", "self", ",", "color", ",", "intensity", "=", "0", ")", ":", "if", "color", "is", "None", ":", "return", "None", "# Adjust for intensity, if possible.", "if", "color", "<", "8", "and", "intensity", ">", "0", ":", "color", "+=", "8", "constructor", "=", "self", ".", "color_map", ".", "get", "(", "color", ",", "None", ")", "if", "isinstance", "(", "constructor", ",", "basestring", ")", ":", "# If this is an X11 color name, we just hope there is a close SVG", "# color name. We could use QColor's static method", "# 'setAllowX11ColorNames()', but this is global and only available", "# on X11. It seems cleaner to aim for uniformity of behavior.", "return", "QtGui", ".", "QColor", "(", "constructor", ")", "elif", "isinstance", "(", "constructor", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "QtGui", ".", "QColor", "(", "*", "constructor", ")", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
QtAnsiCodeProcessor.get_format
Returns a QTextCharFormat that encodes the current style attributes.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py
def get_format(self): """ Returns a QTextCharFormat that encodes the current style attributes. """ format = QtGui.QTextCharFormat() # Set foreground color qcolor = self.get_color(self.foreground_color, self.intensity) if qcolor is not None: format.setForeground(qcolor) # Set background color qcolor = self.get_color(self.background_color, self.intensity) if qcolor is not None: format.setBackground(qcolor) # Set font weight/style options if self.bold: format.setFontWeight(QtGui.QFont.Bold) else: format.setFontWeight(QtGui.QFont.Normal) format.setFontItalic(self.italic) format.setFontUnderline(self.underline) return format
def get_format(self): """ Returns a QTextCharFormat that encodes the current style attributes. """ format = QtGui.QTextCharFormat() # Set foreground color qcolor = self.get_color(self.foreground_color, self.intensity) if qcolor is not None: format.setForeground(qcolor) # Set background color qcolor = self.get_color(self.background_color, self.intensity) if qcolor is not None: format.setBackground(qcolor) # Set font weight/style options if self.bold: format.setFontWeight(QtGui.QFont.Bold) else: format.setFontWeight(QtGui.QFont.Normal) format.setFontItalic(self.italic) format.setFontUnderline(self.underline) return format
[ "Returns", "a", "QTextCharFormat", "that", "encodes", "the", "current", "style", "attributes", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py#L333-L356
[ "def", "get_format", "(", "self", ")", ":", "format", "=", "QtGui", ".", "QTextCharFormat", "(", ")", "# Set foreground color", "qcolor", "=", "self", ".", "get_color", "(", "self", ".", "foreground_color", ",", "self", ".", "intensity", ")", "if", "qcolor", "is", "not", "None", ":", "format", ".", "setForeground", "(", "qcolor", ")", "# Set background color", "qcolor", "=", "self", ".", "get_color", "(", "self", ".", "background_color", ",", "self", ".", "intensity", ")", "if", "qcolor", "is", "not", "None", ":", "format", ".", "setBackground", "(", "qcolor", ")", "# Set font weight/style options", "if", "self", ".", "bold", ":", "format", ".", "setFontWeight", "(", "QtGui", ".", "QFont", ".", "Bold", ")", "else", ":", "format", ".", "setFontWeight", "(", "QtGui", ".", "QFont", ".", "Normal", ")", "format", ".", "setFontItalic", "(", "self", ".", "italic", ")", "format", ".", "setFontUnderline", "(", "self", ".", "underline", ")", "return", "format" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
QtAnsiCodeProcessor.set_background_color
Given a background color (a QColor), attempt to set a color map that will be aesthetically pleasing.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py
def set_background_color(self, color): """ Given a background color (a QColor), attempt to set a color map that will be aesthetically pleasing. """ # Set a new default color map. self.default_color_map = self.darkbg_color_map.copy() if color.value() >= 127: # Colors appropriate for a terminal with a light background. For # now, only use non-bright colors... for i in xrange(8): self.default_color_map[i + 8] = self.default_color_map[i] # ...and replace white with black. self.default_color_map[7] = self.default_color_map[15] = 'black' # Update the current color map with the new defaults. self.color_map.update(self.default_color_map)
def set_background_color(self, color): """ Given a background color (a QColor), attempt to set a color map that will be aesthetically pleasing. """ # Set a new default color map. self.default_color_map = self.darkbg_color_map.copy() if color.value() >= 127: # Colors appropriate for a terminal with a light background. For # now, only use non-bright colors... for i in xrange(8): self.default_color_map[i + 8] = self.default_color_map[i] # ...and replace white with black. self.default_color_map[7] = self.default_color_map[15] = 'black' # Update the current color map with the new defaults. self.color_map.update(self.default_color_map)
[ "Given", "a", "background", "color", "(", "a", "QColor", ")", "attempt", "to", "set", "a", "color", "map", "that", "will", "be", "aesthetically", "pleasing", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/ansi_code_processor.py#L358-L375
[ "def", "set_background_color", "(", "self", ",", "color", ")", ":", "# Set a new default color map.", "self", ".", "default_color_map", "=", "self", ".", "darkbg_color_map", ".", "copy", "(", ")", "if", "color", ".", "value", "(", ")", ">=", "127", ":", "# Colors appropriate for a terminal with a light background. For", "# now, only use non-bright colors...", "for", "i", "in", "xrange", "(", "8", ")", ":", "self", ".", "default_color_map", "[", "i", "+", "8", "]", "=", "self", ".", "default_color_map", "[", "i", "]", "# ...and replace white with black.", "self", ".", "default_color_map", "[", "7", "]", "=", "self", ".", "default_color_map", "[", "15", "]", "=", "'black'", "# Update the current color map with the new defaults.", "self", ".", "color_map", ".", "update", "(", "self", ".", "default_color_map", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
generate
Generate a one-time jwt with an age in seconds
onetimejwt/__init__.py
def generate(secret, age, **payload): """Generate a one-time jwt with an age in seconds""" jti = str(uuid.uuid1()) # random id if not payload: payload = {} payload['exp'] = int(time.time() + age) payload['jti'] = jti return jwt.encode(payload, decode_secret(secret))
def generate(secret, age, **payload): """Generate a one-time jwt with an age in seconds""" jti = str(uuid.uuid1()) # random id if not payload: payload = {} payload['exp'] = int(time.time() + age) payload['jti'] = jti return jwt.encode(payload, decode_secret(secret))
[ "Generate", "a", "one", "-", "time", "jwt", "with", "an", "age", "in", "seconds" ]
srevenant/onetimejwt
python
https://github.com/srevenant/onetimejwt/blob/f3ed561253eb4a8e1522c64f59bf64d275e9d315/onetimejwt/__init__.py#L80-L87
[ "def", "generate", "(", "secret", ",", "age", ",", "*", "*", "payload", ")", ":", "jti", "=", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", "# random id", "if", "not", "payload", ":", "payload", "=", "{", "}", "payload", "[", "'exp'", "]", "=", "int", "(", "time", ".", "time", "(", ")", "+", "age", ")", "payload", "[", "'jti'", "]", "=", "jti", "return", "jwt", ".", "encode", "(", "payload", ",", "decode_secret", "(", "secret", ")", ")" ]
f3ed561253eb4a8e1522c64f59bf64d275e9d315
test
mutex
use a thread lock on current method, if self.lock is defined
onetimejwt/__init__.py
def mutex(func): """use a thread lock on current method, if self.lock is defined""" def wrapper(*args, **kwargs): """Decorator Wrapper""" lock = args[0].lock lock.acquire(True) try: return func(*args, **kwargs) except: raise finally: lock.release() return wrapper
def mutex(func): """use a thread lock on current method, if self.lock is defined""" def wrapper(*args, **kwargs): """Decorator Wrapper""" lock = args[0].lock lock.acquire(True) try: return func(*args, **kwargs) except: raise finally: lock.release() return wrapper
[ "use", "a", "thread", "lock", "on", "current", "method", "if", "self", ".", "lock", "is", "defined" ]
srevenant/onetimejwt
python
https://github.com/srevenant/onetimejwt/blob/f3ed561253eb4a8e1522c64f59bf64d275e9d315/onetimejwt/__init__.py#L89-L102
[ "def", "mutex", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Decorator Wrapper\"\"\"", "lock", "=", "args", "[", "0", "]", ".", "lock", "lock", ".", "acquire", "(", "True", ")", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", ":", "raise", "finally", ":", "lock", ".", "release", "(", ")", "return", "wrapper" ]
f3ed561253eb4a8e1522c64f59bf64d275e9d315
test
Manager._clean
Run by housekeeper thread
onetimejwt/__init__.py
def _clean(self): """Run by housekeeper thread""" now = time.time() for jwt in self.jwts.keys(): if (now - self.jwts[jwt]) > (self.age * 2): del self.jwts[jwt]
def _clean(self): """Run by housekeeper thread""" now = time.time() for jwt in self.jwts.keys(): if (now - self.jwts[jwt]) > (self.age * 2): del self.jwts[jwt]
[ "Run", "by", "housekeeper", "thread" ]
srevenant/onetimejwt
python
https://github.com/srevenant/onetimejwt/blob/f3ed561253eb4a8e1522c64f59bf64d275e9d315/onetimejwt/__init__.py#L125-L130
[ "def", "_clean", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "for", "jwt", "in", "self", ".", "jwts", ".", "keys", "(", ")", ":", "if", "(", "now", "-", "self", ".", "jwts", "[", "jwt", "]", ")", ">", "(", "self", ".", "age", "*", "2", ")", ":", "del", "self", ".", "jwts", "[", "jwt", "]" ]
f3ed561253eb4a8e1522c64f59bf64d275e9d315
test
Manager.already_used
has this jwt been used?
onetimejwt/__init__.py
def already_used(self, tok): """has this jwt been used?""" if tok in self.jwts: return True self.jwts[tok] = time.time() return False
def already_used(self, tok): """has this jwt been used?""" if tok in self.jwts: return True self.jwts[tok] = time.time() return False
[ "has", "this", "jwt", "been", "used?" ]
srevenant/onetimejwt
python
https://github.com/srevenant/onetimejwt/blob/f3ed561253eb4a8e1522c64f59bf64d275e9d315/onetimejwt/__init__.py#L133-L138
[ "def", "already_used", "(", "self", ",", "tok", ")", ":", "if", "tok", "in", "self", ".", "jwts", ":", "return", "True", "self", ".", "jwts", "[", "tok", "]", "=", "time", ".", "time", "(", ")", "return", "False" ]
f3ed561253eb4a8e1522c64f59bf64d275e9d315
test
Manager.valid
is this token valid?
onetimejwt/__init__.py
def valid(self, token): """is this token valid?""" now = time.time() if 'Bearer ' in token: token = token[7:] data = None for secret in self.secrets: try: data = jwt.decode(token, secret) break except jwt.DecodeError: continue except jwt.ExpiredSignatureError: raise JwtFailed("Jwt expired") if not data: raise JwtFailed("Jwt cannot be decoded") exp = data.get('exp') if not exp: raise JwtFailed("Jwt missing expiration (exp)") if now - exp > self.age: raise JwtFailed("Jwt bad expiration - greater than I want to accept") jti = data.get('jti') if not jti: raise JwtFailed("Jwt missing one-time id (jti)") if self.already_used(jti): raise JwtFailed("Jwt re-use disallowed (jti={})".format(jti)) return data
def valid(self, token): """is this token valid?""" now = time.time() if 'Bearer ' in token: token = token[7:] data = None for secret in self.secrets: try: data = jwt.decode(token, secret) break except jwt.DecodeError: continue except jwt.ExpiredSignatureError: raise JwtFailed("Jwt expired") if not data: raise JwtFailed("Jwt cannot be decoded") exp = data.get('exp') if not exp: raise JwtFailed("Jwt missing expiration (exp)") if now - exp > self.age: raise JwtFailed("Jwt bad expiration - greater than I want to accept") jti = data.get('jti') if not jti: raise JwtFailed("Jwt missing one-time id (jti)") if self.already_used(jti): raise JwtFailed("Jwt re-use disallowed (jti={})".format(jti)) return data
[ "is", "this", "token", "valid?" ]
srevenant/onetimejwt
python
https://github.com/srevenant/onetimejwt/blob/f3ed561253eb4a8e1522c64f59bf64d275e9d315/onetimejwt/__init__.py#L140-L174
[ "def", "valid", "(", "self", ",", "token", ")", ":", "now", "=", "time", ".", "time", "(", ")", "if", "'Bearer '", "in", "token", ":", "token", "=", "token", "[", "7", ":", "]", "data", "=", "None", "for", "secret", "in", "self", ".", "secrets", ":", "try", ":", "data", "=", "jwt", ".", "decode", "(", "token", ",", "secret", ")", "break", "except", "jwt", ".", "DecodeError", ":", "continue", "except", "jwt", ".", "ExpiredSignatureError", ":", "raise", "JwtFailed", "(", "\"Jwt expired\"", ")", "if", "not", "data", ":", "raise", "JwtFailed", "(", "\"Jwt cannot be decoded\"", ")", "exp", "=", "data", ".", "get", "(", "'exp'", ")", "if", "not", "exp", ":", "raise", "JwtFailed", "(", "\"Jwt missing expiration (exp)\"", ")", "if", "now", "-", "exp", ">", "self", ".", "age", ":", "raise", "JwtFailed", "(", "\"Jwt bad expiration - greater than I want to accept\"", ")", "jti", "=", "data", ".", "get", "(", "'jti'", ")", "if", "not", "jti", ":", "raise", "JwtFailed", "(", "\"Jwt missing one-time id (jti)\"", ")", "if", "self", ".", "already_used", "(", "jti", ")", ":", "raise", "JwtFailed", "(", "\"Jwt re-use disallowed (jti={})\"", ".", "format", "(", "jti", ")", ")", "return", "data" ]
f3ed561253eb4a8e1522c64f59bf64d275e9d315
test
split_lines
split likely multiline text into lists of strings For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will reverse the effects of ``split_lines(nb)``. Used when writing JSON files.
environment/lib/python2.7/site-packages/IPython/nbformat/v2/rwbase.py
def split_lines(nb): """split likely multiline text into lists of strings For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will reverse the effects of ``split_lines(nb)``. Used when writing JSON files. """ for ws in nb.worksheets: for cell in ws.cells: if cell.cell_type == 'code': if 'input' in cell and isinstance(cell.input, basestring): cell.input = cell.input.splitlines() for output in cell.outputs: for key in _multiline_outputs: item = output.get(key, None) if isinstance(item, basestring): output[key] = item.splitlines() else: # text cell for key in ['source', 'rendered']: item = cell.get(key, None) if isinstance(item, basestring): cell[key] = item.splitlines() return nb
def split_lines(nb): """split likely multiline text into lists of strings For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will reverse the effects of ``split_lines(nb)``. Used when writing JSON files. """ for ws in nb.worksheets: for cell in ws.cells: if cell.cell_type == 'code': if 'input' in cell and isinstance(cell.input, basestring): cell.input = cell.input.splitlines() for output in cell.outputs: for key in _multiline_outputs: item = output.get(key, None) if isinstance(item, basestring): output[key] = item.splitlines() else: # text cell for key in ['source', 'rendered']: item = cell.get(key, None) if isinstance(item, basestring): cell[key] = item.splitlines() return nb
[ "split", "likely", "multiline", "text", "into", "lists", "of", "strings", "For", "file", "output", "more", "friendly", "to", "line", "-", "based", "VCS", ".", "rejoin_lines", "(", "nb", ")", "will", "reverse", "the", "effects", "of", "split_lines", "(", "nb", ")", ".", "Used", "when", "writing", "JSON", "files", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/v2/rwbase.py#L75-L98
[ "def", "split_lines", "(", "nb", ")", ":", "for", "ws", "in", "nb", ".", "worksheets", ":", "for", "cell", "in", "ws", ".", "cells", ":", "if", "cell", ".", "cell_type", "==", "'code'", ":", "if", "'input'", "in", "cell", "and", "isinstance", "(", "cell", ".", "input", ",", "basestring", ")", ":", "cell", ".", "input", "=", "cell", ".", "input", ".", "splitlines", "(", ")", "for", "output", "in", "cell", ".", "outputs", ":", "for", "key", "in", "_multiline_outputs", ":", "item", "=", "output", ".", "get", "(", "key", ",", "None", ")", "if", "isinstance", "(", "item", ",", "basestring", ")", ":", "output", "[", "key", "]", "=", "item", ".", "splitlines", "(", ")", "else", ":", "# text cell", "for", "key", "in", "[", "'source'", ",", "'rendered'", "]", ":", "item", "=", "cell", ".", "get", "(", "key", ",", "None", ")", "if", "isinstance", "(", "item", ",", "basestring", ")", ":", "cell", "[", "key", "]", "=", "item", ".", "splitlines", "(", ")", "return", "nb" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
NotebookWriter.write
Write a notebook to a file like object
environment/lib/python2.7/site-packages/IPython/nbformat/v2/rwbase.py
def write(self, nb, fp, **kwargs): """Write a notebook to a file like object""" return fp.write(self.writes(nb,**kwargs))
def write(self, nb, fp, **kwargs): """Write a notebook to a file like object""" return fp.write(self.writes(nb,**kwargs))
[ "Write", "a", "notebook", "to", "a", "file", "like", "object" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/v2/rwbase.py#L160-L162
[ "def", "write", "(", "self", ",", "nb", ",", "fp", ",", "*", "*", "kwargs", ")", ":", "return", "fp", ".", "write", "(", "self", ".", "writes", "(", "nb", ",", "*", "*", "kwargs", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
semaphore
use `Semaphore` to keep func access thread-safety. example: ``` py @semaphore(3) def func(): pass ```
jasily/threads/decorators.py
def semaphore(count: int, bounded: bool=False): ''' use `Semaphore` to keep func access thread-safety. example: ``` py @semaphore(3) def func(): pass ``` ''' lock_type = threading.BoundedSemaphore if bounded else threading.Semaphore lock_obj = lock_type(value=count) return with_it(lock_obj)
def semaphore(count: int, bounded: bool=False): ''' use `Semaphore` to keep func access thread-safety. example: ``` py @semaphore(3) def func(): pass ``` ''' lock_type = threading.BoundedSemaphore if bounded else threading.Semaphore lock_obj = lock_type(value=count) return with_it(lock_obj)
[ "use", "Semaphore", "to", "keep", "func", "access", "thread", "-", "safety", "." ]
Jasily/jasily-python
python
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/threads/decorators.py#L45-L60
[ "def", "semaphore", "(", "count", ":", "int", ",", "bounded", ":", "bool", "=", "False", ")", ":", "lock_type", "=", "threading", ".", "BoundedSemaphore", "if", "bounded", "else", "threading", ".", "Semaphore", "lock_obj", "=", "lock_type", "(", "value", "=", "count", ")", "return", "with_it", "(", "lock_obj", ")" ]
1c821a120ebbbbc3c5761f5f1e8a73588059242a
test
inputhook_glut
Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance.
environment/lib/python2.7/site-packages/IPython/lib/inputhookglut.py
def inputhook_glut(): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. signal.signal(signal.SIGINT, glut_int_handler) try: t = clock() # Make sure the default window is set after a window has been closed if glut.glutGetWindow() == 0: glut.glutSetWindow( 1 ) glutMainLoopEvent() return 0 while not stdin_ready(): glutMainLoopEvent() # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 5*60.0: # print 'Sleep for 5 s' # dbg time.sleep(5.0) elif used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) except KeyboardInterrupt: pass return 0
def inputhook_glut(): """Run the pyglet event loop by processing pending events only. This keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. signal.signal(signal.SIGINT, glut_int_handler) try: t = clock() # Make sure the default window is set after a window has been closed if glut.glutGetWindow() == 0: glut.glutSetWindow( 1 ) glutMainLoopEvent() return 0 while not stdin_ready(): glutMainLoopEvent() # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 5*60.0: # print 'Sleep for 5 s' # dbg time.sleep(5.0) elif used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) except KeyboardInterrupt: pass return 0
[ "Run", "the", "pyglet", "event", "loop", "by", "processing", "pending", "events", "only", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/inputhookglut.py#L126-L176
[ "def", "inputhook_glut", "(", ")", ":", "# We need to protect against a user pressing Control-C when IPython is", "# idle and this is running. We trap KeyboardInterrupt and pass.", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "glut_int_handler", ")", "try", ":", "t", "=", "clock", "(", ")", "# Make sure the default window is set after a window has been closed", "if", "glut", ".", "glutGetWindow", "(", ")", "==", "0", ":", "glut", ".", "glutSetWindow", "(", "1", ")", "glutMainLoopEvent", "(", ")", "return", "0", "while", "not", "stdin_ready", "(", ")", ":", "glutMainLoopEvent", "(", ")", "# We need to sleep at this point to keep the idle CPU load", "# low. However, if sleep to long, GUI response is poor. As", "# a compromise, we watch how often GUI events are being processed", "# and switch between a short and long sleep time. Here are some", "# stats useful in helping to tune this.", "# time CPU load", "# 0.001 13%", "# 0.005 3%", "# 0.01 1.5%", "# 0.05 0.5%", "used_time", "=", "clock", "(", ")", "-", "t", "if", "used_time", ">", "5", "*", "60.0", ":", "# print 'Sleep for 5 s' # dbg", "time", ".", "sleep", "(", "5.0", ")", "elif", "used_time", ">", "10.0", ":", "# print 'Sleep for 1 s' # dbg", "time", ".", "sleep", "(", "1.0", ")", "elif", "used_time", ">", "0.1", ":", "# Few GUI events coming in, so we can sleep longer", "# print 'Sleep for 0.05 s' # dbg", "time", ".", "sleep", "(", "0.05", ")", "else", ":", "# Many GUI events coming in, so sleep only very little", "time", ".", "sleep", "(", "0.001", ")", "except", "KeyboardInterrupt", ":", "pass", "return", "0" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
commonprefix
Get common prefix for completions Return the longest common prefix of a list of strings, but with special treatment of escape characters that might precede commands in IPython, such as %magic functions. Used in tab completion. For a more general function, see os.path.commonprefix
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def commonprefix(items): """Get common prefix for completions Return the longest common prefix of a list of strings, but with special treatment of escape characters that might precede commands in IPython, such as %magic functions. Used in tab completion. For a more general function, see os.path.commonprefix """ # the last item will always have the least leading % symbol # min / max are first/last in alphabetical order first_match = ESCAPE_RE.match(min(items)) last_match = ESCAPE_RE.match(max(items)) # common suffix is (common prefix of reversed items) reversed if first_match and last_match: prefix = os.path.commonprefix((first_match.group(0)[::-1], last_match.group(0)[::-1]))[::-1] else: prefix = '' items = [s.lstrip(ESCAPE_CHARS) for s in items] return prefix+os.path.commonprefix(items)
def commonprefix(items): """Get common prefix for completions Return the longest common prefix of a list of strings, but with special treatment of escape characters that might precede commands in IPython, such as %magic functions. Used in tab completion. For a more general function, see os.path.commonprefix """ # the last item will always have the least leading % symbol # min / max are first/last in alphabetical order first_match = ESCAPE_RE.match(min(items)) last_match = ESCAPE_RE.match(max(items)) # common suffix is (common prefix of reversed items) reversed if first_match and last_match: prefix = os.path.commonprefix((first_match.group(0)[::-1], last_match.group(0)[::-1]))[::-1] else: prefix = '' items = [s.lstrip(ESCAPE_CHARS) for s in items] return prefix+os.path.commonprefix(items)
[ "Get", "common", "prefix", "for", "completions" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L38-L58
[ "def", "commonprefix", "(", "items", ")", ":", "# the last item will always have the least leading % symbol", "# min / max are first/last in alphabetical order", "first_match", "=", "ESCAPE_RE", ".", "match", "(", "min", "(", "items", ")", ")", "last_match", "=", "ESCAPE_RE", ".", "match", "(", "max", "(", "items", ")", ")", "# common suffix is (common prefix of reversed items) reversed", "if", "first_match", "and", "last_match", ":", "prefix", "=", "os", ".", "path", ".", "commonprefix", "(", "(", "first_match", ".", "group", "(", "0", ")", "[", ":", ":", "-", "1", "]", ",", "last_match", ".", "group", "(", "0", ")", "[", ":", ":", "-", "1", "]", ")", ")", "[", ":", ":", "-", "1", "]", "else", ":", "prefix", "=", "''", "items", "=", "[", "s", ".", "lstrip", "(", "ESCAPE_CHARS", ")", "for", "s", "in", "items", "]", "return", "prefix", "+", "os", ".", "path", ".", "commonprefix", "(", "items", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget.eventFilter
Reimplemented to ensure a console-like behavior in the underlying text widgets.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def eventFilter(self, obj, event): """ Reimplemented to ensure a console-like behavior in the underlying text widgets. """ etype = event.type() if etype == QtCore.QEvent.KeyPress: # Re-map keys for all filtered widgets. key = event.key() if self._control_key_down(event.modifiers()) and \ key in self._ctrl_down_remap: new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, self._ctrl_down_remap[key], QtCore.Qt.NoModifier) QtGui.qApp.sendEvent(obj, new_event) return True elif obj == self._control: return self._event_filter_console_keypress(event) elif obj == self._page_control: return self._event_filter_page_keypress(event) # Make middle-click paste safe. elif etype == QtCore.QEvent.MouseButtonRelease and \ event.button() == QtCore.Qt.MidButton and \ obj == self._control.viewport(): cursor = self._control.cursorForPosition(event.pos()) self._control.setTextCursor(cursor) self.paste(QtGui.QClipboard.Selection) return True # Manually adjust the scrollbars *after* a resize event is dispatched. elif etype == QtCore.QEvent.Resize and not self._filter_resize: self._filter_resize = True QtGui.qApp.sendEvent(obj, event) self._adjust_scrollbars() self._filter_resize = False return True # Override shortcuts for all filtered widgets. elif etype == QtCore.QEvent.ShortcutOverride and \ self.override_shortcuts and \ self._control_key_down(event.modifiers()) and \ event.key() in self._shortcuts: event.accept() # Ensure that drags are safe. The problem is that the drag starting # logic, which determines whether the drag is a Copy or Move, is locked # down in QTextControl. If the widget is editable, which it must be if # we're not executing, the drag will be a Move. The following hack # prevents QTextControl from deleting the text by clearing the selection # when a drag leave event originating from this widget is dispatched. # The fact that we have to clear the user's selection is unfortunate, # but the alternative--trying to prevent Qt from using its hardwired # drag logic and writing our own--is worse. elif etype == QtCore.QEvent.DragEnter and \ obj == self._control.viewport() and \ event.source() == self._control.viewport(): self._filter_drag = True elif etype == QtCore.QEvent.DragLeave and \ obj == self._control.viewport() and \ self._filter_drag: cursor = self._control.textCursor() cursor.clearSelection() self._control.setTextCursor(cursor) self._filter_drag = False # Ensure that drops are safe. elif etype == QtCore.QEvent.Drop and obj == self._control.viewport(): cursor = self._control.cursorForPosition(event.pos()) if self._in_buffer(cursor.position()): text = event.mimeData().text() self._insert_plain_text_into_buffer(cursor, text) # Qt is expecting to get something here--drag and drop occurs in its # own event loop. Send a DragLeave event to end it. QtGui.qApp.sendEvent(obj, QtGui.QDragLeaveEvent()) return True # Handle scrolling of the vsplit pager. This hack attempts to solve # problems with tearing of the help text inside the pager window. This # happens only on Mac OS X with both PySide and PyQt. This fix isn't # perfect but makes the pager more usable. elif etype in self._pager_scroll_events and \ obj == self._page_control: self._page_control.repaint() return True return super(ConsoleWidget, self).eventFilter(obj, event)
def eventFilter(self, obj, event): """ Reimplemented to ensure a console-like behavior in the underlying text widgets. """ etype = event.type() if etype == QtCore.QEvent.KeyPress: # Re-map keys for all filtered widgets. key = event.key() if self._control_key_down(event.modifiers()) and \ key in self._ctrl_down_remap: new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, self._ctrl_down_remap[key], QtCore.Qt.NoModifier) QtGui.qApp.sendEvent(obj, new_event) return True elif obj == self._control: return self._event_filter_console_keypress(event) elif obj == self._page_control: return self._event_filter_page_keypress(event) # Make middle-click paste safe. elif etype == QtCore.QEvent.MouseButtonRelease and \ event.button() == QtCore.Qt.MidButton and \ obj == self._control.viewport(): cursor = self._control.cursorForPosition(event.pos()) self._control.setTextCursor(cursor) self.paste(QtGui.QClipboard.Selection) return True # Manually adjust the scrollbars *after* a resize event is dispatched. elif etype == QtCore.QEvent.Resize and not self._filter_resize: self._filter_resize = True QtGui.qApp.sendEvent(obj, event) self._adjust_scrollbars() self._filter_resize = False return True # Override shortcuts for all filtered widgets. elif etype == QtCore.QEvent.ShortcutOverride and \ self.override_shortcuts and \ self._control_key_down(event.modifiers()) and \ event.key() in self._shortcuts: event.accept() # Ensure that drags are safe. The problem is that the drag starting # logic, which determines whether the drag is a Copy or Move, is locked # down in QTextControl. If the widget is editable, which it must be if # we're not executing, the drag will be a Move. The following hack # prevents QTextControl from deleting the text by clearing the selection # when a drag leave event originating from this widget is dispatched. # The fact that we have to clear the user's selection is unfortunate, # but the alternative--trying to prevent Qt from using its hardwired # drag logic and writing our own--is worse. elif etype == QtCore.QEvent.DragEnter and \ obj == self._control.viewport() and \ event.source() == self._control.viewport(): self._filter_drag = True elif etype == QtCore.QEvent.DragLeave and \ obj == self._control.viewport() and \ self._filter_drag: cursor = self._control.textCursor() cursor.clearSelection() self._control.setTextCursor(cursor) self._filter_drag = False # Ensure that drops are safe. elif etype == QtCore.QEvent.Drop and obj == self._control.viewport(): cursor = self._control.cursorForPosition(event.pos()) if self._in_buffer(cursor.position()): text = event.mimeData().text() self._insert_plain_text_into_buffer(cursor, text) # Qt is expecting to get something here--drag and drop occurs in its # own event loop. Send a DragLeave event to end it. QtGui.qApp.sendEvent(obj, QtGui.QDragLeaveEvent()) return True # Handle scrolling of the vsplit pager. This hack attempts to solve # problems with tearing of the help text inside the pager window. This # happens only on Mac OS X with both PySide and PyQt. This fix isn't # perfect but makes the pager more usable. elif etype in self._pager_scroll_events and \ obj == self._page_control: self._page_control.repaint() return True return super(ConsoleWidget, self).eventFilter(obj, event)
[ "Reimplemented", "to", "ensure", "a", "console", "-", "like", "behavior", "in", "the", "underlying", "text", "widgets", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L347-L435
[ "def", "eventFilter", "(", "self", ",", "obj", ",", "event", ")", ":", "etype", "=", "event", ".", "type", "(", ")", "if", "etype", "==", "QtCore", ".", "QEvent", ".", "KeyPress", ":", "# Re-map keys for all filtered widgets.", "key", "=", "event", ".", "key", "(", ")", "if", "self", ".", "_control_key_down", "(", "event", ".", "modifiers", "(", ")", ")", "and", "key", "in", "self", ".", "_ctrl_down_remap", ":", "new_event", "=", "QtGui", ".", "QKeyEvent", "(", "QtCore", ".", "QEvent", ".", "KeyPress", ",", "self", ".", "_ctrl_down_remap", "[", "key", "]", ",", "QtCore", ".", "Qt", ".", "NoModifier", ")", "QtGui", ".", "qApp", ".", "sendEvent", "(", "obj", ",", "new_event", ")", "return", "True", "elif", "obj", "==", "self", ".", "_control", ":", "return", "self", ".", "_event_filter_console_keypress", "(", "event", ")", "elif", "obj", "==", "self", ".", "_page_control", ":", "return", "self", ".", "_event_filter_page_keypress", "(", "event", ")", "# Make middle-click paste safe.", "elif", "etype", "==", "QtCore", ".", "QEvent", ".", "MouseButtonRelease", "and", "event", ".", "button", "(", ")", "==", "QtCore", ".", "Qt", ".", "MidButton", "and", "obj", "==", "self", ".", "_control", ".", "viewport", "(", ")", ":", "cursor", "=", "self", ".", "_control", ".", "cursorForPosition", "(", "event", ".", "pos", "(", ")", ")", "self", ".", "_control", ".", "setTextCursor", "(", "cursor", ")", "self", ".", "paste", "(", "QtGui", ".", "QClipboard", ".", "Selection", ")", "return", "True", "# Manually adjust the scrollbars *after* a resize event is dispatched.", "elif", "etype", "==", "QtCore", ".", "QEvent", ".", "Resize", "and", "not", "self", ".", "_filter_resize", ":", "self", ".", "_filter_resize", "=", "True", "QtGui", ".", "qApp", ".", "sendEvent", "(", "obj", ",", "event", ")", "self", ".", "_adjust_scrollbars", "(", ")", "self", ".", "_filter_resize", "=", "False", "return", "True", "# Override shortcuts for all filtered widgets.", "elif", "etype", "==", "QtCore", ".", "QEvent", ".", "ShortcutOverride", "and", "self", ".", "override_shortcuts", "and", "self", ".", "_control_key_down", "(", "event", ".", "modifiers", "(", ")", ")", "and", "event", ".", "key", "(", ")", "in", "self", ".", "_shortcuts", ":", "event", ".", "accept", "(", ")", "# Ensure that drags are safe. The problem is that the drag starting", "# logic, which determines whether the drag is a Copy or Move, is locked", "# down in QTextControl. If the widget is editable, which it must be if", "# we're not executing, the drag will be a Move. The following hack", "# prevents QTextControl from deleting the text by clearing the selection", "# when a drag leave event originating from this widget is dispatched.", "# The fact that we have to clear the user's selection is unfortunate,", "# but the alternative--trying to prevent Qt from using its hardwired", "# drag logic and writing our own--is worse.", "elif", "etype", "==", "QtCore", ".", "QEvent", ".", "DragEnter", "and", "obj", "==", "self", ".", "_control", ".", "viewport", "(", ")", "and", "event", ".", "source", "(", ")", "==", "self", ".", "_control", ".", "viewport", "(", ")", ":", "self", ".", "_filter_drag", "=", "True", "elif", "etype", "==", "QtCore", ".", "QEvent", ".", "DragLeave", "and", "obj", "==", "self", ".", "_control", ".", "viewport", "(", ")", "and", "self", ".", "_filter_drag", ":", "cursor", "=", "self", ".", "_control", ".", "textCursor", "(", ")", "cursor", ".", "clearSelection", "(", ")", "self", ".", "_control", ".", "setTextCursor", "(", "cursor", ")", "self", ".", "_filter_drag", "=", "False", "# Ensure that drops are safe.", "elif", "etype", "==", "QtCore", ".", "QEvent", ".", "Drop", "and", "obj", "==", "self", ".", "_control", ".", "viewport", "(", ")", ":", "cursor", "=", "self", ".", "_control", ".", "cursorForPosition", "(", "event", ".", "pos", "(", ")", ")", "if", "self", ".", "_in_buffer", "(", "cursor", ".", "position", "(", ")", ")", ":", "text", "=", "event", ".", "mimeData", "(", ")", ".", "text", "(", ")", "self", ".", "_insert_plain_text_into_buffer", "(", "cursor", ",", "text", ")", "# Qt is expecting to get something here--drag and drop occurs in its", "# own event loop. Send a DragLeave event to end it.", "QtGui", ".", "qApp", ".", "sendEvent", "(", "obj", ",", "QtGui", ".", "QDragLeaveEvent", "(", ")", ")", "return", "True", "# Handle scrolling of the vsplit pager. This hack attempts to solve", "# problems with tearing of the help text inside the pager window. This", "# happens only on Mac OS X with both PySide and PyQt. This fix isn't", "# perfect but makes the pager more usable.", "elif", "etype", "in", "self", ".", "_pager_scroll_events", "and", "obj", "==", "self", ".", "_page_control", ":", "self", ".", "_page_control", ".", "repaint", "(", ")", "return", "True", "return", "super", "(", "ConsoleWidget", ",", "self", ")", ".", "eventFilter", "(", "obj", ",", "event", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget.sizeHint
Reimplemented to suggest a size that is 80 characters wide and 25 lines high.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def sizeHint(self): """ Reimplemented to suggest a size that is 80 characters wide and 25 lines high. """ font_metrics = QtGui.QFontMetrics(self.font) margin = (self._control.frameWidth() + self._control.document().documentMargin()) * 2 style = self.style() splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth) # Note 1: Despite my best efforts to take the various margins into # account, the width is still coming out a bit too small, so we include # a fudge factor of one character here. # Note 2: QFontMetrics.maxWidth is not used here or anywhere else due # to a Qt bug on certain Mac OS systems where it returns 0. width = font_metrics.width(' ') * 81 + margin width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent) if self.paging == 'hsplit': width = width * 2 + splitwidth height = font_metrics.height() * 25 + margin if self.paging == 'vsplit': height = height * 2 + splitwidth return QtCore.QSize(width, height)
def sizeHint(self): """ Reimplemented to suggest a size that is 80 characters wide and 25 lines high. """ font_metrics = QtGui.QFontMetrics(self.font) margin = (self._control.frameWidth() + self._control.document().documentMargin()) * 2 style = self.style() splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth) # Note 1: Despite my best efforts to take the various margins into # account, the width is still coming out a bit too small, so we include # a fudge factor of one character here. # Note 2: QFontMetrics.maxWidth is not used here or anywhere else due # to a Qt bug on certain Mac OS systems where it returns 0. width = font_metrics.width(' ') * 81 + margin width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent) if self.paging == 'hsplit': width = width * 2 + splitwidth height = font_metrics.height() * 25 + margin if self.paging == 'vsplit': height = height * 2 + splitwidth return QtCore.QSize(width, height)
[ "Reimplemented", "to", "suggest", "a", "size", "that", "is", "80", "characters", "wide", "and", "25", "lines", "high", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L441-L465
[ "def", "sizeHint", "(", "self", ")", ":", "font_metrics", "=", "QtGui", ".", "QFontMetrics", "(", "self", ".", "font", ")", "margin", "=", "(", "self", ".", "_control", ".", "frameWidth", "(", ")", "+", "self", ".", "_control", ".", "document", "(", ")", ".", "documentMargin", "(", ")", ")", "*", "2", "style", "=", "self", ".", "style", "(", ")", "splitwidth", "=", "style", ".", "pixelMetric", "(", "QtGui", ".", "QStyle", ".", "PM_SplitterWidth", ")", "# Note 1: Despite my best efforts to take the various margins into", "# account, the width is still coming out a bit too small, so we include", "# a fudge factor of one character here.", "# Note 2: QFontMetrics.maxWidth is not used here or anywhere else due", "# to a Qt bug on certain Mac OS systems where it returns 0.", "width", "=", "font_metrics", ".", "width", "(", "' '", ")", "*", "81", "+", "margin", "width", "+=", "style", ".", "pixelMetric", "(", "QtGui", ".", "QStyle", ".", "PM_ScrollBarExtent", ")", "if", "self", ".", "paging", "==", "'hsplit'", ":", "width", "=", "width", "*", "2", "+", "splitwidth", "height", "=", "font_metrics", ".", "height", "(", ")", "*", "25", "+", "margin", "if", "self", ".", "paging", "==", "'vsplit'", ":", "height", "=", "height", "*", "2", "+", "splitwidth", "return", "QtCore", ".", "QSize", "(", "width", ",", "height", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget.can_cut
Returns whether text can be cut to the clipboard.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def can_cut(self): """ Returns whether text can be cut to the clipboard. """ cursor = self._control.textCursor() return (cursor.hasSelection() and self._in_buffer(cursor.anchor()) and self._in_buffer(cursor.position()))
def can_cut(self): """ Returns whether text can be cut to the clipboard. """ cursor = self._control.textCursor() return (cursor.hasSelection() and self._in_buffer(cursor.anchor()) and self._in_buffer(cursor.position()))
[ "Returns", "whether", "text", "can", "be", "cut", "to", "the", "clipboard", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L476-L482
[ "def", "can_cut", "(", "self", ")", ":", "cursor", "=", "self", ".", "_control", ".", "textCursor", "(", ")", "return", "(", "cursor", ".", "hasSelection", "(", ")", "and", "self", ".", "_in_buffer", "(", "cursor", ".", "anchor", "(", ")", ")", "and", "self", ".", "_in_buffer", "(", "cursor", ".", "position", "(", ")", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget.can_paste
Returns whether text can be pasted from the clipboard.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def can_paste(self): """ Returns whether text can be pasted from the clipboard. """ if self._control.textInteractionFlags() & QtCore.Qt.TextEditable: return bool(QtGui.QApplication.clipboard().text()) return False
def can_paste(self): """ Returns whether text can be pasted from the clipboard. """ if self._control.textInteractionFlags() & QtCore.Qt.TextEditable: return bool(QtGui.QApplication.clipboard().text()) return False
[ "Returns", "whether", "text", "can", "be", "pasted", "from", "the", "clipboard", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L484-L489
[ "def", "can_paste", "(", "self", ")", ":", "if", "self", ".", "_control", ".", "textInteractionFlags", "(", ")", "&", "QtCore", ".", "Qt", ".", "TextEditable", ":", "return", "bool", "(", "QtGui", ".", "QApplication", ".", "clipboard", "(", ")", ".", "text", "(", ")", ")", "return", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget.clear
Clear the console. Parameters: ----------- keep_input : bool, optional (default True) If set, restores the old input buffer if a new prompt is written.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def clear(self, keep_input=True): """ Clear the console. Parameters: ----------- keep_input : bool, optional (default True) If set, restores the old input buffer if a new prompt is written. """ if self._executing: self._control.clear() else: if keep_input: input_buffer = self.input_buffer self._control.clear() self._show_prompt() if keep_input: self.input_buffer = input_buffer
def clear(self, keep_input=True): """ Clear the console. Parameters: ----------- keep_input : bool, optional (default True) If set, restores the old input buffer if a new prompt is written. """ if self._executing: self._control.clear() else: if keep_input: input_buffer = self.input_buffer self._control.clear() self._show_prompt() if keep_input: self.input_buffer = input_buffer
[ "Clear", "the", "console", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L491-L507
[ "def", "clear", "(", "self", ",", "keep_input", "=", "True", ")", ":", "if", "self", ".", "_executing", ":", "self", ".", "_control", ".", "clear", "(", ")", "else", ":", "if", "keep_input", ":", "input_buffer", "=", "self", ".", "input_buffer", "self", ".", "_control", ".", "clear", "(", ")", "self", ".", "_show_prompt", "(", ")", "if", "keep_input", ":", "self", ".", "input_buffer", "=", "input_buffer" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget.cut
Copy the currently selected text to the clipboard and delete it if it's inside the input buffer.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def cut(self): """ Copy the currently selected text to the clipboard and delete it if it's inside the input buffer. """ self.copy() if self.can_cut(): self._control.textCursor().removeSelectedText()
def cut(self): """ Copy the currently selected text to the clipboard and delete it if it's inside the input buffer. """ self.copy() if self.can_cut(): self._control.textCursor().removeSelectedText()
[ "Copy", "the", "currently", "selected", "text", "to", "the", "clipboard", "and", "delete", "it", "if", "it", "s", "inside", "the", "input", "buffer", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L514-L520
[ "def", "cut", "(", "self", ")", ":", "self", ".", "copy", "(", ")", "if", "self", ".", "can_cut", "(", ")", ":", "self", ".", "_control", ".", "textCursor", "(", ")", ".", "removeSelectedText", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget.execute
Executes source or the input buffer, possibly prompting for more input. Parameters: ----------- source : str, optional The source to execute. If not specified, the input buffer will be used. If specified and 'hidden' is False, the input buffer will be replaced with the source before execution. hidden : bool, optional (default False) If set, no output will be shown and the prompt will not be modified. In other words, it will be completely invisible to the user that an execution has occurred. interactive : bool, optional (default False) Whether the console is to treat the source as having been manually entered by the user. The effect of this parameter depends on the subclass implementation. Raises: ------- RuntimeError If incomplete input is given and 'hidden' is True. In this case, it is not possible to prompt for more input. Returns: -------- A boolean indicating whether the source was executed.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def execute(self, source=None, hidden=False, interactive=False): """ Executes source or the input buffer, possibly prompting for more input. Parameters: ----------- source : str, optional The source to execute. If not specified, the input buffer will be used. If specified and 'hidden' is False, the input buffer will be replaced with the source before execution. hidden : bool, optional (default False) If set, no output will be shown and the prompt will not be modified. In other words, it will be completely invisible to the user that an execution has occurred. interactive : bool, optional (default False) Whether the console is to treat the source as having been manually entered by the user. The effect of this parameter depends on the subclass implementation. Raises: ------- RuntimeError If incomplete input is given and 'hidden' is True. In this case, it is not possible to prompt for more input. Returns: -------- A boolean indicating whether the source was executed. """ # WARNING: The order in which things happen here is very particular, in # large part because our syntax highlighting is fragile. If you change # something, test carefully! # Decide what to execute. if source is None: source = self.input_buffer if not hidden: # A newline is appended later, but it should be considered part # of the input buffer. source += '\n' elif not hidden: self.input_buffer = source # Execute the source or show a continuation prompt if it is incomplete. complete = self._is_complete(source, interactive) if hidden: if complete: self._execute(source, hidden) else: error = 'Incomplete noninteractive input: "%s"' raise RuntimeError(error % source) else: if complete: self._append_plain_text('\n') self._input_buffer_executing = self.input_buffer self._executing = True self._prompt_finished() # The maximum block count is only in effect during execution. # This ensures that _prompt_pos does not become invalid due to # text truncation. self._control.document().setMaximumBlockCount(self.buffer_size) # Setting a positive maximum block count will automatically # disable the undo/redo history, but just to be safe: self._control.setUndoRedoEnabled(False) # Perform actual execution. self._execute(source, hidden) else: # Do this inside an edit block so continuation prompts are # removed seamlessly via undo/redo. cursor = self._get_end_cursor() cursor.beginEditBlock() cursor.insertText('\n') self._insert_continuation_prompt(cursor) cursor.endEditBlock() # Do not do this inside the edit block. It works as expected # when using a QPlainTextEdit control, but does not have an # effect when using a QTextEdit. I believe this is a Qt bug. self._control.moveCursor(QtGui.QTextCursor.End) return complete
def execute(self, source=None, hidden=False, interactive=False): """ Executes source or the input buffer, possibly prompting for more input. Parameters: ----------- source : str, optional The source to execute. If not specified, the input buffer will be used. If specified and 'hidden' is False, the input buffer will be replaced with the source before execution. hidden : bool, optional (default False) If set, no output will be shown and the prompt will not be modified. In other words, it will be completely invisible to the user that an execution has occurred. interactive : bool, optional (default False) Whether the console is to treat the source as having been manually entered by the user. The effect of this parameter depends on the subclass implementation. Raises: ------- RuntimeError If incomplete input is given and 'hidden' is True. In this case, it is not possible to prompt for more input. Returns: -------- A boolean indicating whether the source was executed. """ # WARNING: The order in which things happen here is very particular, in # large part because our syntax highlighting is fragile. If you change # something, test carefully! # Decide what to execute. if source is None: source = self.input_buffer if not hidden: # A newline is appended later, but it should be considered part # of the input buffer. source += '\n' elif not hidden: self.input_buffer = source # Execute the source or show a continuation prompt if it is incomplete. complete = self._is_complete(source, interactive) if hidden: if complete: self._execute(source, hidden) else: error = 'Incomplete noninteractive input: "%s"' raise RuntimeError(error % source) else: if complete: self._append_plain_text('\n') self._input_buffer_executing = self.input_buffer self._executing = True self._prompt_finished() # The maximum block count is only in effect during execution. # This ensures that _prompt_pos does not become invalid due to # text truncation. self._control.document().setMaximumBlockCount(self.buffer_size) # Setting a positive maximum block count will automatically # disable the undo/redo history, but just to be safe: self._control.setUndoRedoEnabled(False) # Perform actual execution. self._execute(source, hidden) else: # Do this inside an edit block so continuation prompts are # removed seamlessly via undo/redo. cursor = self._get_end_cursor() cursor.beginEditBlock() cursor.insertText('\n') self._insert_continuation_prompt(cursor) cursor.endEditBlock() # Do not do this inside the edit block. It works as expected # when using a QPlainTextEdit control, but does not have an # effect when using a QTextEdit. I believe this is a Qt bug. self._control.moveCursor(QtGui.QTextCursor.End) return complete
[ "Executes", "source", "or", "the", "input", "buffer", "possibly", "prompting", "for", "more", "input", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L522-L611
[ "def", "execute", "(", "self", ",", "source", "=", "None", ",", "hidden", "=", "False", ",", "interactive", "=", "False", ")", ":", "# WARNING: The order in which things happen here is very particular, in", "# large part because our syntax highlighting is fragile. If you change", "# something, test carefully!", "# Decide what to execute.", "if", "source", "is", "None", ":", "source", "=", "self", ".", "input_buffer", "if", "not", "hidden", ":", "# A newline is appended later, but it should be considered part", "# of the input buffer.", "source", "+=", "'\\n'", "elif", "not", "hidden", ":", "self", ".", "input_buffer", "=", "source", "# Execute the source or show a continuation prompt if it is incomplete.", "complete", "=", "self", ".", "_is_complete", "(", "source", ",", "interactive", ")", "if", "hidden", ":", "if", "complete", ":", "self", ".", "_execute", "(", "source", ",", "hidden", ")", "else", ":", "error", "=", "'Incomplete noninteractive input: \"%s\"'", "raise", "RuntimeError", "(", "error", "%", "source", ")", "else", ":", "if", "complete", ":", "self", ".", "_append_plain_text", "(", "'\\n'", ")", "self", ".", "_input_buffer_executing", "=", "self", ".", "input_buffer", "self", ".", "_executing", "=", "True", "self", ".", "_prompt_finished", "(", ")", "# The maximum block count is only in effect during execution.", "# This ensures that _prompt_pos does not become invalid due to", "# text truncation.", "self", ".", "_control", ".", "document", "(", ")", ".", "setMaximumBlockCount", "(", "self", ".", "buffer_size", ")", "# Setting a positive maximum block count will automatically", "# disable the undo/redo history, but just to be safe:", "self", ".", "_control", ".", "setUndoRedoEnabled", "(", "False", ")", "# Perform actual execution.", "self", ".", "_execute", "(", "source", ",", "hidden", ")", "else", ":", "# Do this inside an edit block so continuation prompts are", "# removed seamlessly via undo/redo.", "cursor", "=", "self", ".", "_get_end_cursor", "(", ")", "cursor", ".", "beginEditBlock", "(", ")", "cursor", ".", "insertText", "(", "'\\n'", ")", "self", ".", "_insert_continuation_prompt", "(", "cursor", ")", "cursor", ".", "endEditBlock", "(", ")", "# Do not do this inside the edit block. It works as expected", "# when using a QPlainTextEdit control, but does not have an", "# effect when using a QTextEdit. I believe this is a Qt bug.", "self", ".", "_control", ".", "moveCursor", "(", "QtGui", ".", "QTextCursor", ".", "End", ")", "return", "complete" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget._get_input_buffer
The text that the user has entered entered at the current prompt. If the console is currently executing, the text that is executing will always be returned.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def _get_input_buffer(self, force=False): """ The text that the user has entered entered at the current prompt. If the console is currently executing, the text that is executing will always be returned. """ # If we're executing, the input buffer may not even exist anymore due to # the limit imposed by 'buffer_size'. Therefore, we store it. if self._executing and not force: return self._input_buffer_executing cursor = self._get_end_cursor() cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor) input_buffer = cursor.selection().toPlainText() # Strip out continuation prompts. return input_buffer.replace('\n' + self._continuation_prompt, '\n')
def _get_input_buffer(self, force=False): """ The text that the user has entered entered at the current prompt. If the console is currently executing, the text that is executing will always be returned. """ # If we're executing, the input buffer may not even exist anymore due to # the limit imposed by 'buffer_size'. Therefore, we store it. if self._executing and not force: return self._input_buffer_executing cursor = self._get_end_cursor() cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor) input_buffer = cursor.selection().toPlainText() # Strip out continuation prompts. return input_buffer.replace('\n' + self._continuation_prompt, '\n')
[ "The", "text", "that", "the", "user", "has", "entered", "entered", "at", "the", "current", "prompt", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L618-L634
[ "def", "_get_input_buffer", "(", "self", ",", "force", "=", "False", ")", ":", "# If we're executing, the input buffer may not even exist anymore due to", "# the limit imposed by 'buffer_size'. Therefore, we store it.", "if", "self", ".", "_executing", "and", "not", "force", ":", "return", "self", ".", "_input_buffer_executing", "cursor", "=", "self", ".", "_get_end_cursor", "(", ")", "cursor", ".", "setPosition", "(", "self", ".", "_prompt_pos", ",", "QtGui", ".", "QTextCursor", ".", "KeepAnchor", ")", "input_buffer", "=", "cursor", ".", "selection", "(", ")", ".", "toPlainText", "(", ")", "# Strip out continuation prompts.", "return", "input_buffer", ".", "replace", "(", "'\\n'", "+", "self", ".", "_continuation_prompt", ",", "'\\n'", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget._set_input_buffer
Sets the text in the input buffer. If the console is currently executing, this call has no *immediate* effect. When the execution is finished, the input buffer will be updated appropriately.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def _set_input_buffer(self, string): """ Sets the text in the input buffer. If the console is currently executing, this call has no *immediate* effect. When the execution is finished, the input buffer will be updated appropriately. """ # If we're executing, store the text for later. if self._executing: self._input_buffer_pending = string return # Remove old text. cursor = self._get_end_cursor() cursor.beginEditBlock() cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor) cursor.removeSelectedText() # Insert new text with continuation prompts. self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string) cursor.endEditBlock() self._control.moveCursor(QtGui.QTextCursor.End)
def _set_input_buffer(self, string): """ Sets the text in the input buffer. If the console is currently executing, this call has no *immediate* effect. When the execution is finished, the input buffer will be updated appropriately. """ # If we're executing, store the text for later. if self._executing: self._input_buffer_pending = string return # Remove old text. cursor = self._get_end_cursor() cursor.beginEditBlock() cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor) cursor.removeSelectedText() # Insert new text with continuation prompts. self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string) cursor.endEditBlock() self._control.moveCursor(QtGui.QTextCursor.End)
[ "Sets", "the", "text", "in", "the", "input", "buffer", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L636-L657
[ "def", "_set_input_buffer", "(", "self", ",", "string", ")", ":", "# If we're executing, store the text for later.", "if", "self", ".", "_executing", ":", "self", ".", "_input_buffer_pending", "=", "string", "return", "# Remove old text.", "cursor", "=", "self", ".", "_get_end_cursor", "(", ")", "cursor", ".", "beginEditBlock", "(", ")", "cursor", ".", "setPosition", "(", "self", ".", "_prompt_pos", ",", "QtGui", ".", "QTextCursor", ".", "KeepAnchor", ")", "cursor", ".", "removeSelectedText", "(", ")", "# Insert new text with continuation prompts.", "self", ".", "_insert_plain_text_into_buffer", "(", "self", ".", "_get_prompt_cursor", "(", ")", ",", "string", ")", "cursor", ".", "endEditBlock", "(", ")", "self", ".", "_control", ".", "moveCursor", "(", "QtGui", ".", "QTextCursor", ".", "End", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget._set_font
Sets the base font for the ConsoleWidget to the specified QFont.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def _set_font(self, font): """ Sets the base font for the ConsoleWidget to the specified QFont. """ font_metrics = QtGui.QFontMetrics(font) self._control.setTabStopWidth(self.tab_width * font_metrics.width(' ')) self._completion_widget.setFont(font) self._control.document().setDefaultFont(font) if self._page_control: self._page_control.document().setDefaultFont(font) self.font_changed.emit(font)
def _set_font(self, font): """ Sets the base font for the ConsoleWidget to the specified QFont. """ font_metrics = QtGui.QFontMetrics(font) self._control.setTabStopWidth(self.tab_width * font_metrics.width(' ')) self._completion_widget.setFont(font) self._control.document().setDefaultFont(font) if self._page_control: self._page_control.document().setDefaultFont(font) self.font_changed.emit(font)
[ "Sets", "the", "base", "font", "for", "the", "ConsoleWidget", "to", "the", "specified", "QFont", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L666-L677
[ "def", "_set_font", "(", "self", ",", "font", ")", ":", "font_metrics", "=", "QtGui", ".", "QFontMetrics", "(", "font", ")", "self", ".", "_control", ".", "setTabStopWidth", "(", "self", ".", "tab_width", "*", "font_metrics", ".", "width", "(", "' '", ")", ")", "self", ".", "_completion_widget", ".", "setFont", "(", "font", ")", "self", ".", "_control", ".", "document", "(", ")", ".", "setDefaultFont", "(", "font", ")", "if", "self", ".", "_page_control", ":", "self", ".", "_page_control", ".", "document", "(", ")", ".", "setDefaultFont", "(", "font", ")", "self", ".", "font_changed", ".", "emit", "(", "font", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget.paste
Paste the contents of the clipboard into the input region. Parameters: ----------- mode : QClipboard::Mode, optional [default QClipboard::Clipboard] Controls which part of the system clipboard is used. This can be used to access the selection clipboard in X11 and the Find buffer in Mac OS. By default, the regular clipboard is used.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def paste(self, mode=QtGui.QClipboard.Clipboard): """ Paste the contents of the clipboard into the input region. Parameters: ----------- mode : QClipboard::Mode, optional [default QClipboard::Clipboard] Controls which part of the system clipboard is used. This can be used to access the selection clipboard in X11 and the Find buffer in Mac OS. By default, the regular clipboard is used. """ if self._control.textInteractionFlags() & QtCore.Qt.TextEditable: # Make sure the paste is safe. self._keep_cursor_in_buffer() cursor = self._control.textCursor() # Remove any trailing newline, which confuses the GUI and forces the # user to backspace. text = QtGui.QApplication.clipboard().text(mode).rstrip() self._insert_plain_text_into_buffer(cursor, dedent(text))
def paste(self, mode=QtGui.QClipboard.Clipboard): """ Paste the contents of the clipboard into the input region. Parameters: ----------- mode : QClipboard::Mode, optional [default QClipboard::Clipboard] Controls which part of the system clipboard is used. This can be used to access the selection clipboard in X11 and the Find buffer in Mac OS. By default, the regular clipboard is used. """ if self._control.textInteractionFlags() & QtCore.Qt.TextEditable: # Make sure the paste is safe. self._keep_cursor_in_buffer() cursor = self._control.textCursor() # Remove any trailing newline, which confuses the GUI and forces the # user to backspace. text = QtGui.QApplication.clipboard().text(mode).rstrip() self._insert_plain_text_into_buffer(cursor, dedent(text))
[ "Paste", "the", "contents", "of", "the", "clipboard", "into", "the", "input", "region", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L681-L700
[ "def", "paste", "(", "self", ",", "mode", "=", "QtGui", ".", "QClipboard", ".", "Clipboard", ")", ":", "if", "self", ".", "_control", ".", "textInteractionFlags", "(", ")", "&", "QtCore", ".", "Qt", ".", "TextEditable", ":", "# Make sure the paste is safe.", "self", ".", "_keep_cursor_in_buffer", "(", ")", "cursor", "=", "self", ".", "_control", ".", "textCursor", "(", ")", "# Remove any trailing newline, which confuses the GUI and forces the", "# user to backspace.", "text", "=", "QtGui", ".", "QApplication", ".", "clipboard", "(", ")", ".", "text", "(", "mode", ")", ".", "rstrip", "(", ")", "self", ".", "_insert_plain_text_into_buffer", "(", "cursor", ",", "dedent", "(", "text", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget.print_
Print the contents of the ConsoleWidget to the specified QPrinter.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def print_(self, printer = None): """ Print the contents of the ConsoleWidget to the specified QPrinter. """ if (not printer): printer = QtGui.QPrinter() if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted): return self._control.print_(printer)
def print_(self, printer = None): """ Print the contents of the ConsoleWidget to the specified QPrinter. """ if (not printer): printer = QtGui.QPrinter() if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted): return self._control.print_(printer)
[ "Print", "the", "contents", "of", "the", "ConsoleWidget", "to", "the", "specified", "QPrinter", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L702-L709
[ "def", "print_", "(", "self", ",", "printer", "=", "None", ")", ":", "if", "(", "not", "printer", ")", ":", "printer", "=", "QtGui", ".", "QPrinter", "(", ")", "if", "(", "QtGui", ".", "QPrintDialog", "(", "printer", ")", ".", "exec_", "(", ")", "!=", "QtGui", ".", "QDialog", ".", "Accepted", ")", ":", "return", "self", ".", "_control", ".", "print_", "(", "printer", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget.prompt_to_top
Moves the prompt to the top of the viewport.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def prompt_to_top(self): """ Moves the prompt to the top of the viewport. """ if not self._executing: prompt_cursor = self._get_prompt_cursor() if self._get_cursor().blockNumber() < prompt_cursor.blockNumber(): self._set_cursor(prompt_cursor) self._set_top_cursor(prompt_cursor)
def prompt_to_top(self): """ Moves the prompt to the top of the viewport. """ if not self._executing: prompt_cursor = self._get_prompt_cursor() if self._get_cursor().blockNumber() < prompt_cursor.blockNumber(): self._set_cursor(prompt_cursor) self._set_top_cursor(prompt_cursor)
[ "Moves", "the", "prompt", "to", "the", "top", "of", "the", "viewport", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L711-L718
[ "def", "prompt_to_top", "(", "self", ")", ":", "if", "not", "self", ".", "_executing", ":", "prompt_cursor", "=", "self", ".", "_get_prompt_cursor", "(", ")", "if", "self", ".", "_get_cursor", "(", ")", ".", "blockNumber", "(", ")", "<", "prompt_cursor", ".", "blockNumber", "(", ")", ":", "self", ".", "_set_cursor", "(", "prompt_cursor", ")", "self", ".", "_set_top_cursor", "(", "prompt_cursor", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget.reset_font
Sets the font to the default fixed-width font for this platform.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def reset_font(self): """ Sets the font to the default fixed-width font for this platform. """ if sys.platform == 'win32': # Consolas ships with Vista/Win7, fallback to Courier if needed fallback = 'Courier' elif sys.platform == 'darwin': # OSX always has Monaco fallback = 'Monaco' else: # Monospace should always exist fallback = 'Monospace' font = get_font(self.font_family, fallback) if self.font_size: font.setPointSize(self.font_size) else: font.setPointSize(QtGui.qApp.font().pointSize()) font.setStyleHint(QtGui.QFont.TypeWriter) self._set_font(font)
def reset_font(self): """ Sets the font to the default fixed-width font for this platform. """ if sys.platform == 'win32': # Consolas ships with Vista/Win7, fallback to Courier if needed fallback = 'Courier' elif sys.platform == 'darwin': # OSX always has Monaco fallback = 'Monaco' else: # Monospace should always exist fallback = 'Monospace' font = get_font(self.font_family, fallback) if self.font_size: font.setPointSize(self.font_size) else: font.setPointSize(QtGui.qApp.font().pointSize()) font.setStyleHint(QtGui.QFont.TypeWriter) self._set_font(font)
[ "Sets", "the", "font", "to", "the", "default", "fixed", "-", "width", "font", "for", "this", "platform", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L726-L744
[ "def", "reset_font", "(", "self", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "# Consolas ships with Vista/Win7, fallback to Courier if needed", "fallback", "=", "'Courier'", "elif", "sys", ".", "platform", "==", "'darwin'", ":", "# OSX always has Monaco", "fallback", "=", "'Monaco'", "else", ":", "# Monospace should always exist", "fallback", "=", "'Monospace'", "font", "=", "get_font", "(", "self", ".", "font_family", ",", "fallback", ")", "if", "self", ".", "font_size", ":", "font", ".", "setPointSize", "(", "self", ".", "font_size", ")", "else", ":", "font", ".", "setPointSize", "(", "QtGui", ".", "qApp", ".", "font", "(", ")", ".", "pointSize", "(", ")", ")", "font", ".", "setStyleHint", "(", "QtGui", ".", "QFont", ".", "TypeWriter", ")", "self", ".", "_set_font", "(", "font", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ConsoleWidget.change_font_size
Change the font size by the specified amount (in points).
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py
def change_font_size(self, delta): """Change the font size by the specified amount (in points). """ font = self.font size = max(font.pointSize() + delta, 1) # minimum 1 point font.setPointSize(size) self._set_font(font)
def change_font_size(self, delta): """Change the font size by the specified amount (in points). """ font = self.font size = max(font.pointSize() + delta, 1) # minimum 1 point font.setPointSize(size) self._set_font(font)
[ "Change", "the", "font", "size", "by", "the", "specified", "amount", "(", "in", "points", ")", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L746-L752
[ "def", "change_font_size", "(", "self", ",", "delta", ")", ":", "font", "=", "self", ".", "font", "size", "=", "max", "(", "font", ".", "pointSize", "(", ")", "+", "delta", ",", "1", ")", "# minimum 1 point", "font", ".", "setPointSize", "(", "size", ")", "self", ".", "_set_font", "(", "font", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e