id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
225,800 | autokey/autokey | lib/autokey/qtui/dialogs/hotkeysettings.py | HotkeySettingsDialog.set_key | def set_key(self, key, modifiers: typing.List[Key]=None):
"""This is called when the user successfully finishes recording a key combination."""
if modifiers is None:
modifiers = [] # type: typing.List[Key]
if key in self.KEY_MAP:
key = self.KEY_MAP[key]
self._setKeyLabel(key)
self.key = key
self.controlButton.setChecked(Key.CONTROL in modifiers)
self.altButton.setChecked(Key.ALT in modifiers)
self.shiftButton.setChecked(Key.SHIFT in modifiers)
self.superButton.setChecked(Key.SUPER in modifiers)
self.hyperButton.setChecked(Key.HYPER in modifiers)
self.metaButton.setChecked(Key.META in modifiers)
self.recording_finished.emit(True) | python | def set_key(self, key, modifiers: typing.List[Key]=None):
"""This is called when the user successfully finishes recording a key combination."""
if modifiers is None:
modifiers = [] # type: typing.List[Key]
if key in self.KEY_MAP:
key = self.KEY_MAP[key]
self._setKeyLabel(key)
self.key = key
self.controlButton.setChecked(Key.CONTROL in modifiers)
self.altButton.setChecked(Key.ALT in modifiers)
self.shiftButton.setChecked(Key.SHIFT in modifiers)
self.superButton.setChecked(Key.SUPER in modifiers)
self.hyperButton.setChecked(Key.HYPER in modifiers)
self.metaButton.setChecked(Key.META in modifiers)
self.recording_finished.emit(True) | [
"def",
"set_key",
"(",
"self",
",",
"key",
",",
"modifiers",
":",
"typing",
".",
"List",
"[",
"Key",
"]",
"=",
"None",
")",
":",
"if",
"modifiers",
"is",
"None",
":",
"modifiers",
"=",
"[",
"]",
"# type: typing.List[Key]",
"if",
"key",
"in",
"self",
... | This is called when the user successfully finishes recording a key combination. | [
"This",
"is",
"called",
"when",
"the",
"user",
"successfully",
"finishes",
"recording",
"a",
"key",
"combination",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/dialogs/hotkeysettings.py#L127-L141 |
225,801 | autokey/autokey | lib/autokey/qtui/dialogs/hotkeysettings.py | HotkeySettingsDialog.cancel_grab | def cancel_grab(self):
"""
This is called when the user cancels a recording.
Canceling is done by clicking with the left mouse button.
"""
logger.debug("User canceled hotkey recording.")
self.recording_finished.emit(True)
self._setKeyLabel(self.key if self.key is not None else "(None)") | python | def cancel_grab(self):
"""
This is called when the user cancels a recording.
Canceling is done by clicking with the left mouse button.
"""
logger.debug("User canceled hotkey recording.")
self.recording_finished.emit(True)
self._setKeyLabel(self.key if self.key is not None else "(None)") | [
"def",
"cancel_grab",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"User canceled hotkey recording.\"",
")",
"self",
".",
"recording_finished",
".",
"emit",
"(",
"True",
")",
"self",
".",
"_setKeyLabel",
"(",
"self",
".",
"key",
"if",
"self",
".",
... | This is called when the user cancels a recording.
Canceling is done by clicking with the left mouse button. | [
"This",
"is",
"called",
"when",
"the",
"user",
"cancels",
"a",
"recording",
".",
"Canceling",
"is",
"done",
"by",
"clicking",
"with",
"the",
"left",
"mouse",
"button",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/dialogs/hotkeysettings.py#L143-L150 |
225,802 | autokey/autokey | lib/autokey/iomediator/_iomediator.py | IoMediator.handle_modifier_down | def handle_modifier_down(self, modifier):
"""
Updates the state of the given modifier key to 'pressed'
"""
_logger.debug("%s pressed", modifier)
if modifier in (Key.CAPSLOCK, Key.NUMLOCK):
if self.modifiers[modifier]:
self.modifiers[modifier] = False
else:
self.modifiers[modifier] = True
else:
self.modifiers[modifier] = True | python | def handle_modifier_down(self, modifier):
"""
Updates the state of the given modifier key to 'pressed'
"""
_logger.debug("%s pressed", modifier)
if modifier in (Key.CAPSLOCK, Key.NUMLOCK):
if self.modifiers[modifier]:
self.modifiers[modifier] = False
else:
self.modifiers[modifier] = True
else:
self.modifiers[modifier] = True | [
"def",
"handle_modifier_down",
"(",
"self",
",",
"modifier",
")",
":",
"_logger",
".",
"debug",
"(",
"\"%s pressed\"",
",",
"modifier",
")",
"if",
"modifier",
"in",
"(",
"Key",
".",
"CAPSLOCK",
",",
"Key",
".",
"NUMLOCK",
")",
":",
"if",
"self",
".",
"... | Updates the state of the given modifier key to 'pressed' | [
"Updates",
"the",
"state",
"of",
"the",
"given",
"modifier",
"key",
"to",
"pressed"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/iomediator/_iomediator.py#L72-L83 |
225,803 | autokey/autokey | lib/autokey/iomediator/_iomediator.py | IoMediator.handle_modifier_up | def handle_modifier_up(self, modifier):
"""
Updates the state of the given modifier key to 'released'.
"""
_logger.debug("%s released", modifier)
# Caps and num lock are handled on key down only
if modifier not in (Key.CAPSLOCK, Key.NUMLOCK):
self.modifiers[modifier] = False | python | def handle_modifier_up(self, modifier):
"""
Updates the state of the given modifier key to 'released'.
"""
_logger.debug("%s released", modifier)
# Caps and num lock are handled on key down only
if modifier not in (Key.CAPSLOCK, Key.NUMLOCK):
self.modifiers[modifier] = False | [
"def",
"handle_modifier_up",
"(",
"self",
",",
"modifier",
")",
":",
"_logger",
".",
"debug",
"(",
"\"%s released\"",
",",
"modifier",
")",
"# Caps and num lock are handled on key down only",
"if",
"modifier",
"not",
"in",
"(",
"Key",
".",
"CAPSLOCK",
",",
"Key",
... | Updates the state of the given modifier key to 'released'. | [
"Updates",
"the",
"state",
"of",
"the",
"given",
"modifier",
"key",
"to",
"released",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/iomediator/_iomediator.py#L85-L92 |
225,804 | autokey/autokey | lib/autokey/iomediator/_iomediator.py | IoMediator.send_string | def send_string(self, string: str):
"""
Sends the given string for output.
"""
if not string:
return
string = string.replace('\n', "<enter>")
string = string.replace('\t', "<tab>")
_logger.debug("Send via event interface")
self.__clearModifiers()
modifiers = []
for section in KEY_SPLIT_RE.split(string):
if len(section) > 0:
if Key.is_key(section[:-1]) and section[-1] == '+' and section[:-1] in MODIFIERS:
# Section is a modifier application (modifier followed by '+')
modifiers.append(section[:-1])
else:
if len(modifiers) > 0:
# Modifiers ready for application - send modified key
if Key.is_key(section):
self.interface.send_modified_key(section, modifiers)
modifiers = []
else:
self.interface.send_modified_key(section[0], modifiers)
if len(section) > 1:
self.interface.send_string(section[1:])
modifiers = []
else:
# Normal string/key operation
if Key.is_key(section):
self.interface.send_key(section)
else:
self.interface.send_string(section)
self.__reapplyModifiers() | python | def send_string(self, string: str):
"""
Sends the given string for output.
"""
if not string:
return
string = string.replace('\n', "<enter>")
string = string.replace('\t', "<tab>")
_logger.debug("Send via event interface")
self.__clearModifiers()
modifiers = []
for section in KEY_SPLIT_RE.split(string):
if len(section) > 0:
if Key.is_key(section[:-1]) and section[-1] == '+' and section[:-1] in MODIFIERS:
# Section is a modifier application (modifier followed by '+')
modifiers.append(section[:-1])
else:
if len(modifiers) > 0:
# Modifiers ready for application - send modified key
if Key.is_key(section):
self.interface.send_modified_key(section, modifiers)
modifiers = []
else:
self.interface.send_modified_key(section[0], modifiers)
if len(section) > 1:
self.interface.send_string(section[1:])
modifiers = []
else:
# Normal string/key operation
if Key.is_key(section):
self.interface.send_key(section)
else:
self.interface.send_string(section)
self.__reapplyModifiers() | [
"def",
"send_string",
"(",
"self",
",",
"string",
":",
"str",
")",
":",
"if",
"not",
"string",
":",
"return",
"string",
"=",
"string",
".",
"replace",
"(",
"'\\n'",
",",
"\"<enter>\"",
")",
"string",
"=",
"string",
".",
"replace",
"(",
"'\\t'",
",",
... | Sends the given string for output. | [
"Sends",
"the",
"given",
"string",
"for",
"output",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/iomediator/_iomediator.py#L124-L161 |
225,805 | autokey/autokey | lib/autokey/iomediator/_iomediator.py | IoMediator.send_left | def send_left(self, count):
"""
Sends the given number of left key presses.
"""
for i in range(count):
self.interface.send_key(Key.LEFT) | python | def send_left(self, count):
"""
Sends the given number of left key presses.
"""
for i in range(count):
self.interface.send_key(Key.LEFT) | [
"def",
"send_left",
"(",
"self",
",",
"count",
")",
":",
"for",
"i",
"in",
"range",
"(",
"count",
")",
":",
"self",
".",
"interface",
".",
"send_key",
"(",
"Key",
".",
"LEFT",
")"
] | Sends the given number of left key presses. | [
"Sends",
"the",
"given",
"number",
"of",
"left",
"key",
"presses",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/iomediator/_iomediator.py#L200-L205 |
225,806 | autokey/autokey | lib/autokey/iomediator/_iomediator.py | IoMediator.send_up | def send_up(self, count):
"""
Sends the given number of up key presses.
"""
for i in range(count):
self.interface.send_key(Key.UP) | python | def send_up(self, count):
"""
Sends the given number of up key presses.
"""
for i in range(count):
self.interface.send_key(Key.UP) | [
"def",
"send_up",
"(",
"self",
",",
"count",
")",
":",
"for",
"i",
"in",
"range",
"(",
"count",
")",
":",
"self",
".",
"interface",
".",
"send_key",
"(",
"Key",
".",
"UP",
")"
] | Sends the given number of up key presses. | [
"Sends",
"the",
"given",
"number",
"of",
"up",
"key",
"presses",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/iomediator/_iomediator.py#L211-L216 |
225,807 | autokey/autokey | lib/autokey/iomediator/_iomediator.py | IoMediator.send_backspace | def send_backspace(self, count):
"""
Sends the given number of backspace key presses.
"""
for i in range(count):
self.interface.send_key(Key.BACKSPACE) | python | def send_backspace(self, count):
"""
Sends the given number of backspace key presses.
"""
for i in range(count):
self.interface.send_key(Key.BACKSPACE) | [
"def",
"send_backspace",
"(",
"self",
",",
"count",
")",
":",
"for",
"i",
"in",
"range",
"(",
"count",
")",
":",
"self",
".",
"interface",
".",
"send_key",
"(",
"Key",
".",
"BACKSPACE",
")"
] | Sends the given number of backspace key presses. | [
"Sends",
"the",
"given",
"number",
"of",
"backspace",
"key",
"presses",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/iomediator/_iomediator.py#L218-L223 |
225,808 | autokey/autokey | lib/autokey/scripting.py | Keyboard.fake_keypress | def fake_keypress(self, key, repeat=1):
"""
Fake a keypress
Usage: C{keyboard.fake_keypress(key, repeat=1)}
Uses XTest to 'fake' a keypress. This is useful to send keypresses to some
applications which won't respond to keyboard.send_key()
@param key: they key to be sent (e.g. "s" or "<enter>")
@param repeat: number of times to repeat the key event
"""
for _ in range(repeat):
self.mediator.fake_keypress(key) | python | def fake_keypress(self, key, repeat=1):
"""
Fake a keypress
Usage: C{keyboard.fake_keypress(key, repeat=1)}
Uses XTest to 'fake' a keypress. This is useful to send keypresses to some
applications which won't respond to keyboard.send_key()
@param key: they key to be sent (e.g. "s" or "<enter>")
@param repeat: number of times to repeat the key event
"""
for _ in range(repeat):
self.mediator.fake_keypress(key) | [
"def",
"fake_keypress",
"(",
"self",
",",
"key",
",",
"repeat",
"=",
"1",
")",
":",
"for",
"_",
"in",
"range",
"(",
"repeat",
")",
":",
"self",
".",
"mediator",
".",
"fake_keypress",
"(",
"key",
")"
] | Fake a keypress
Usage: C{keyboard.fake_keypress(key, repeat=1)}
Uses XTest to 'fake' a keypress. This is useful to send keypresses to some
applications which won't respond to keyboard.send_key()
@param key: they key to be sent (e.g. "s" or "<enter>")
@param repeat: number of times to repeat the key event | [
"Fake",
"a",
"keypress"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L148-L161 |
225,809 | autokey/autokey | lib/autokey/scripting.py | QtDialog.info_dialog | def info_dialog(self, title="Information", message="", **kwargs):
"""
Show an information dialog
Usage: C{dialog.info_dialog(title="Information", message="", **kwargs)}
@param title: window title for the dialog
@param message: message displayed in the dialog
@return: a tuple containing the exit code and user input
@rtype: C{DialogData(int, str)}
"""
return self._run_kdialog(title, ["--msgbox", message], kwargs) | python | def info_dialog(self, title="Information", message="", **kwargs):
"""
Show an information dialog
Usage: C{dialog.info_dialog(title="Information", message="", **kwargs)}
@param title: window title for the dialog
@param message: message displayed in the dialog
@return: a tuple containing the exit code and user input
@rtype: C{DialogData(int, str)}
"""
return self._run_kdialog(title, ["--msgbox", message], kwargs) | [
"def",
"info_dialog",
"(",
"self",
",",
"title",
"=",
"\"Information\"",
",",
"message",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_run_kdialog",
"(",
"title",
",",
"[",
"\"--msgbox\"",
",",
"message",
"]",
",",
"kwargs",
... | Show an information dialog
Usage: C{dialog.info_dialog(title="Information", message="", **kwargs)}
@param title: window title for the dialog
@param message: message displayed in the dialog
@return: a tuple containing the exit code and user input
@rtype: C{DialogData(int, str)} | [
"Show",
"an",
"information",
"dialog"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L265-L276 |
225,810 | autokey/autokey | lib/autokey/scripting.py | QtDialog.calendar | def calendar(self, title="Choose a date", format_str="%Y-%m-%d", date="today", **kwargs):
"""
Show a calendar dialog
Usage: C{dialog.calendar_dialog(title="Choose a date", format="%Y-%m-%d", date="YYYY-MM-DD", **kwargs)}
Note: the format and date parameters are not currently used
@param title: window title for the dialog
@param format_str: format of date to be returned
@param date: initial date as YYYY-MM-DD, otherwise today
@return: a tuple containing the exit code and date
@rtype: C{DialogData(int, str)}
"""
return self._run_kdialog(title, ["--calendar", title], kwargs) | python | def calendar(self, title="Choose a date", format_str="%Y-%m-%d", date="today", **kwargs):
"""
Show a calendar dialog
Usage: C{dialog.calendar_dialog(title="Choose a date", format="%Y-%m-%d", date="YYYY-MM-DD", **kwargs)}
Note: the format and date parameters are not currently used
@param title: window title for the dialog
@param format_str: format of date to be returned
@param date: initial date as YYYY-MM-DD, otherwise today
@return: a tuple containing the exit code and date
@rtype: C{DialogData(int, str)}
"""
return self._run_kdialog(title, ["--calendar", title], kwargs) | [
"def",
"calendar",
"(",
"self",
",",
"title",
"=",
"\"Choose a date\"",
",",
"format_str",
"=",
"\"%Y-%m-%d\"",
",",
"date",
"=",
"\"today\"",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_run_kdialog",
"(",
"title",
",",
"[",
"\"--calendar\"... | Show a calendar dialog
Usage: C{dialog.calendar_dialog(title="Choose a date", format="%Y-%m-%d", date="YYYY-MM-DD", **kwargs)}
Note: the format and date parameters are not currently used
@param title: window title for the dialog
@param format_str: format of date to be returned
@param date: initial date as YYYY-MM-DD, otherwise today
@return: a tuple containing the exit code and date
@rtype: C{DialogData(int, str)} | [
"Show",
"a",
"calendar",
"dialog"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L453-L467 |
225,811 | autokey/autokey | lib/autokey/scripting.py | Window.activate | def activate(self, title, switchDesktop=False, matchClass=False):
"""
Activate the specified window, giving it input focus
Usage: C{window.activate(title, switchDesktop=False, matchClass=False)}
If switchDesktop is False (default), the window will be moved to the current desktop
and activated. Otherwise, switch to the window's current desktop and activate it there.
@param title: window title to match against (as case-insensitive substring match)
@param switchDesktop: whether or not to switch to the window's current desktop
@param matchClass: if True, match on the window class instead of the title
"""
if switchDesktop:
args = ["-a", title]
else:
args = ["-R", title]
if matchClass:
args += ["-x"]
self._run_wmctrl(args) | python | def activate(self, title, switchDesktop=False, matchClass=False):
"""
Activate the specified window, giving it input focus
Usage: C{window.activate(title, switchDesktop=False, matchClass=False)}
If switchDesktop is False (default), the window will be moved to the current desktop
and activated. Otherwise, switch to the window's current desktop and activate it there.
@param title: window title to match against (as case-insensitive substring match)
@param switchDesktop: whether or not to switch to the window's current desktop
@param matchClass: if True, match on the window class instead of the title
"""
if switchDesktop:
args = ["-a", title]
else:
args = ["-R", title]
if matchClass:
args += ["-x"]
self._run_wmctrl(args) | [
"def",
"activate",
"(",
"self",
",",
"title",
",",
"switchDesktop",
"=",
"False",
",",
"matchClass",
"=",
"False",
")",
":",
"if",
"switchDesktop",
":",
"args",
"=",
"[",
"\"-a\"",
",",
"title",
"]",
"else",
":",
"args",
"=",
"[",
"\"-R\"",
",",
"tit... | Activate the specified window, giving it input focus
Usage: C{window.activate(title, switchDesktop=False, matchClass=False)}
If switchDesktop is False (default), the window will be moved to the current desktop
and activated. Otherwise, switch to the window's current desktop and activate it there.
@param title: window title to match against (as case-insensitive substring match)
@param switchDesktop: whether or not to switch to the window's current desktop
@param matchClass: if True, match on the window class instead of the title | [
"Activate",
"the",
"specified",
"window",
"giving",
"it",
"input",
"focus"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L963-L982 |
225,812 | autokey/autokey | lib/autokey/scripting.py | Window.set_property | def set_property(self, title, action, prop, matchClass=False):
"""
Set a property on the given window using the specified action
Usage: C{window.set_property(title, action, prop, matchClass=False)}
Allowable actions: C{add, remove, toggle}
Allowable properties: C{modal, sticky, maximized_vert, maximized_horz, shaded, skip_taskbar,
skip_pager, hidden, fullscreen, above}
@param title: window title to match against (as case-insensitive substring match)
@param action: one of the actions listed above
@param prop: one of the properties listed above
@param matchClass: if True, match on the window class instead of the title
"""
if matchClass:
xArgs = ["-x"]
else:
xArgs = []
self._run_wmctrl(["-r", title, "-b" + action + ',' + prop] + xArgs) | python | def set_property(self, title, action, prop, matchClass=False):
"""
Set a property on the given window using the specified action
Usage: C{window.set_property(title, action, prop, matchClass=False)}
Allowable actions: C{add, remove, toggle}
Allowable properties: C{modal, sticky, maximized_vert, maximized_horz, shaded, skip_taskbar,
skip_pager, hidden, fullscreen, above}
@param title: window title to match against (as case-insensitive substring match)
@param action: one of the actions listed above
@param prop: one of the properties listed above
@param matchClass: if True, match on the window class instead of the title
"""
if matchClass:
xArgs = ["-x"]
else:
xArgs = []
self._run_wmctrl(["-r", title, "-b" + action + ',' + prop] + xArgs) | [
"def",
"set_property",
"(",
"self",
",",
"title",
",",
"action",
",",
"prop",
",",
"matchClass",
"=",
"False",
")",
":",
"if",
"matchClass",
":",
"xArgs",
"=",
"[",
"\"-x\"",
"]",
"else",
":",
"xArgs",
"=",
"[",
"]",
"self",
".",
"_run_wmctrl",
"(",
... | Set a property on the given window using the specified action
Usage: C{window.set_property(title, action, prop, matchClass=False)}
Allowable actions: C{add, remove, toggle}
Allowable properties: C{modal, sticky, maximized_vert, maximized_horz, shaded, skip_taskbar,
skip_pager, hidden, fullscreen, above}
@param title: window title to match against (as case-insensitive substring match)
@param action: one of the actions listed above
@param prop: one of the properties listed above
@param matchClass: if True, match on the window class instead of the title | [
"Set",
"a",
"property",
"on",
"the",
"given",
"window",
"using",
"the",
"specified",
"action"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L1047-L1066 |
225,813 | autokey/autokey | lib/autokey/scripting.py | Engine.run_script_from_macro | def run_script_from_macro(self, args):
"""
Used internally by AutoKey for phrase macros
"""
self.__macroArgs = args["args"].split(',')
try:
self.run_script(args["name"])
except Exception as e:
self.set_return_value("{ERROR: %s}" % str(e)) | python | def run_script_from_macro(self, args):
"""
Used internally by AutoKey for phrase macros
"""
self.__macroArgs = args["args"].split(',')
try:
self.run_script(args["name"])
except Exception as e:
self.set_return_value("{ERROR: %s}" % str(e)) | [
"def",
"run_script_from_macro",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"__macroArgs",
"=",
"args",
"[",
"\"args\"",
"]",
".",
"split",
"(",
"','",
")",
"try",
":",
"self",
".",
"run_script",
"(",
"args",
"[",
"\"name\"",
"]",
")",
"except",
... | Used internally by AutoKey for phrase macros | [
"Used",
"internally",
"by",
"AutoKey",
"for",
"phrase",
"macros"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting.py#L1256-L1265 |
225,814 | autokey/autokey | lib/autokey/scripting_highlevel.py | move_to_pat | def move_to_pat(pat: str, offset: (float, float)=None, tolerance: int=0) -> None:
"""See help for click_on_pat"""
with tempfile.NamedTemporaryFile() as f:
subprocess.call('''
xwd -root -silent -display :0 |
convert xwd:- png:''' + f.name, shell=True)
loc = visgrep(f.name, pat, tolerance)
pat_size = get_png_dim(pat)
if offset is None:
x, y = [l + ps//2 for l, ps in zip(loc, pat_size)]
else:
x, y = [l + ps*(off/100) for off, l, ps in zip(offset, loc, pat_size)]
mouse_move(x, y) | python | def move_to_pat(pat: str, offset: (float, float)=None, tolerance: int=0) -> None:
"""See help for click_on_pat"""
with tempfile.NamedTemporaryFile() as f:
subprocess.call('''
xwd -root -silent -display :0 |
convert xwd:- png:''' + f.name, shell=True)
loc = visgrep(f.name, pat, tolerance)
pat_size = get_png_dim(pat)
if offset is None:
x, y = [l + ps//2 for l, ps in zip(loc, pat_size)]
else:
x, y = [l + ps*(off/100) for off, l, ps in zip(offset, loc, pat_size)]
mouse_move(x, y) | [
"def",
"move_to_pat",
"(",
"pat",
":",
"str",
",",
"offset",
":",
"(",
"float",
",",
"float",
")",
"=",
"None",
",",
"tolerance",
":",
"int",
"=",
"0",
")",
"->",
"None",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
")",
"as",
"f",
":",... | See help for click_on_pat | [
"See",
"help",
"for",
"click_on_pat"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting_highlevel.py#L99-L111 |
225,815 | autokey/autokey | lib/autokey/scripting_highlevel.py | acknowledge_gnome_notification | def acknowledge_gnome_notification():
"""
Moves mouse pointer to the bottom center of the screen and clicks on it.
"""
x0, y0 = mouse_pos()
mouse_move(10000, 10000) # TODO: What if the screen is larger? Loop until mouse position does not change anymore?
x, y = mouse_pos()
mouse_rmove(-x/2, 0)
mouse_click(LEFT)
time.sleep(.2)
mouse_move(x0, y0) | python | def acknowledge_gnome_notification():
"""
Moves mouse pointer to the bottom center of the screen and clicks on it.
"""
x0, y0 = mouse_pos()
mouse_move(10000, 10000) # TODO: What if the screen is larger? Loop until mouse position does not change anymore?
x, y = mouse_pos()
mouse_rmove(-x/2, 0)
mouse_click(LEFT)
time.sleep(.2)
mouse_move(x0, y0) | [
"def",
"acknowledge_gnome_notification",
"(",
")",
":",
"x0",
",",
"y0",
"=",
"mouse_pos",
"(",
")",
"mouse_move",
"(",
"10000",
",",
"10000",
")",
"# TODO: What if the screen is larger? Loop until mouse position does not change anymore?",
"x",
",",
"y",
"=",
"mouse_pos... | Moves mouse pointer to the bottom center of the screen and clicks on it. | [
"Moves",
"mouse",
"pointer",
"to",
"the",
"bottom",
"center",
"of",
"the",
"screen",
"and",
"clicks",
"on",
"it",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/scripting_highlevel.py#L114-L124 |
225,816 | autokey/autokey | lib/autokey/service.py | Service.calculate_extra_keys | def calculate_extra_keys(self, buffer):
"""
Determine extra keys pressed since the given buffer was built
"""
extraBs = len(self.inputStack) - len(buffer)
if extraBs > 0:
extraKeys = ''.join(self.inputStack[len(buffer)])
else:
extraBs = 0
extraKeys = ''
return extraBs, extraKeys | python | def calculate_extra_keys(self, buffer):
"""
Determine extra keys pressed since the given buffer was built
"""
extraBs = len(self.inputStack) - len(buffer)
if extraBs > 0:
extraKeys = ''.join(self.inputStack[len(buffer)])
else:
extraBs = 0
extraKeys = ''
return extraBs, extraKeys | [
"def",
"calculate_extra_keys",
"(",
"self",
",",
"buffer",
")",
":",
"extraBs",
"=",
"len",
"(",
"self",
".",
"inputStack",
")",
"-",
"len",
"(",
"buffer",
")",
"if",
"extraBs",
">",
"0",
":",
"extraKeys",
"=",
"''",
".",
"join",
"(",
"self",
".",
... | Determine extra keys pressed since the given buffer was built | [
"Determine",
"extra",
"keys",
"pressed",
"since",
"the",
"given",
"buffer",
"was",
"built"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/service.py#L244-L254 |
225,817 | autokey/autokey | lib/autokey/service.py | Service.__updateStack | def __updateStack(self, key):
"""
Update the input stack in non-hotkey mode, and determine if anything
further is needed.
@return: True if further action is needed
"""
#if self.lastMenu is not None:
# if not ConfigManager.SETTINGS[MENU_TAKES_FOCUS]:
# self.app.hide_menu()
#
# self.lastMenu = None
if key == Key.ENTER:
# Special case - map Enter to \n
key = '\n'
if key == Key.TAB:
# Special case - map Tab to \t
key = '\t'
if key == Key.BACKSPACE:
if ConfigManager.SETTINGS[UNDO_USING_BACKSPACE] and self.phraseRunner.can_undo():
self.phraseRunner.undo_expansion()
else:
# handle backspace by dropping the last saved character
try:
self.inputStack.pop()
except IndexError:
# in case self.inputStack is empty
pass
return False
elif len(key) > 1:
# non-simple key
self.inputStack.clear()
self.phraseRunner.clear_last()
return False
else:
# Key is a character
self.phraseRunner.clear_last()
# if len(self.inputStack) == MAX_STACK_LENGTH, front items will removed for appending new items.
self.inputStack.append(key)
return True | python | def __updateStack(self, key):
"""
Update the input stack in non-hotkey mode, and determine if anything
further is needed.
@return: True if further action is needed
"""
#if self.lastMenu is not None:
# if not ConfigManager.SETTINGS[MENU_TAKES_FOCUS]:
# self.app.hide_menu()
#
# self.lastMenu = None
if key == Key.ENTER:
# Special case - map Enter to \n
key = '\n'
if key == Key.TAB:
# Special case - map Tab to \t
key = '\t'
if key == Key.BACKSPACE:
if ConfigManager.SETTINGS[UNDO_USING_BACKSPACE] and self.phraseRunner.can_undo():
self.phraseRunner.undo_expansion()
else:
# handle backspace by dropping the last saved character
try:
self.inputStack.pop()
except IndexError:
# in case self.inputStack is empty
pass
return False
elif len(key) > 1:
# non-simple key
self.inputStack.clear()
self.phraseRunner.clear_last()
return False
else:
# Key is a character
self.phraseRunner.clear_last()
# if len(self.inputStack) == MAX_STACK_LENGTH, front items will removed for appending new items.
self.inputStack.append(key)
return True | [
"def",
"__updateStack",
"(",
"self",
",",
"key",
")",
":",
"#if self.lastMenu is not None:",
"# if not ConfigManager.SETTINGS[MENU_TAKES_FOCUS]:",
"# self.app.hide_menu()",
"#",
"# self.lastMenu = None",
"if",
"key",
"==",
"Key",
".",
"ENTER",
":",
"# Special cas... | Update the input stack in non-hotkey mode, and determine if anything
further is needed.
@return: True if further action is needed | [
"Update",
"the",
"input",
"stack",
"in",
"non",
"-",
"hotkey",
"mode",
"and",
"determine",
"if",
"anything",
"further",
"is",
"needed",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/service.py#L256-L299 |
225,818 | autokey/autokey | lib/autokey/interface.py | XInterfaceBase.__grabHotkeys | def __grabHotkeys(self):
"""
Run during startup to grab global and specific hotkeys in all open windows
"""
c = self.app.configManager
hotkeys = c.hotKeys + c.hotKeyFolders
# Grab global hotkeys in root window
for item in c.globalHotkeys:
if item.enabled:
self.__enqueue(self.__grabHotkey, item.hotKey, item.modifiers, self.rootWindow)
if self.__needsMutterWorkaround(item):
self.__enqueue(self.__grabRecurse, item, self.rootWindow, False)
# Grab hotkeys without a filter in root window
for item in hotkeys:
if item.get_applicable_regex() is None:
self.__enqueue(self.__grabHotkey, item.hotKey, item.modifiers, self.rootWindow)
if self.__needsMutterWorkaround(item):
self.__enqueue(self.__grabRecurse, item, self.rootWindow, False)
self.__enqueue(self.__recurseTree, self.rootWindow, hotkeys) | python | def __grabHotkeys(self):
"""
Run during startup to grab global and specific hotkeys in all open windows
"""
c = self.app.configManager
hotkeys = c.hotKeys + c.hotKeyFolders
# Grab global hotkeys in root window
for item in c.globalHotkeys:
if item.enabled:
self.__enqueue(self.__grabHotkey, item.hotKey, item.modifiers, self.rootWindow)
if self.__needsMutterWorkaround(item):
self.__enqueue(self.__grabRecurse, item, self.rootWindow, False)
# Grab hotkeys without a filter in root window
for item in hotkeys:
if item.get_applicable_regex() is None:
self.__enqueue(self.__grabHotkey, item.hotKey, item.modifiers, self.rootWindow)
if self.__needsMutterWorkaround(item):
self.__enqueue(self.__grabRecurse, item, self.rootWindow, False)
self.__enqueue(self.__recurseTree, self.rootWindow, hotkeys) | [
"def",
"__grabHotkeys",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"app",
".",
"configManager",
"hotkeys",
"=",
"c",
".",
"hotKeys",
"+",
"c",
".",
"hotKeyFolders",
"# Grab global hotkeys in root window",
"for",
"item",
"in",
"c",
".",
"globalHotkeys",
":... | Run during startup to grab global and specific hotkeys in all open windows | [
"Run",
"during",
"startup",
"to",
"grab",
"global",
"and",
"specific",
"hotkeys",
"in",
"all",
"open",
"windows"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/interface.py#L353-L374 |
225,819 | autokey/autokey | lib/autokey/interface.py | XInterfaceBase.__ungrabAllHotkeys | def __ungrabAllHotkeys(self):
"""
Ungrab all hotkeys in preparation for keymap change
"""
c = self.app.configManager
hotkeys = c.hotKeys + c.hotKeyFolders
# Ungrab global hotkeys in root window, recursively
for item in c.globalHotkeys:
if item.enabled:
self.__ungrabHotkey(item.hotKey, item.modifiers, self.rootWindow)
if self.__needsMutterWorkaround(item):
self.__ungrabRecurse(item, self.rootWindow, False)
# Ungrab hotkeys without a filter in root window, recursively
for item in hotkeys:
if item.get_applicable_regex() is None:
self.__ungrabHotkey(item.hotKey, item.modifiers, self.rootWindow)
if self.__needsMutterWorkaround(item):
self.__ungrabRecurse(item, self.rootWindow, False)
self.__recurseTreeUngrab(self.rootWindow, hotkeys) | python | def __ungrabAllHotkeys(self):
"""
Ungrab all hotkeys in preparation for keymap change
"""
c = self.app.configManager
hotkeys = c.hotKeys + c.hotKeyFolders
# Ungrab global hotkeys in root window, recursively
for item in c.globalHotkeys:
if item.enabled:
self.__ungrabHotkey(item.hotKey, item.modifiers, self.rootWindow)
if self.__needsMutterWorkaround(item):
self.__ungrabRecurse(item, self.rootWindow, False)
# Ungrab hotkeys without a filter in root window, recursively
for item in hotkeys:
if item.get_applicable_regex() is None:
self.__ungrabHotkey(item.hotKey, item.modifiers, self.rootWindow)
if self.__needsMutterWorkaround(item):
self.__ungrabRecurse(item, self.rootWindow, False)
self.__recurseTreeUngrab(self.rootWindow, hotkeys) | [
"def",
"__ungrabAllHotkeys",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"app",
".",
"configManager",
"hotkeys",
"=",
"c",
".",
"hotKeys",
"+",
"c",
".",
"hotKeyFolders",
"# Ungrab global hotkeys in root window, recursively",
"for",
"item",
"in",
"c",
".",
"... | Ungrab all hotkeys in preparation for keymap change | [
"Ungrab",
"all",
"hotkeys",
"in",
"preparation",
"for",
"keymap",
"change"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/interface.py#L397-L418 |
225,820 | autokey/autokey | lib/autokey/interface.py | XInterfaceBase.__grabHotkeysForWindow | def __grabHotkeysForWindow(self, window):
"""
Grab all hotkeys relevant to the window
Used when a new window is created
"""
c = self.app.configManager
hotkeys = c.hotKeys + c.hotKeyFolders
window_info = self.get_window_info(window)
for item in hotkeys:
if item.get_applicable_regex() is not None and item._should_trigger_window_title(window_info):
self.__enqueue(self.__grabHotkey, item.hotKey, item.modifiers, window)
elif self.__needsMutterWorkaround(item):
self.__enqueue(self.__grabHotkey, item.hotKey, item.modifiers, window) | python | def __grabHotkeysForWindow(self, window):
"""
Grab all hotkeys relevant to the window
Used when a new window is created
"""
c = self.app.configManager
hotkeys = c.hotKeys + c.hotKeyFolders
window_info = self.get_window_info(window)
for item in hotkeys:
if item.get_applicable_regex() is not None and item._should_trigger_window_title(window_info):
self.__enqueue(self.__grabHotkey, item.hotKey, item.modifiers, window)
elif self.__needsMutterWorkaround(item):
self.__enqueue(self.__grabHotkey, item.hotKey, item.modifiers, window) | [
"def",
"__grabHotkeysForWindow",
"(",
"self",
",",
"window",
")",
":",
"c",
"=",
"self",
".",
"app",
".",
"configManager",
"hotkeys",
"=",
"c",
".",
"hotKeys",
"+",
"c",
".",
"hotKeyFolders",
"window_info",
"=",
"self",
".",
"get_window_info",
"(",
"window... | Grab all hotkeys relevant to the window
Used when a new window is created | [
"Grab",
"all",
"hotkeys",
"relevant",
"to",
"the",
"window"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/interface.py#L441-L454 |
225,821 | autokey/autokey | lib/autokey/interface.py | XInterfaceBase.__grabHotkey | def __grabHotkey(self, key, modifiers, window):
"""
Grab a specific hotkey in the given window
"""
logger.debug("Grabbing hotkey: %r %r", modifiers, key)
try:
keycode = self.__lookupKeyCode(key)
mask = 0
for mod in modifiers:
mask |= self.modMasks[mod]
window.grab_key(keycode, mask, True, X.GrabModeAsync, X.GrabModeAsync)
if Key.NUMLOCK in self.modMasks:
window.grab_key(keycode, mask|self.modMasks[Key.NUMLOCK], True, X.GrabModeAsync, X.GrabModeAsync)
if Key.CAPSLOCK in self.modMasks:
window.grab_key(keycode, mask|self.modMasks[Key.CAPSLOCK], True, X.GrabModeAsync, X.GrabModeAsync)
if Key.CAPSLOCK in self.modMasks and Key.NUMLOCK in self.modMasks:
window.grab_key(keycode, mask|self.modMasks[Key.CAPSLOCK]|self.modMasks[Key.NUMLOCK], True, X.GrabModeAsync, X.GrabModeAsync)
except Exception as e:
logger.warning("Failed to grab hotkey %r %r: %s", modifiers, key, str(e)) | python | def __grabHotkey(self, key, modifiers, window):
"""
Grab a specific hotkey in the given window
"""
logger.debug("Grabbing hotkey: %r %r", modifiers, key)
try:
keycode = self.__lookupKeyCode(key)
mask = 0
for mod in modifiers:
mask |= self.modMasks[mod]
window.grab_key(keycode, mask, True, X.GrabModeAsync, X.GrabModeAsync)
if Key.NUMLOCK in self.modMasks:
window.grab_key(keycode, mask|self.modMasks[Key.NUMLOCK], True, X.GrabModeAsync, X.GrabModeAsync)
if Key.CAPSLOCK in self.modMasks:
window.grab_key(keycode, mask|self.modMasks[Key.CAPSLOCK], True, X.GrabModeAsync, X.GrabModeAsync)
if Key.CAPSLOCK in self.modMasks and Key.NUMLOCK in self.modMasks:
window.grab_key(keycode, mask|self.modMasks[Key.CAPSLOCK]|self.modMasks[Key.NUMLOCK], True, X.GrabModeAsync, X.GrabModeAsync)
except Exception as e:
logger.warning("Failed to grab hotkey %r %r: %s", modifiers, key, str(e)) | [
"def",
"__grabHotkey",
"(",
"self",
",",
"key",
",",
"modifiers",
",",
"window",
")",
":",
"logger",
".",
"debug",
"(",
"\"Grabbing hotkey: %r %r\"",
",",
"modifiers",
",",
"key",
")",
"try",
":",
"keycode",
"=",
"self",
".",
"__lookupKeyCode",
"(",
"key",... | Grab a specific hotkey in the given window | [
"Grab",
"a",
"specific",
"hotkey",
"in",
"the",
"given",
"window"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/interface.py#L456-L479 |
225,822 | autokey/autokey | lib/autokey/interface.py | XInterfaceBase.grab_hotkey | def grab_hotkey(self, item):
"""
Grab a hotkey.
If the hotkey has no filter regex, it is global and is grabbed recursively from the root window
If it has a filter regex, iterate over all children of the root and grab from matching windows
"""
if item.get_applicable_regex() is None:
self.__enqueue(self.__grabHotkey, item.hotKey, item.modifiers, self.rootWindow)
if self.__needsMutterWorkaround(item):
self.__enqueue(self.__grabRecurse, item, self.rootWindow, False)
else:
self.__enqueue(self.__grabRecurse, item, self.rootWindow) | python | def grab_hotkey(self, item):
"""
Grab a hotkey.
If the hotkey has no filter regex, it is global and is grabbed recursively from the root window
If it has a filter regex, iterate over all children of the root and grab from matching windows
"""
if item.get_applicable_regex() is None:
self.__enqueue(self.__grabHotkey, item.hotKey, item.modifiers, self.rootWindow)
if self.__needsMutterWorkaround(item):
self.__enqueue(self.__grabRecurse, item, self.rootWindow, False)
else:
self.__enqueue(self.__grabRecurse, item, self.rootWindow) | [
"def",
"grab_hotkey",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
".",
"get_applicable_regex",
"(",
")",
"is",
"None",
":",
"self",
".",
"__enqueue",
"(",
"self",
".",
"__grabHotkey",
",",
"item",
".",
"hotKey",
",",
"item",
".",
"modifiers",
","... | Grab a hotkey.
If the hotkey has no filter regex, it is global and is grabbed recursively from the root window
If it has a filter regex, iterate over all children of the root and grab from matching windows | [
"Grab",
"a",
"hotkey",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/interface.py#L481-L493 |
225,823 | autokey/autokey | lib/autokey/interface.py | XInterfaceBase.ungrab_hotkey | def ungrab_hotkey(self, item):
"""
Ungrab a hotkey.
If the hotkey has no filter regex, it is global and is grabbed recursively from the root window
If it has a filter regex, iterate over all children of the root and ungrab from matching windows
"""
import copy
newItem = copy.copy(item)
if item.get_applicable_regex() is None:
self.__enqueue(self.__ungrabHotkey, newItem.hotKey, newItem.modifiers, self.rootWindow)
if self.__needsMutterWorkaround(item):
self.__enqueue(self.__ungrabRecurse, newItem, self.rootWindow, False)
else:
self.__enqueue(self.__ungrabRecurse, newItem, self.rootWindow) | python | def ungrab_hotkey(self, item):
"""
Ungrab a hotkey.
If the hotkey has no filter regex, it is global and is grabbed recursively from the root window
If it has a filter regex, iterate over all children of the root and ungrab from matching windows
"""
import copy
newItem = copy.copy(item)
if item.get_applicable_regex() is None:
self.__enqueue(self.__ungrabHotkey, newItem.hotKey, newItem.modifiers, self.rootWindow)
if self.__needsMutterWorkaround(item):
self.__enqueue(self.__ungrabRecurse, newItem, self.rootWindow, False)
else:
self.__enqueue(self.__ungrabRecurse, newItem, self.rootWindow) | [
"def",
"ungrab_hotkey",
"(",
"self",
",",
"item",
")",
":",
"import",
"copy",
"newItem",
"=",
"copy",
".",
"copy",
"(",
"item",
")",
"if",
"item",
".",
"get_applicable_regex",
"(",
")",
"is",
"None",
":",
"self",
".",
"__enqueue",
"(",
"self",
".",
"... | Ungrab a hotkey.
If the hotkey has no filter regex, it is global and is grabbed recursively from the root window
If it has a filter regex, iterate over all children of the root and ungrab from matching windows | [
"Ungrab",
"a",
"hotkey",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/interface.py#L514-L529 |
225,824 | autokey/autokey | lib/autokey/interface.py | XInterfaceBase.__ungrabHotkey | def __ungrabHotkey(self, key, modifiers, window):
"""
Ungrab a specific hotkey in the given window
"""
logger.debug("Ungrabbing hotkey: %r %r", modifiers, key)
try:
keycode = self.__lookupKeyCode(key)
mask = 0
for mod in modifiers:
mask |= self.modMasks[mod]
window.ungrab_key(keycode, mask)
if Key.NUMLOCK in self.modMasks:
window.ungrab_key(keycode, mask|self.modMasks[Key.NUMLOCK])
if Key.CAPSLOCK in self.modMasks:
window.ungrab_key(keycode, mask|self.modMasks[Key.CAPSLOCK])
if Key.CAPSLOCK in self.modMasks and Key.NUMLOCK in self.modMasks:
window.ungrab_key(keycode, mask|self.modMasks[Key.CAPSLOCK]|self.modMasks[Key.NUMLOCK])
except Exception as e:
logger.warning("Failed to ungrab hotkey %r %r: %s", modifiers, key, str(e)) | python | def __ungrabHotkey(self, key, modifiers, window):
"""
Ungrab a specific hotkey in the given window
"""
logger.debug("Ungrabbing hotkey: %r %r", modifiers, key)
try:
keycode = self.__lookupKeyCode(key)
mask = 0
for mod in modifiers:
mask |= self.modMasks[mod]
window.ungrab_key(keycode, mask)
if Key.NUMLOCK in self.modMasks:
window.ungrab_key(keycode, mask|self.modMasks[Key.NUMLOCK])
if Key.CAPSLOCK in self.modMasks:
window.ungrab_key(keycode, mask|self.modMasks[Key.CAPSLOCK])
if Key.CAPSLOCK in self.modMasks and Key.NUMLOCK in self.modMasks:
window.ungrab_key(keycode, mask|self.modMasks[Key.CAPSLOCK]|self.modMasks[Key.NUMLOCK])
except Exception as e:
logger.warning("Failed to ungrab hotkey %r %r: %s", modifiers, key, str(e)) | [
"def",
"__ungrabHotkey",
"(",
"self",
",",
"key",
",",
"modifiers",
",",
"window",
")",
":",
"logger",
".",
"debug",
"(",
"\"Ungrabbing hotkey: %r %r\"",
",",
"modifiers",
",",
"key",
")",
"try",
":",
"keycode",
"=",
"self",
".",
"__lookupKeyCode",
"(",
"k... | Ungrab a specific hotkey in the given window | [
"Ungrab",
"a",
"specific",
"hotkey",
"in",
"the",
"given",
"window"
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/interface.py#L550-L572 |
225,825 | autokey/autokey | lib/autokey/interface.py | XInterfaceBase._send_string_clipboard | def _send_string_clipboard(self, string: str, paste_command: model.SendMode):
"""
Use the clipboard to send a string.
"""
backup = self.clipboard.text # Keep a backup of current content, to restore the original afterwards.
if backup is None:
logger.warning("Tried to backup the X clipboard content, but got None instead of a string.")
self.clipboard.text = string
try:
self.mediator.send_string(paste_command.value)
finally:
self.ungrab_keyboard()
# Because send_string is queued, also enqueue the clipboard restore, to keep the proper action ordering.
self.__enqueue(self._restore_clipboard_text, backup) | python | def _send_string_clipboard(self, string: str, paste_command: model.SendMode):
"""
Use the clipboard to send a string.
"""
backup = self.clipboard.text # Keep a backup of current content, to restore the original afterwards.
if backup is None:
logger.warning("Tried to backup the X clipboard content, but got None instead of a string.")
self.clipboard.text = string
try:
self.mediator.send_string(paste_command.value)
finally:
self.ungrab_keyboard()
# Because send_string is queued, also enqueue the clipboard restore, to keep the proper action ordering.
self.__enqueue(self._restore_clipboard_text, backup) | [
"def",
"_send_string_clipboard",
"(",
"self",
",",
"string",
":",
"str",
",",
"paste_command",
":",
"model",
".",
"SendMode",
")",
":",
"backup",
"=",
"self",
".",
"clipboard",
".",
"text",
"# Keep a backup of current content, to restore the original afterwards.",
"if... | Use the clipboard to send a string. | [
"Use",
"the",
"clipboard",
"to",
"send",
"a",
"string",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/interface.py#L615-L628 |
225,826 | autokey/autokey | lib/autokey/interface.py | XInterfaceBase._restore_clipboard_text | def _restore_clipboard_text(self, backup: str):
"""Restore the clipboard content."""
# Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before
# the pasting happens, causing the backup to be pasted instead of the desired clipboard content.
time.sleep(0.2)
self.clipboard.text = backup if backup is not None else "" | python | def _restore_clipboard_text(self, backup: str):
"""Restore the clipboard content."""
# Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before
# the pasting happens, causing the backup to be pasted instead of the desired clipboard content.
time.sleep(0.2)
self.clipboard.text = backup if backup is not None else "" | [
"def",
"_restore_clipboard_text",
"(",
"self",
",",
"backup",
":",
"str",
")",
":",
"# Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before",
"# the pasting happens, causing the backup to be pasted instead of the desired clipboard content.",... | Restore the clipboard content. | [
"Restore",
"the",
"clipboard",
"content",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/interface.py#L630-L635 |
225,827 | autokey/autokey | lib/autokey/interface.py | XInterfaceBase._send_string_selection | def _send_string_selection(self, string: str):
"""Use the mouse selection clipboard to send a string."""
backup = self.clipboard.selection # Keep a backup of current content, to restore the original afterwards.
if backup is None:
logger.warning("Tried to backup the X PRIMARY selection content, but got None instead of a string.")
self.clipboard.selection = string
self.__enqueue(self._paste_using_mouse_button_2)
self.__enqueue(self._restore_clipboard_selection, backup) | python | def _send_string_selection(self, string: str):
"""Use the mouse selection clipboard to send a string."""
backup = self.clipboard.selection # Keep a backup of current content, to restore the original afterwards.
if backup is None:
logger.warning("Tried to backup the X PRIMARY selection content, but got None instead of a string.")
self.clipboard.selection = string
self.__enqueue(self._paste_using_mouse_button_2)
self.__enqueue(self._restore_clipboard_selection, backup) | [
"def",
"_send_string_selection",
"(",
"self",
",",
"string",
":",
"str",
")",
":",
"backup",
"=",
"self",
".",
"clipboard",
".",
"selection",
"# Keep a backup of current content, to restore the original afterwards.",
"if",
"backup",
"is",
"None",
":",
"logger",
".",
... | Use the mouse selection clipboard to send a string. | [
"Use",
"the",
"mouse",
"selection",
"clipboard",
"to",
"send",
"a",
"string",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/interface.py#L637-L644 |
225,828 | autokey/autokey | lib/autokey/interface.py | XInterfaceBase._restore_clipboard_selection | def _restore_clipboard_selection(self, backup: str):
"""Restore the selection clipboard content."""
# Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before
# the pasting happens, causing the backup to be pasted instead of the desired clipboard content.
# Programmatically pressing the middle mouse button seems VERY slow, so wait rather long.
# It might be a good idea to make this delay configurable. There might be systems that need even longer.
time.sleep(1)
self.clipboard.selection = backup if backup is not None else "" | python | def _restore_clipboard_selection(self, backup: str):
"""Restore the selection clipboard content."""
# Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before
# the pasting happens, causing the backup to be pasted instead of the desired clipboard content.
# Programmatically pressing the middle mouse button seems VERY slow, so wait rather long.
# It might be a good idea to make this delay configurable. There might be systems that need even longer.
time.sleep(1)
self.clipboard.selection = backup if backup is not None else "" | [
"def",
"_restore_clipboard_selection",
"(",
"self",
",",
"backup",
":",
"str",
")",
":",
"# Pasting takes some time, so wait a bit before restoring the content. Otherwise the restore is done before",
"# the pasting happens, causing the backup to be pasted instead of the desired clipboard conte... | Restore the selection clipboard content. | [
"Restore",
"the",
"selection",
"clipboard",
"content",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/interface.py#L646-L654 |
225,829 | autokey/autokey | lib/autokey/qtui/settings/engine.py | EngineSettings.save | def save(self):
"""This function is called by the parent dialog window when the user selects to save the settings."""
if self.path is None: # Delete requested, so remove the current path from sys.path, if present
if self.config_manager.userCodeDir is not None:
sys.path.remove(self.config_manager.userCodeDir)
self.config_manager.userCodeDir = None
logger.info("Removed custom module search path from configuration and sys.path.")
else:
if self.path != self.config_manager.userCodeDir:
if self.config_manager.userCodeDir is not None:
sys.path.remove(self.config_manager.userCodeDir)
sys.path.append(self.path)
self.config_manager.userCodeDir = self.path
logger.info("Saved custom module search path and added it to sys.path: {}".format(self.path)) | python | def save(self):
"""This function is called by the parent dialog window when the user selects to save the settings."""
if self.path is None: # Delete requested, so remove the current path from sys.path, if present
if self.config_manager.userCodeDir is not None:
sys.path.remove(self.config_manager.userCodeDir)
self.config_manager.userCodeDir = None
logger.info("Removed custom module search path from configuration and sys.path.")
else:
if self.path != self.config_manager.userCodeDir:
if self.config_manager.userCodeDir is not None:
sys.path.remove(self.config_manager.userCodeDir)
sys.path.append(self.path)
self.config_manager.userCodeDir = self.path
logger.info("Saved custom module search path and added it to sys.path: {}".format(self.path)) | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"path",
"is",
"None",
":",
"# Delete requested, so remove the current path from sys.path, if present",
"if",
"self",
".",
"config_manager",
".",
"userCodeDir",
"is",
"not",
"None",
":",
"sys",
".",
"path",
... | This function is called by the parent dialog window when the user selects to save the settings. | [
"This",
"function",
"is",
"called",
"by",
"the",
"parent",
"dialog",
"window",
"when",
"the",
"user",
"selects",
"to",
"save",
"the",
"settings",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/settings/engine.py#L55-L69 |
225,830 | autokey/autokey | lib/autokey/qtui/settings/engine.py | EngineSettings.on_browse_button_pressed | def on_browse_button_pressed(self):
"""
PyQt slot called when the user hits the "Browse" button.
Display a directory selection dialog and store the returned path.
"""
path = QFileDialog.getExistingDirectory(self.parentWidget(), "Choose a directory containing Python modules")
if path: # Non-empty means the user chose a path and clicked on OK
self.path = path
self.clear_button.setEnabled(True)
self.folder_label.setText(path)
logger.debug("User selects a custom module search path: {}".format(self.path)) | python | def on_browse_button_pressed(self):
"""
PyQt slot called when the user hits the "Browse" button.
Display a directory selection dialog and store the returned path.
"""
path = QFileDialog.getExistingDirectory(self.parentWidget(), "Choose a directory containing Python modules")
if path: # Non-empty means the user chose a path and clicked on OK
self.path = path
self.clear_button.setEnabled(True)
self.folder_label.setText(path)
logger.debug("User selects a custom module search path: {}".format(self.path)) | [
"def",
"on_browse_button_pressed",
"(",
"self",
")",
":",
"path",
"=",
"QFileDialog",
".",
"getExistingDirectory",
"(",
"self",
".",
"parentWidget",
"(",
")",
",",
"\"Choose a directory containing Python modules\"",
")",
"if",
"path",
":",
"# Non-empty means the user ch... | PyQt slot called when the user hits the "Browse" button.
Display a directory selection dialog and store the returned path. | [
"PyQt",
"slot",
"called",
"when",
"the",
"user",
"hits",
"the",
"Browse",
"button",
".",
"Display",
"a",
"directory",
"selection",
"dialog",
"and",
"store",
"the",
"returned",
"path",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/settings/engine.py#L72-L83 |
225,831 | autokey/autokey | lib/autokey/qtui/settings/engine.py | EngineSettings.on_clear_button_pressed | def on_clear_button_pressed(self):
"""
PyQt slot called when the user hits the "Clear" button.
Removes any set custom module search path.
"""
self.path = None
self.clear_button.setEnabled(False)
self.folder_label.setText(self.initial_folder_label_text)
logger.debug("User selects to clear the custom module search path.") | python | def on_clear_button_pressed(self):
"""
PyQt slot called when the user hits the "Clear" button.
Removes any set custom module search path.
"""
self.path = None
self.clear_button.setEnabled(False)
self.folder_label.setText(self.initial_folder_label_text)
logger.debug("User selects to clear the custom module search path.") | [
"def",
"on_clear_button_pressed",
"(",
"self",
")",
":",
"self",
".",
"path",
"=",
"None",
"self",
".",
"clear_button",
".",
"setEnabled",
"(",
"False",
")",
"self",
".",
"folder_label",
".",
"setText",
"(",
"self",
".",
"initial_folder_label_text",
")",
"lo... | PyQt slot called when the user hits the "Clear" button.
Removes any set custom module search path. | [
"PyQt",
"slot",
"called",
"when",
"the",
"user",
"hits",
"the",
"Clear",
"button",
".",
"Removes",
"any",
"set",
"custom",
"module",
"search",
"path",
"."
] | 35decb72f286ce68cd2a1f09ace8891a520b58d1 | https://github.com/autokey/autokey/blob/35decb72f286ce68cd2a1f09ace8891a520b58d1/lib/autokey/qtui/settings/engine.py#L86-L94 |
225,832 | maartenbreddels/ipyvolume | ipyvolume/examples.py | example_ylm | def example_ylm(m=0, n=2, shape=128, limits=[-4, 4], draw=True, show=True, **kwargs):
"""Show a spherical harmonic."""
import ipyvolume.pylab as p3
__, __, __, r, theta, phi = xyz(shape=shape, limits=limits, spherical=True)
radial = np.exp(-(r - 2) ** 2)
data = np.abs(scipy.special.sph_harm(m, n, theta, phi) ** 2) * radial # pylint: disable=no-member
if draw:
vol = p3.volshow(data=data, **kwargs)
if show:
p3.show()
return vol
else:
return data | python | def example_ylm(m=0, n=2, shape=128, limits=[-4, 4], draw=True, show=True, **kwargs):
"""Show a spherical harmonic."""
import ipyvolume.pylab as p3
__, __, __, r, theta, phi = xyz(shape=shape, limits=limits, spherical=True)
radial = np.exp(-(r - 2) ** 2)
data = np.abs(scipy.special.sph_harm(m, n, theta, phi) ** 2) * radial # pylint: disable=no-member
if draw:
vol = p3.volshow(data=data, **kwargs)
if show:
p3.show()
return vol
else:
return data | [
"def",
"example_ylm",
"(",
"m",
"=",
"0",
",",
"n",
"=",
"2",
",",
"shape",
"=",
"128",
",",
"limits",
"=",
"[",
"-",
"4",
",",
"4",
"]",
",",
"draw",
"=",
"True",
",",
"show",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"ipyv... | Show a spherical harmonic. | [
"Show",
"a",
"spherical",
"harmonic",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/examples.py#L55-L68 |
225,833 | maartenbreddels/ipyvolume | ipyvolume/examples.py | ball | def ball(rmax=3, rmin=0, shape=128, limits=[-4, 4], draw=True, show=True, **kwargs):
"""Show a ball."""
import ipyvolume.pylab as p3
__, __, __, r, _theta, _phi = xyz(shape=shape, limits=limits, spherical=True)
data = r * 0
data[(r < rmax) & (r >= rmin)] = 0.5
if "data_min" not in kwargs:
kwargs["data_min"] = 0
if "data_max" not in kwargs:
kwargs["data_max"] = 1
data = data.T
if draw:
vol = p3.volshow(data=data, **kwargs)
if show:
p3.show()
return vol
else:
return data | python | def ball(rmax=3, rmin=0, shape=128, limits=[-4, 4], draw=True, show=True, **kwargs):
"""Show a ball."""
import ipyvolume.pylab as p3
__, __, __, r, _theta, _phi = xyz(shape=shape, limits=limits, spherical=True)
data = r * 0
data[(r < rmax) & (r >= rmin)] = 0.5
if "data_min" not in kwargs:
kwargs["data_min"] = 0
if "data_max" not in kwargs:
kwargs["data_max"] = 1
data = data.T
if draw:
vol = p3.volshow(data=data, **kwargs)
if show:
p3.show()
return vol
else:
return data | [
"def",
"ball",
"(",
"rmax",
"=",
"3",
",",
"rmin",
"=",
"0",
",",
"shape",
"=",
"128",
",",
"limits",
"=",
"[",
"-",
"4",
",",
"4",
"]",
",",
"draw",
"=",
"True",
",",
"show",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"ipyvo... | Show a ball. | [
"Show",
"a",
"ball",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/examples.py#L72-L90 |
225,834 | maartenbreddels/ipyvolume | ipyvolume/examples.py | brain | def brain(
draw=True, show=True, fiducial=True, flat=True, inflated=True, subject='S1', interval=1000, uv=True, color=None
):
"""Show a human brain model.
Requirement:
$ pip install https://github.com/gallantlab/pycortex
"""
import ipyvolume as ipv
try:
import cortex
except:
warnings.warn("it seems pycortex is not installed, which is needed for this example")
raise
xlist, ylist, zlist = [], [], []
polys_list = []
def add(pts, polys):
xlist.append(pts[:, 0])
ylist.append(pts[:, 1])
zlist.append(pts[:, 2])
polys_list.append(polys)
def n(x):
return (x - x.min()) / x.ptp()
if fiducial or color is True:
pts, polys = cortex.db.get_surf('S1', 'fiducial', merge=True)
x, y, z = pts.T
r = n(x)
g = n(y)
b = n(z)
if color is True:
color = np.array([r, g, b]).T.copy()
else:
color = None
if fiducial:
add(pts, polys)
else:
if color is False:
color = None
if inflated:
add(*cortex.db.get_surf('S1', 'inflated', merge=True, nudge=True))
u = v = None
if flat or uv:
pts, polys = cortex.db.get_surf('S1', 'flat', merge=True, nudge=True)
x, y, z = pts.T
u = n(x)
v = n(y)
if flat:
add(pts, polys)
polys_list.sort(key=lambda x: len(x))
polys = polys_list[0]
if draw:
if color is None:
mesh = ipv.plot_trisurf(xlist, ylist, zlist, polys, u=u, v=v)
else:
mesh = ipv.plot_trisurf(xlist, ylist, zlist, polys, color=color, u=u, v=v)
if show:
if len(x) > 1:
ipv.animation_control(mesh, interval=interval)
ipv.squarelim()
ipv.show()
return mesh
else:
return xlist, ylist, zlist, polys | python | def brain(
draw=True, show=True, fiducial=True, flat=True, inflated=True, subject='S1', interval=1000, uv=True, color=None
):
"""Show a human brain model.
Requirement:
$ pip install https://github.com/gallantlab/pycortex
"""
import ipyvolume as ipv
try:
import cortex
except:
warnings.warn("it seems pycortex is not installed, which is needed for this example")
raise
xlist, ylist, zlist = [], [], []
polys_list = []
def add(pts, polys):
xlist.append(pts[:, 0])
ylist.append(pts[:, 1])
zlist.append(pts[:, 2])
polys_list.append(polys)
def n(x):
return (x - x.min()) / x.ptp()
if fiducial or color is True:
pts, polys = cortex.db.get_surf('S1', 'fiducial', merge=True)
x, y, z = pts.T
r = n(x)
g = n(y)
b = n(z)
if color is True:
color = np.array([r, g, b]).T.copy()
else:
color = None
if fiducial:
add(pts, polys)
else:
if color is False:
color = None
if inflated:
add(*cortex.db.get_surf('S1', 'inflated', merge=True, nudge=True))
u = v = None
if flat or uv:
pts, polys = cortex.db.get_surf('S1', 'flat', merge=True, nudge=True)
x, y, z = pts.T
u = n(x)
v = n(y)
if flat:
add(pts, polys)
polys_list.sort(key=lambda x: len(x))
polys = polys_list[0]
if draw:
if color is None:
mesh = ipv.plot_trisurf(xlist, ylist, zlist, polys, u=u, v=v)
else:
mesh = ipv.plot_trisurf(xlist, ylist, zlist, polys, color=color, u=u, v=v)
if show:
if len(x) > 1:
ipv.animation_control(mesh, interval=interval)
ipv.squarelim()
ipv.show()
return mesh
else:
return xlist, ylist, zlist, polys | [
"def",
"brain",
"(",
"draw",
"=",
"True",
",",
"show",
"=",
"True",
",",
"fiducial",
"=",
"True",
",",
"flat",
"=",
"True",
",",
"inflated",
"=",
"True",
",",
"subject",
"=",
"'S1'",
",",
"interval",
"=",
"1000",
",",
"uv",
"=",
"True",
",",
"col... | Show a human brain model.
Requirement:
$ pip install https://github.com/gallantlab/pycortex | [
"Show",
"a",
"human",
"brain",
"model",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/examples.py#L161-L229 |
225,835 | maartenbreddels/ipyvolume | ipyvolume/examples.py | head | def head(draw=True, show=True, max_shape=256):
"""Show a volumetric rendering of a human male head."""
# inspired by http://graphicsrunner.blogspot.com/2009/01/volume-rendering-102-transfer-functions.html
import ipyvolume as ipv
from scipy.interpolate import interp1d
# First part is a simpler version of setting up the transfer function. Interpolation with higher order
# splines does not work well, the original must do sth different
colors = [[0.91, 0.7, 0.61, 0.0], [0.91, 0.7, 0.61, 80.0], [1.0, 1.0, 0.85, 82.0], [1.0, 1.0, 0.85, 256]]
x = np.array([k[-1] for k in colors])
rgb = np.array([k[:3] for k in colors])
N = 256
xnew = np.linspace(0, 256, N)
tf_data = np.zeros((N, 4))
kind = 'linear'
for channel in range(3):
f = interp1d(x, rgb[:, channel], kind=kind)
ynew = f(xnew)
tf_data[:, channel] = ynew
alphas = [[0, 0], [0, 40], [0.2, 60], [0.05, 63], [0, 80], [0.9, 82], [1.0, 256]]
x = np.array([k[1] * 1.0 for k in alphas])
y = np.array([k[0] * 1.0 for k in alphas])
f = interp1d(x, y, kind=kind)
ynew = f(xnew)
tf_data[:, 3] = ynew
tf = ipv.TransferFunction(rgba=tf_data.astype(np.float32))
head_data = ipv.datasets.head.fetch().data
if draw:
vol = ipv.volshow(head_data, tf=tf, max_shape=max_shape)
if show:
ipv.show()
return vol
else:
return head_data | python | def head(draw=True, show=True, max_shape=256):
"""Show a volumetric rendering of a human male head."""
# inspired by http://graphicsrunner.blogspot.com/2009/01/volume-rendering-102-transfer-functions.html
import ipyvolume as ipv
from scipy.interpolate import interp1d
# First part is a simpler version of setting up the transfer function. Interpolation with higher order
# splines does not work well, the original must do sth different
colors = [[0.91, 0.7, 0.61, 0.0], [0.91, 0.7, 0.61, 80.0], [1.0, 1.0, 0.85, 82.0], [1.0, 1.0, 0.85, 256]]
x = np.array([k[-1] for k in colors])
rgb = np.array([k[:3] for k in colors])
N = 256
xnew = np.linspace(0, 256, N)
tf_data = np.zeros((N, 4))
kind = 'linear'
for channel in range(3):
f = interp1d(x, rgb[:, channel], kind=kind)
ynew = f(xnew)
tf_data[:, channel] = ynew
alphas = [[0, 0], [0, 40], [0.2, 60], [0.05, 63], [0, 80], [0.9, 82], [1.0, 256]]
x = np.array([k[1] * 1.0 for k in alphas])
y = np.array([k[0] * 1.0 for k in alphas])
f = interp1d(x, y, kind=kind)
ynew = f(xnew)
tf_data[:, 3] = ynew
tf = ipv.TransferFunction(rgba=tf_data.astype(np.float32))
head_data = ipv.datasets.head.fetch().data
if draw:
vol = ipv.volshow(head_data, tf=tf, max_shape=max_shape)
if show:
ipv.show()
return vol
else:
return head_data | [
"def",
"head",
"(",
"draw",
"=",
"True",
",",
"show",
"=",
"True",
",",
"max_shape",
"=",
"256",
")",
":",
"# inspired by http://graphicsrunner.blogspot.com/2009/01/volume-rendering-102-transfer-functions.html",
"import",
"ipyvolume",
"as",
"ipv",
"from",
"scipy",
".",
... | Show a volumetric rendering of a human male head. | [
"Show",
"a",
"volumetric",
"rendering",
"of",
"a",
"human",
"male",
"head",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/examples.py#L232-L266 |
225,836 | maartenbreddels/ipyvolume | ipyvolume/examples.py | gaussian | def gaussian(N=1000, draw=True, show=True, seed=42, color=None, marker='sphere'):
"""Show N random gaussian distributed points using a scatter plot."""
import ipyvolume as ipv
rng = np.random.RandomState(seed) # pylint: disable=no-member
x, y, z = rng.normal(size=(3, N))
if draw:
if color:
mesh = ipv.scatter(x, y, z, marker=marker, color=color)
else:
mesh = ipv.scatter(x, y, z, marker=marker)
if show:
# ipv.squarelim()
ipv.show()
return mesh
else:
return x, y, z | python | def gaussian(N=1000, draw=True, show=True, seed=42, color=None, marker='sphere'):
"""Show N random gaussian distributed points using a scatter plot."""
import ipyvolume as ipv
rng = np.random.RandomState(seed) # pylint: disable=no-member
x, y, z = rng.normal(size=(3, N))
if draw:
if color:
mesh = ipv.scatter(x, y, z, marker=marker, color=color)
else:
mesh = ipv.scatter(x, y, z, marker=marker)
if show:
# ipv.squarelim()
ipv.show()
return mesh
else:
return x, y, z | [
"def",
"gaussian",
"(",
"N",
"=",
"1000",
",",
"draw",
"=",
"True",
",",
"show",
"=",
"True",
",",
"seed",
"=",
"42",
",",
"color",
"=",
"None",
",",
"marker",
"=",
"'sphere'",
")",
":",
"import",
"ipyvolume",
"as",
"ipv",
"rng",
"=",
"np",
".",
... | Show N random gaussian distributed points using a scatter plot. | [
"Show",
"N",
"random",
"gaussian",
"distributed",
"points",
"using",
"a",
"scatter",
"plot",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/examples.py#L269-L286 |
225,837 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | figure | def figure(
key=None,
width=400,
height=500,
lighting=True,
controls=True,
controls_vr=False,
controls_light=False,
debug=False,
**kwargs
):
"""Create a new figure if no key is given, or return the figure associated with key.
:param key: Python object that identifies this figure
:param int width: pixel width of WebGL canvas
:param int height: .. height ..
:param bool lighting: use lighting or not
:param bool controls: show controls or not
:param bool controls_vr: show controls for VR or not
:param bool debug: show debug buttons or not
:return: :any:`Figure`
"""
if key is not None and key in current.figures:
current.figure = current.figures[key]
current.container = current.containers[key]
elif isinstance(key, ipv.Figure) and key in current.figures.values():
key_index = list(current.figures.values()).index(key)
key = list(current.figures.keys())[key_index]
current.figure = current.figures[key]
current.container = current.containers[key]
else:
current.figure = ipv.Figure(width=width, height=height, **kwargs)
current.container = ipywidgets.VBox()
current.container.children = [current.figure]
if key is None:
key = uuid.uuid4().hex
current.figures[key] = current.figure
current.containers[key] = current.container
if controls:
# stereo = ipywidgets.ToggleButton(value=current.figure.stereo, description='stereo', icon='eye')
# l1 = ipywidgets.jslink((current.figure, 'stereo'), (stereo, 'value'))
# current.container.children += (ipywidgets.HBox([stereo, ]),)
pass # stereo and fullscreen are now include in the js code (per view)
if controls_vr:
eye_separation = ipywidgets.FloatSlider(value=current.figure.eye_separation, min=-10, max=10, icon='eye')
ipywidgets.jslink((eye_separation, 'value'), (current.figure, 'eye_separation'))
current.container.children += (eye_separation,)
if controls_light:
globals()['controls_light']()
if debug:
show = ipywidgets.ToggleButtons(options=["Volume", "Back", "Front", "Coordinate"])
current.container.children += (show,)
# ipywidgets.jslink((current.figure, 'show'), (show, 'value'))
traitlets.link((current.figure, 'show'), (show, 'value'))
return current.figure | python | def figure(
key=None,
width=400,
height=500,
lighting=True,
controls=True,
controls_vr=False,
controls_light=False,
debug=False,
**kwargs
):
"""Create a new figure if no key is given, or return the figure associated with key.
:param key: Python object that identifies this figure
:param int width: pixel width of WebGL canvas
:param int height: .. height ..
:param bool lighting: use lighting or not
:param bool controls: show controls or not
:param bool controls_vr: show controls for VR or not
:param bool debug: show debug buttons or not
:return: :any:`Figure`
"""
if key is not None and key in current.figures:
current.figure = current.figures[key]
current.container = current.containers[key]
elif isinstance(key, ipv.Figure) and key in current.figures.values():
key_index = list(current.figures.values()).index(key)
key = list(current.figures.keys())[key_index]
current.figure = current.figures[key]
current.container = current.containers[key]
else:
current.figure = ipv.Figure(width=width, height=height, **kwargs)
current.container = ipywidgets.VBox()
current.container.children = [current.figure]
if key is None:
key = uuid.uuid4().hex
current.figures[key] = current.figure
current.containers[key] = current.container
if controls:
# stereo = ipywidgets.ToggleButton(value=current.figure.stereo, description='stereo', icon='eye')
# l1 = ipywidgets.jslink((current.figure, 'stereo'), (stereo, 'value'))
# current.container.children += (ipywidgets.HBox([stereo, ]),)
pass # stereo and fullscreen are now include in the js code (per view)
if controls_vr:
eye_separation = ipywidgets.FloatSlider(value=current.figure.eye_separation, min=-10, max=10, icon='eye')
ipywidgets.jslink((eye_separation, 'value'), (current.figure, 'eye_separation'))
current.container.children += (eye_separation,)
if controls_light:
globals()['controls_light']()
if debug:
show = ipywidgets.ToggleButtons(options=["Volume", "Back", "Front", "Coordinate"])
current.container.children += (show,)
# ipywidgets.jslink((current.figure, 'show'), (show, 'value'))
traitlets.link((current.figure, 'show'), (show, 'value'))
return current.figure | [
"def",
"figure",
"(",
"key",
"=",
"None",
",",
"width",
"=",
"400",
",",
"height",
"=",
"500",
",",
"lighting",
"=",
"True",
",",
"controls",
"=",
"True",
",",
"controls_vr",
"=",
"False",
",",
"controls_light",
"=",
"False",
",",
"debug",
"=",
"Fals... | Create a new figure if no key is given, or return the figure associated with key.
:param key: Python object that identifies this figure
:param int width: pixel width of WebGL canvas
:param int height: .. height ..
:param bool lighting: use lighting or not
:param bool controls: show controls or not
:param bool controls_vr: show controls for VR or not
:param bool debug: show debug buttons or not
:return: :any:`Figure` | [
"Create",
"a",
"new",
"figure",
"if",
"no",
"key",
"is",
"given",
"or",
"return",
"the",
"figure",
"associated",
"with",
"key",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L168-L222 |
225,838 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | squarelim | def squarelim():
"""Set all axes with equal aspect ratio, such that the space is 'square'."""
fig = gcf()
xmin, xmax = fig.xlim
ymin, ymax = fig.ylim
zmin, zmax = fig.zlim
width = max([abs(xmax - xmin), abs(ymax - ymin), abs(zmax - zmin)])
xc = (xmin + xmax) / 2
yc = (ymin + ymax) / 2
zc = (zmin + zmax) / 2
xlim(xc - width / 2, xc + width / 2)
ylim(yc - width / 2, yc + width / 2)
zlim(zc - width / 2, zc + width / 2) | python | def squarelim():
"""Set all axes with equal aspect ratio, such that the space is 'square'."""
fig = gcf()
xmin, xmax = fig.xlim
ymin, ymax = fig.ylim
zmin, zmax = fig.zlim
width = max([abs(xmax - xmin), abs(ymax - ymin), abs(zmax - zmin)])
xc = (xmin + xmax) / 2
yc = (ymin + ymax) / 2
zc = (zmin + zmax) / 2
xlim(xc - width / 2, xc + width / 2)
ylim(yc - width / 2, yc + width / 2)
zlim(zc - width / 2, zc + width / 2) | [
"def",
"squarelim",
"(",
")",
":",
"fig",
"=",
"gcf",
"(",
")",
"xmin",
",",
"xmax",
"=",
"fig",
".",
"xlim",
"ymin",
",",
"ymax",
"=",
"fig",
".",
"ylim",
"zmin",
",",
"zmax",
"=",
"fig",
".",
"zlim",
"width",
"=",
"max",
"(",
"[",
"abs",
"(... | Set all axes with equal aspect ratio, such that the space is 'square'. | [
"Set",
"all",
"axes",
"with",
"equal",
"aspect",
"ratio",
"such",
"that",
"the",
"space",
"is",
"square",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L290-L302 |
225,839 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | plot_surface | def plot_surface(x, y, z, color=default_color, wrapx=False, wrapy=False):
"""Draws a 2d surface in 3d, defined by the 2d ordered arrays x,y,z.
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param color: {color2d}
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points
:param bool wrapy: simular for the y coordinate
:return: :any:`Mesh`
"""
return plot_mesh(x, y, z, color=color, wrapx=wrapx, wrapy=wrapy, wireframe=False) | python | def plot_surface(x, y, z, color=default_color, wrapx=False, wrapy=False):
"""Draws a 2d surface in 3d, defined by the 2d ordered arrays x,y,z.
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param color: {color2d}
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points
:param bool wrapy: simular for the y coordinate
:return: :any:`Mesh`
"""
return plot_mesh(x, y, z, color=color, wrapx=wrapx, wrapy=wrapy, wireframe=False) | [
"def",
"plot_surface",
"(",
"x",
",",
"y",
",",
"z",
",",
"color",
"=",
"default_color",
",",
"wrapx",
"=",
"False",
",",
"wrapy",
"=",
"False",
")",
":",
"return",
"plot_mesh",
"(",
"x",
",",
"y",
",",
"z",
",",
"color",
"=",
"color",
",",
"wrap... | Draws a 2d surface in 3d, defined by the 2d ordered arrays x,y,z.
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param color: {color2d}
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points
:param bool wrapy: simular for the y coordinate
:return: :any:`Mesh` | [
"Draws",
"a",
"2d",
"surface",
"in",
"3d",
"defined",
"by",
"the",
"2d",
"ordered",
"arrays",
"x",
"y",
"z",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L354-L365 |
225,840 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | plot_wireframe | def plot_wireframe(x, y, z, color=default_color, wrapx=False, wrapy=False):
"""Draws a 2d wireframe in 3d, defines by the 2d ordered arrays x,y,z.
See also :any:`ipyvolume.pylab.plot_mesh`
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param color: {color2d}
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the begin and end points
:param bool wrapy: idem for y
:return: :any:`Mesh`
"""
return plot_mesh(x, y, z, color=color, wrapx=wrapx, wrapy=wrapy, wireframe=True, surface=False) | python | def plot_wireframe(x, y, z, color=default_color, wrapx=False, wrapy=False):
"""Draws a 2d wireframe in 3d, defines by the 2d ordered arrays x,y,z.
See also :any:`ipyvolume.pylab.plot_mesh`
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param color: {color2d}
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the begin and end points
:param bool wrapy: idem for y
:return: :any:`Mesh`
"""
return plot_mesh(x, y, z, color=color, wrapx=wrapx, wrapy=wrapy, wireframe=True, surface=False) | [
"def",
"plot_wireframe",
"(",
"x",
",",
"y",
",",
"z",
",",
"color",
"=",
"default_color",
",",
"wrapx",
"=",
"False",
",",
"wrapy",
"=",
"False",
")",
":",
"return",
"plot_mesh",
"(",
"x",
",",
"y",
",",
"z",
",",
"color",
"=",
"color",
",",
"wr... | Draws a 2d wireframe in 3d, defines by the 2d ordered arrays x,y,z.
See also :any:`ipyvolume.pylab.plot_mesh`
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param color: {color2d}
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the begin and end points
:param bool wrapy: idem for y
:return: :any:`Mesh` | [
"Draws",
"a",
"2d",
"wireframe",
"in",
"3d",
"defines",
"by",
"the",
"2d",
"ordered",
"arrays",
"x",
"y",
"z",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L369-L382 |
225,841 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | plot | def plot(x, y, z, color=default_color, **kwargs):
"""Plot a line in 3d.
:param x: {x}
:param y: {y}
:param z: {z}
:param color: {color}
:param kwargs: extra arguments passed to the Scatter constructor
:return: :any:`Scatter`
"""
fig = gcf()
_grow_limits(x, y, z)
defaults = dict(
visible_lines=True, color_selected=None, size_selected=1, size=1, connected=True, visible_markers=False
)
kwargs = dict(defaults, **kwargs)
s = ipv.Scatter(x=x, y=y, z=z, color=color, **kwargs)
s.material.visible = False
fig.scatters = fig.scatters + [s]
return s | python | def plot(x, y, z, color=default_color, **kwargs):
"""Plot a line in 3d.
:param x: {x}
:param y: {y}
:param z: {z}
:param color: {color}
:param kwargs: extra arguments passed to the Scatter constructor
:return: :any:`Scatter`
"""
fig = gcf()
_grow_limits(x, y, z)
defaults = dict(
visible_lines=True, color_selected=None, size_selected=1, size=1, connected=True, visible_markers=False
)
kwargs = dict(defaults, **kwargs)
s = ipv.Scatter(x=x, y=y, z=z, color=color, **kwargs)
s.material.visible = False
fig.scatters = fig.scatters + [s]
return s | [
"def",
"plot",
"(",
"x",
",",
"y",
",",
"z",
",",
"color",
"=",
"default_color",
",",
"*",
"*",
"kwargs",
")",
":",
"fig",
"=",
"gcf",
"(",
")",
"_grow_limits",
"(",
"x",
",",
"y",
",",
"z",
")",
"defaults",
"=",
"dict",
"(",
"visible_lines",
"... | Plot a line in 3d.
:param x: {x}
:param y: {y}
:param z: {z}
:param color: {color}
:param kwargs: extra arguments passed to the Scatter constructor
:return: :any:`Scatter` | [
"Plot",
"a",
"line",
"in",
"3d",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L480-L499 |
225,842 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | quiver | def quiver(
x,
y,
z,
u,
v,
w,
size=default_size * 10,
size_selected=default_size_selected * 10,
color=default_color,
color_selected=default_color_selected,
marker="arrow",
**kwargs
):
"""Create a quiver plot, which is like a scatter plot but with arrows pointing in the direction given by u, v and w.
:param x: {x}
:param y: {y}
:param z: {z}
:param u: {u_dir}
:param v: {v_dir}
:param w: {w_dir}
:param size: {size}
:param size_selected: like size, but for selected glyphs
:param color: {color}
:param color_selected: like color, but for selected glyphs
:param marker: (currently only 'arrow' would make sense)
:param kwargs: extra arguments passed on to the Scatter constructor
:return: :any:`Scatter`
"""
fig = gcf()
_grow_limits(x, y, z)
if 'vx' in kwargs or 'vy' in kwargs or 'vz' in kwargs:
raise KeyError('Please use u, v, w instead of vx, vy, vz')
s = ipv.Scatter(
x=x,
y=y,
z=z,
vx=u,
vy=v,
vz=w,
color=color,
size=size,
color_selected=color_selected,
size_selected=size_selected,
geo=marker,
**kwargs
)
fig.scatters = fig.scatters + [s]
return s | python | def quiver(
x,
y,
z,
u,
v,
w,
size=default_size * 10,
size_selected=default_size_selected * 10,
color=default_color,
color_selected=default_color_selected,
marker="arrow",
**kwargs
):
"""Create a quiver plot, which is like a scatter plot but with arrows pointing in the direction given by u, v and w.
:param x: {x}
:param y: {y}
:param z: {z}
:param u: {u_dir}
:param v: {v_dir}
:param w: {w_dir}
:param size: {size}
:param size_selected: like size, but for selected glyphs
:param color: {color}
:param color_selected: like color, but for selected glyphs
:param marker: (currently only 'arrow' would make sense)
:param kwargs: extra arguments passed on to the Scatter constructor
:return: :any:`Scatter`
"""
fig = gcf()
_grow_limits(x, y, z)
if 'vx' in kwargs or 'vy' in kwargs or 'vz' in kwargs:
raise KeyError('Please use u, v, w instead of vx, vy, vz')
s = ipv.Scatter(
x=x,
y=y,
z=z,
vx=u,
vy=v,
vz=w,
color=color,
size=size,
color_selected=color_selected,
size_selected=size_selected,
geo=marker,
**kwargs
)
fig.scatters = fig.scatters + [s]
return s | [
"def",
"quiver",
"(",
"x",
",",
"y",
",",
"z",
",",
"u",
",",
"v",
",",
"w",
",",
"size",
"=",
"default_size",
"*",
"10",
",",
"size_selected",
"=",
"default_size_selected",
"*",
"10",
",",
"color",
"=",
"default_color",
",",
"color_selected",
"=",
"... | Create a quiver plot, which is like a scatter plot but with arrows pointing in the direction given by u, v and w.
:param x: {x}
:param y: {y}
:param z: {z}
:param u: {u_dir}
:param v: {v_dir}
:param w: {w_dir}
:param size: {size}
:param size_selected: like size, but for selected glyphs
:param color: {color}
:param color_selected: like color, but for selected glyphs
:param marker: (currently only 'arrow' would make sense)
:param kwargs: extra arguments passed on to the Scatter constructor
:return: :any:`Scatter` | [
"Create",
"a",
"quiver",
"plot",
"which",
"is",
"like",
"a",
"scatter",
"plot",
"but",
"with",
"arrows",
"pointing",
"in",
"the",
"direction",
"given",
"by",
"u",
"v",
"and",
"w",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L551-L600 |
225,843 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | animation_control | def animation_control(object, sequence_length=None, add=True, interval=200):
"""Animate scatter, quiver or mesh by adding a slider and play button.
:param object: :any:`Scatter` or :any:`Mesh` object (having an sequence_index property), or a list of these to
control multiple.
:param sequence_length: If sequence_length is None we try try our best to figure out, in case we do it badly,
you can tell us what it should be. Should be equal to the S in the shape of the numpy arrays as for instance
documented in :any:`scatter` or :any:`plot_mesh`.
:param add: if True, add the widgets to the container, else return a HBox with the slider and play button. Useful when you
want to customise the layout of the widgets yourself.
:param interval: interval in msec between each frame
:return: If add is False, if returns the ipywidgets.HBox object containing the controls
"""
if isinstance(object, (list, tuple)):
objects = object
else:
objects = [object]
del object
if sequence_length is None:
# get all non-None arrays
sequence_lengths = []
for object in objects:
sequence_lengths_previous = list(sequence_lengths)
values = [getattr(object, name) for name in "x y z vx vy vz".split() if hasattr(object, name)]
values = [k for k in values if k is not None]
# sort them such that the higest dim is first
values.sort(key=lambda key: -len(key.shape))
try:
sequence_length = values[0].shape[0] # assume this defines the sequence length
if isinstance(object, ipv.Mesh): # for a mesh, it does not make sense to have less than 1 dimension
if len(values[0].shape) >= 2: # if just 1d, it is most likely not an animation
sequence_lengths.append(sequence_length)
else:
sequence_lengths.append(sequence_length)
except IndexError: # scalars get ignored
pass
if hasattr(object, 'color'):
color = object.color
if color is not None:
shape = color.shape
if len(shape) == 3: # would be the case for for (frame, point_index, color_index)
sequence_lengths.append(shape[0])
# TODO: maybe support arrays of string type of form (frame, point_index)
if len(sequence_lengths) == len(sequence_lengths_previous):
raise ValueError('no frame dimension found for object: {}'.format(object))
sequence_length = max(sequence_lengths)
fig = gcf()
fig.animation = interval
fig.animation_exponent = 1.0
play = ipywidgets.Play(min=0, max=sequence_length - 1, interval=interval, value=0, step=1)
slider = ipywidgets.FloatSlider(min=0, max=play.max, step=1)
ipywidgets.jslink((play, 'value'), (slider, 'value'))
for object in objects:
ipywidgets.jslink((slider, 'value'), (object, 'sequence_index'))
control = ipywidgets.HBox([play, slider])
if add:
current.container.children += (control,)
else:
return control | python | def animation_control(object, sequence_length=None, add=True, interval=200):
"""Animate scatter, quiver or mesh by adding a slider and play button.
:param object: :any:`Scatter` or :any:`Mesh` object (having an sequence_index property), or a list of these to
control multiple.
:param sequence_length: If sequence_length is None we try try our best to figure out, in case we do it badly,
you can tell us what it should be. Should be equal to the S in the shape of the numpy arrays as for instance
documented in :any:`scatter` or :any:`plot_mesh`.
:param add: if True, add the widgets to the container, else return a HBox with the slider and play button. Useful when you
want to customise the layout of the widgets yourself.
:param interval: interval in msec between each frame
:return: If add is False, if returns the ipywidgets.HBox object containing the controls
"""
if isinstance(object, (list, tuple)):
objects = object
else:
objects = [object]
del object
if sequence_length is None:
# get all non-None arrays
sequence_lengths = []
for object in objects:
sequence_lengths_previous = list(sequence_lengths)
values = [getattr(object, name) for name in "x y z vx vy vz".split() if hasattr(object, name)]
values = [k for k in values if k is not None]
# sort them such that the higest dim is first
values.sort(key=lambda key: -len(key.shape))
try:
sequence_length = values[0].shape[0] # assume this defines the sequence length
if isinstance(object, ipv.Mesh): # for a mesh, it does not make sense to have less than 1 dimension
if len(values[0].shape) >= 2: # if just 1d, it is most likely not an animation
sequence_lengths.append(sequence_length)
else:
sequence_lengths.append(sequence_length)
except IndexError: # scalars get ignored
pass
if hasattr(object, 'color'):
color = object.color
if color is not None:
shape = color.shape
if len(shape) == 3: # would be the case for for (frame, point_index, color_index)
sequence_lengths.append(shape[0])
# TODO: maybe support arrays of string type of form (frame, point_index)
if len(sequence_lengths) == len(sequence_lengths_previous):
raise ValueError('no frame dimension found for object: {}'.format(object))
sequence_length = max(sequence_lengths)
fig = gcf()
fig.animation = interval
fig.animation_exponent = 1.0
play = ipywidgets.Play(min=0, max=sequence_length - 1, interval=interval, value=0, step=1)
slider = ipywidgets.FloatSlider(min=0, max=play.max, step=1)
ipywidgets.jslink((play, 'value'), (slider, 'value'))
for object in objects:
ipywidgets.jslink((slider, 'value'), (object, 'sequence_index'))
control = ipywidgets.HBox([play, slider])
if add:
current.container.children += (control,)
else:
return control | [
"def",
"animation_control",
"(",
"object",
",",
"sequence_length",
"=",
"None",
",",
"add",
"=",
"True",
",",
"interval",
"=",
"200",
")",
":",
"if",
"isinstance",
"(",
"object",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"objects",
"=",
"object",
... | Animate scatter, quiver or mesh by adding a slider and play button.
:param object: :any:`Scatter` or :any:`Mesh` object (having an sequence_index property), or a list of these to
control multiple.
:param sequence_length: If sequence_length is None we try try our best to figure out, in case we do it badly,
you can tell us what it should be. Should be equal to the S in the shape of the numpy arrays as for instance
documented in :any:`scatter` or :any:`plot_mesh`.
:param add: if True, add the widgets to the container, else return a HBox with the slider and play button. Useful when you
want to customise the layout of the widgets yourself.
:param interval: interval in msec between each frame
:return: If add is False, if returns the ipywidgets.HBox object containing the controls | [
"Animate",
"scatter",
"quiver",
"or",
"mesh",
"by",
"adding",
"a",
"slider",
"and",
"play",
"button",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L617-L675 |
225,844 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | transfer_function | def transfer_function(
level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1, controls=True, max_opacity=0.2
):
"""Create a transfer function, see volshow."""
tf_kwargs = {}
# level, opacity and widths can be scalars
try:
level[0]
except:
level = [level]
try:
opacity[0]
except:
opacity = [opacity] * 3
try:
level_width[0]
except:
level_width = [level_width] * 3
# clip off lists
min_length = min(len(level), len(level_width), len(opacity))
level = list(level[:min_length])
opacity = list(opacity[:min_length])
level_width = list(level_width[:min_length])
# append with zeros
while len(level) < 3:
level.append(0)
while len(opacity) < 3:
opacity.append(0)
while len(level_width) < 3:
level_width.append(0)
for i in range(1, 4):
tf_kwargs["level" + str(i)] = level[i - 1]
tf_kwargs["opacity" + str(i)] = opacity[i - 1]
tf_kwargs["width" + str(i)] = level_width[i - 1]
tf = ipv.TransferFunctionWidgetJs3(**tf_kwargs)
gcf() # make sure a current container/figure exists
if controls:
current.container.children = (tf.control(max_opacity=max_opacity),) + current.container.children
return tf | python | def transfer_function(
level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1, controls=True, max_opacity=0.2
):
"""Create a transfer function, see volshow."""
tf_kwargs = {}
# level, opacity and widths can be scalars
try:
level[0]
except:
level = [level]
try:
opacity[0]
except:
opacity = [opacity] * 3
try:
level_width[0]
except:
level_width = [level_width] * 3
# clip off lists
min_length = min(len(level), len(level_width), len(opacity))
level = list(level[:min_length])
opacity = list(opacity[:min_length])
level_width = list(level_width[:min_length])
# append with zeros
while len(level) < 3:
level.append(0)
while len(opacity) < 3:
opacity.append(0)
while len(level_width) < 3:
level_width.append(0)
for i in range(1, 4):
tf_kwargs["level" + str(i)] = level[i - 1]
tf_kwargs["opacity" + str(i)] = opacity[i - 1]
tf_kwargs["width" + str(i)] = level_width[i - 1]
tf = ipv.TransferFunctionWidgetJs3(**tf_kwargs)
gcf() # make sure a current container/figure exists
if controls:
current.container.children = (tf.control(max_opacity=max_opacity),) + current.container.children
return tf | [
"def",
"transfer_function",
"(",
"level",
"=",
"[",
"0.1",
",",
"0.5",
",",
"0.9",
"]",
",",
"opacity",
"=",
"[",
"0.01",
",",
"0.05",
",",
"0.1",
"]",
",",
"level_width",
"=",
"0.1",
",",
"controls",
"=",
"True",
",",
"max_opacity",
"=",
"0.2",
")... | Create a transfer function, see volshow. | [
"Create",
"a",
"transfer",
"function",
"see",
"volshow",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L684-L722 |
225,845 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | save | def save(
filepath,
makedirs=True,
title=u'IPyVolume Widget',
all_states=False,
offline=False,
scripts_path='js',
drop_defaults=False,
template_options=(("extra_script_head", ""), ("body_pre", ""), ("body_post", "")),
devmode=False,
offline_cors=False,
):
"""Save the current container to a HTML file.
By default the HTML file is not standalone and requires an internet connection to fetch a few javascript
libraries. Use offline=True to download these and make the HTML file work without an internet connection.
:param str filepath: The file to write the HTML output to.
:param bool makedirs: whether to make directories in the filename path, if they do not already exist
:param str title: title for the html page
:param bool all_states: if True, the state of all widgets know to the widget manager is included, else only those in widgets
:param bool offline: if True, use local urls for required js/css packages and download all js/css required packages
(if not already available), such that the html can be viewed with no internet connection
:param str scripts_path: the folder to save required js/css packages to (relative to the filepath)
:param bool drop_defaults: Whether to drop default values from the widget states
:param template_options: list or dict of additional template options
:param bool devmode: if True, attempt to get index.js from local js/dist folder
:param bool offline_cors: if True, sets crossorigin attribute of script tags to anonymous
"""
ipyvolume.embed.embed_html(
filepath,
current.container,
makedirs=makedirs,
title=title,
all_states=all_states,
offline=offline,
scripts_path=scripts_path,
drop_defaults=drop_defaults,
template_options=template_options,
devmode=devmode,
offline_cors=offline_cors,
) | python | def save(
filepath,
makedirs=True,
title=u'IPyVolume Widget',
all_states=False,
offline=False,
scripts_path='js',
drop_defaults=False,
template_options=(("extra_script_head", ""), ("body_pre", ""), ("body_post", "")),
devmode=False,
offline_cors=False,
):
"""Save the current container to a HTML file.
By default the HTML file is not standalone and requires an internet connection to fetch a few javascript
libraries. Use offline=True to download these and make the HTML file work without an internet connection.
:param str filepath: The file to write the HTML output to.
:param bool makedirs: whether to make directories in the filename path, if they do not already exist
:param str title: title for the html page
:param bool all_states: if True, the state of all widgets know to the widget manager is included, else only those in widgets
:param bool offline: if True, use local urls for required js/css packages and download all js/css required packages
(if not already available), such that the html can be viewed with no internet connection
:param str scripts_path: the folder to save required js/css packages to (relative to the filepath)
:param bool drop_defaults: Whether to drop default values from the widget states
:param template_options: list or dict of additional template options
:param bool devmode: if True, attempt to get index.js from local js/dist folder
:param bool offline_cors: if True, sets crossorigin attribute of script tags to anonymous
"""
ipyvolume.embed.embed_html(
filepath,
current.container,
makedirs=makedirs,
title=title,
all_states=all_states,
offline=offline,
scripts_path=scripts_path,
drop_defaults=drop_defaults,
template_options=template_options,
devmode=devmode,
offline_cors=offline_cors,
) | [
"def",
"save",
"(",
"filepath",
",",
"makedirs",
"=",
"True",
",",
"title",
"=",
"u'IPyVolume Widget'",
",",
"all_states",
"=",
"False",
",",
"offline",
"=",
"False",
",",
"scripts_path",
"=",
"'js'",
",",
"drop_defaults",
"=",
"False",
",",
"template_option... | Save the current container to a HTML file.
By default the HTML file is not standalone and requires an internet connection to fetch a few javascript
libraries. Use offline=True to download these and make the HTML file work without an internet connection.
:param str filepath: The file to write the HTML output to.
:param bool makedirs: whether to make directories in the filename path, if they do not already exist
:param str title: title for the html page
:param bool all_states: if True, the state of all widgets know to the widget manager is included, else only those in widgets
:param bool offline: if True, use local urls for required js/css packages and download all js/css required packages
(if not already available), such that the html can be viewed with no internet connection
:param str scripts_path: the folder to save required js/css packages to (relative to the filepath)
:param bool drop_defaults: Whether to drop default values from the widget states
:param template_options: list or dict of additional template options
:param bool devmode: if True, attempt to get index.js from local js/dist folder
:param bool offline_cors: if True, sets crossorigin attribute of script tags to anonymous | [
"Save",
"the",
"current",
"container",
"to",
"a",
"HTML",
"file",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L888-L930 |
225,846 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | screenshot | def screenshot(
width=None,
height=None,
format="png",
fig=None,
timeout_seconds=10,
output_widget=None,
headless=False,
devmode=False,
):
"""Save the figure to a PIL.Image object.
:param int width: the width of the image in pixels
:param int height: the height of the image in pixels
:param format: format of output data (png, jpeg or svg)
:type fig: ipyvolume.widgets.Figure or None
:param fig: if None use the current figure
:type timeout_seconds: int
:param timeout_seconds: maximum time to wait for image data to return
:type output_widget: ipywidgets.Output
:param output_widget: a widget to use as a context manager for capturing the data
:param bool headless: if True, use headless chrome to take screenshot
:param bool devmode: if True, attempt to get index.js from local js/dist folder
:return: PIL.Image
"""
assert format in ['png', 'jpeg', 'svg'], "image format must be png, jpeg or svg"
data = _screenshot_data(
timeout_seconds=timeout_seconds,
output_widget=output_widget,
format=format,
width=width,
height=height,
fig=fig,
headless=headless,
devmode=devmode,
)
f = StringIO(data)
return PIL.Image.open(f) | python | def screenshot(
width=None,
height=None,
format="png",
fig=None,
timeout_seconds=10,
output_widget=None,
headless=False,
devmode=False,
):
"""Save the figure to a PIL.Image object.
:param int width: the width of the image in pixels
:param int height: the height of the image in pixels
:param format: format of output data (png, jpeg or svg)
:type fig: ipyvolume.widgets.Figure or None
:param fig: if None use the current figure
:type timeout_seconds: int
:param timeout_seconds: maximum time to wait for image data to return
:type output_widget: ipywidgets.Output
:param output_widget: a widget to use as a context manager for capturing the data
:param bool headless: if True, use headless chrome to take screenshot
:param bool devmode: if True, attempt to get index.js from local js/dist folder
:return: PIL.Image
"""
assert format in ['png', 'jpeg', 'svg'], "image format must be png, jpeg or svg"
data = _screenshot_data(
timeout_seconds=timeout_seconds,
output_widget=output_widget,
format=format,
width=width,
height=height,
fig=fig,
headless=headless,
devmode=devmode,
)
f = StringIO(data)
return PIL.Image.open(f) | [
"def",
"screenshot",
"(",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"format",
"=",
"\"png\"",
",",
"fig",
"=",
"None",
",",
"timeout_seconds",
"=",
"10",
",",
"output_widget",
"=",
"None",
",",
"headless",
"=",
"False",
",",
"devmode",
"="... | Save the figure to a PIL.Image object.
:param int width: the width of the image in pixels
:param int height: the height of the image in pixels
:param format: format of output data (png, jpeg or svg)
:type fig: ipyvolume.widgets.Figure or None
:param fig: if None use the current figure
:type timeout_seconds: int
:param timeout_seconds: maximum time to wait for image data to return
:type output_widget: ipywidgets.Output
:param output_widget: a widget to use as a context manager for capturing the data
:param bool headless: if True, use headless chrome to take screenshot
:param bool devmode: if True, attempt to get index.js from local js/dist folder
:return: PIL.Image | [
"Save",
"the",
"figure",
"to",
"a",
"PIL",
".",
"Image",
"object",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L1059-L1097 |
225,847 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | savefig | def savefig(
filename, width=None, height=None, fig=None, timeout_seconds=10, output_widget=None, headless=False, devmode=False
):
"""Save the figure to an image file.
:param str filename: must have extension .png, .jpeg or .svg
:param int width: the width of the image in pixels
:param int height: the height of the image in pixels
:type fig: ipyvolume.widgets.Figure or None
:param fig: if None use the current figure
:param float timeout_seconds: maximum time to wait for image data to return
:param ipywidgets.Output output_widget: a widget to use as a context manager for capturing the data
:param bool headless: if True, use headless chrome to save figure
:param bool devmode: if True, attempt to get index.js from local js/dist folder
"""
__, ext = os.path.splitext(filename)
format = ext[1:]
assert format in ['png', 'jpeg', 'svg'], "image format must be png, jpeg or svg"
with open(filename, "wb") as f:
f.write(
_screenshot_data(
timeout_seconds=timeout_seconds,
output_widget=output_widget,
format=format,
width=width,
height=height,
fig=fig,
headless=headless,
devmode=devmode,
)
) | python | def savefig(
filename, width=None, height=None, fig=None, timeout_seconds=10, output_widget=None, headless=False, devmode=False
):
"""Save the figure to an image file.
:param str filename: must have extension .png, .jpeg or .svg
:param int width: the width of the image in pixels
:param int height: the height of the image in pixels
:type fig: ipyvolume.widgets.Figure or None
:param fig: if None use the current figure
:param float timeout_seconds: maximum time to wait for image data to return
:param ipywidgets.Output output_widget: a widget to use as a context manager for capturing the data
:param bool headless: if True, use headless chrome to save figure
:param bool devmode: if True, attempt to get index.js from local js/dist folder
"""
__, ext = os.path.splitext(filename)
format = ext[1:]
assert format in ['png', 'jpeg', 'svg'], "image format must be png, jpeg or svg"
with open(filename, "wb") as f:
f.write(
_screenshot_data(
timeout_seconds=timeout_seconds,
output_widget=output_widget,
format=format,
width=width,
height=height,
fig=fig,
headless=headless,
devmode=devmode,
)
) | [
"def",
"savefig",
"(",
"filename",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"fig",
"=",
"None",
",",
"timeout_seconds",
"=",
"10",
",",
"output_widget",
"=",
"None",
",",
"headless",
"=",
"False",
",",
"devmode",
"=",
"False",
")",
... | Save the figure to an image file.
:param str filename: must have extension .png, .jpeg or .svg
:param int width: the width of the image in pixels
:param int height: the height of the image in pixels
:type fig: ipyvolume.widgets.Figure or None
:param fig: if None use the current figure
:param float timeout_seconds: maximum time to wait for image data to return
:param ipywidgets.Output output_widget: a widget to use as a context manager for capturing the data
:param bool headless: if True, use headless chrome to save figure
:param bool devmode: if True, attempt to get index.js from local js/dist folder | [
"Save",
"the",
"figure",
"to",
"an",
"image",
"file",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L1100-L1130 |
225,848 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | xyzlabel | def xyzlabel(labelx, labely, labelz):
"""Set all labels at once."""
xlabel(labelx)
ylabel(labely)
zlabel(labelz) | python | def xyzlabel(labelx, labely, labelz):
"""Set all labels at once."""
xlabel(labelx)
ylabel(labely)
zlabel(labelz) | [
"def",
"xyzlabel",
"(",
"labelx",
",",
"labely",
",",
"labelz",
")",
":",
"xlabel",
"(",
"labelx",
")",
"ylabel",
"(",
"labely",
")",
"zlabel",
"(",
"labelz",
")"
] | Set all labels at once. | [
"Set",
"all",
"labels",
"at",
"once",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L1151-L1155 |
225,849 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | view | def view(azimuth=None, elevation=None, distance=None):
"""Set camera angles and distance and return the current.
:param float azimuth: rotation around the axis pointing up in degrees
:param float elevation: rotation where +90 means 'up', -90 means 'down', in degrees
:param float distance: radial distance from the center to the camera.
"""
fig = gcf()
# first calculate the current values
x, y, z = fig.camera.position
r = np.sqrt(x ** 2 + y ** 2 + z ** 2)
az = np.degrees(np.arctan2(x, z))
el = np.degrees(np.arcsin(y / r))
if azimuth is None:
azimuth = az
if elevation is None:
elevation = el
if distance is None:
distance = r
cosaz = np.cos(np.radians(azimuth))
sinaz = np.sin(np.radians(azimuth))
sine = np.sin(np.radians(elevation))
cose = np.cos(np.radians(elevation))
fig.camera.position = (distance * sinaz * cose, distance * sine, distance * cosaz * cose)
return azimuth, elevation, distance | python | def view(azimuth=None, elevation=None, distance=None):
"""Set camera angles and distance and return the current.
:param float azimuth: rotation around the axis pointing up in degrees
:param float elevation: rotation where +90 means 'up', -90 means 'down', in degrees
:param float distance: radial distance from the center to the camera.
"""
fig = gcf()
# first calculate the current values
x, y, z = fig.camera.position
r = np.sqrt(x ** 2 + y ** 2 + z ** 2)
az = np.degrees(np.arctan2(x, z))
el = np.degrees(np.arcsin(y / r))
if azimuth is None:
azimuth = az
if elevation is None:
elevation = el
if distance is None:
distance = r
cosaz = np.cos(np.radians(azimuth))
sinaz = np.sin(np.radians(azimuth))
sine = np.sin(np.radians(elevation))
cose = np.cos(np.radians(elevation))
fig.camera.position = (distance * sinaz * cose, distance * sine, distance * cosaz * cose)
return azimuth, elevation, distance | [
"def",
"view",
"(",
"azimuth",
"=",
"None",
",",
"elevation",
"=",
"None",
",",
"distance",
"=",
"None",
")",
":",
"fig",
"=",
"gcf",
"(",
")",
"# first calculate the current values",
"x",
",",
"y",
",",
"z",
"=",
"fig",
".",
"camera",
".",
"position",... | Set camera angles and distance and return the current.
:param float azimuth: rotation around the axis pointing up in degrees
:param float elevation: rotation where +90 means 'up', -90 means 'down', in degrees
:param float distance: radial distance from the center to the camera. | [
"Set",
"camera",
"angles",
"and",
"distance",
"and",
"return",
"the",
"current",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L1158-L1182 |
225,850 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | plot_plane | def plot_plane(where="back", texture=None):
"""Plot a plane at a particular location in the viewbox.
:param str where: 'back', 'front', 'left', 'right', 'top', 'bottom'
:param texture: {texture}
:return: :any:`Mesh`
"""
fig = gcf()
xmin, xmax = fig.xlim
ymin, ymax = fig.ylim
zmin, zmax = fig.zlim
if where == "back":
x = [xmin, xmax, xmax, xmin]
y = [ymin, ymin, ymax, ymax]
z = [zmin, zmin, zmin, zmin]
if where == "front":
x = [xmin, xmax, xmax, xmin][::-1]
y = [ymin, ymin, ymax, ymax]
z = [zmax, zmax, zmax, zmax]
if where == "left":
x = [xmin, xmin, xmin, xmin]
y = [ymin, ymin, ymax, ymax]
z = [zmin, zmax, zmax, zmin]
if where == "right":
x = [xmax, xmax, xmax, xmax]
y = [ymin, ymin, ymax, ymax]
z = [zmin, zmax, zmax, zmin][::-1]
if where == "top":
x = [xmin, xmax, xmax, xmin]
y = [ymax, ymax, ymax, ymax]
z = [zmax, zmax, zmin, zmin]
if where == "bottom":
x = [xmax, xmin, xmin, xmax]
y = [ymin, ymin, ymin, ymin]
z = [zmin, zmin, zmax, zmax]
triangles = [(0, 1, 2), (0, 2, 3)]
u = v = None
if texture is not None:
u = [0.0, 1.0, 1.0, 0.0]
v = [0.0, 0.0, 1.0, 1.0]
mesh = plot_trisurf(x, y, z, triangles, texture=texture, u=u, v=v)
return mesh | python | def plot_plane(where="back", texture=None):
"""Plot a plane at a particular location in the viewbox.
:param str where: 'back', 'front', 'left', 'right', 'top', 'bottom'
:param texture: {texture}
:return: :any:`Mesh`
"""
fig = gcf()
xmin, xmax = fig.xlim
ymin, ymax = fig.ylim
zmin, zmax = fig.zlim
if where == "back":
x = [xmin, xmax, xmax, xmin]
y = [ymin, ymin, ymax, ymax]
z = [zmin, zmin, zmin, zmin]
if where == "front":
x = [xmin, xmax, xmax, xmin][::-1]
y = [ymin, ymin, ymax, ymax]
z = [zmax, zmax, zmax, zmax]
if where == "left":
x = [xmin, xmin, xmin, xmin]
y = [ymin, ymin, ymax, ymax]
z = [zmin, zmax, zmax, zmin]
if where == "right":
x = [xmax, xmax, xmax, xmax]
y = [ymin, ymin, ymax, ymax]
z = [zmin, zmax, zmax, zmin][::-1]
if where == "top":
x = [xmin, xmax, xmax, xmin]
y = [ymax, ymax, ymax, ymax]
z = [zmax, zmax, zmin, zmin]
if where == "bottom":
x = [xmax, xmin, xmin, xmax]
y = [ymin, ymin, ymin, ymin]
z = [zmin, zmin, zmax, zmax]
triangles = [(0, 1, 2), (0, 2, 3)]
u = v = None
if texture is not None:
u = [0.0, 1.0, 1.0, 0.0]
v = [0.0, 0.0, 1.0, 1.0]
mesh = plot_trisurf(x, y, z, triangles, texture=texture, u=u, v=v)
return mesh | [
"def",
"plot_plane",
"(",
"where",
"=",
"\"back\"",
",",
"texture",
"=",
"None",
")",
":",
"fig",
"=",
"gcf",
"(",
")",
"xmin",
",",
"xmax",
"=",
"fig",
".",
"xlim",
"ymin",
",",
"ymax",
"=",
"fig",
".",
"ylim",
"zmin",
",",
"zmax",
"=",
"fig",
... | Plot a plane at a particular location in the viewbox.
:param str where: 'back', 'front', 'left', 'right', 'top', 'bottom'
:param texture: {texture}
:return: :any:`Mesh` | [
"Plot",
"a",
"plane",
"at",
"a",
"particular",
"location",
"in",
"the",
"viewbox",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L1306-L1347 |
225,851 | maartenbreddels/ipyvolume | ipyvolume/pylab.py | _make_triangles_lines | def _make_triangles_lines(shape, wrapx=False, wrapy=False):
"""Transform rectangular regular grid into triangles.
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points
:param bool wrapy: simular for the y coordinate
:return: triangles and lines used to plot Mesh
"""
nx, ny = shape
mx = nx if wrapx else nx - 1
my = ny if wrapy else ny - 1
"""
create all pair of indices (i,j) of the rectangular grid
minus last row if wrapx = False => mx
minus last column if wrapy = False => my
| (0,0) ... (0,j) ... (0,my-1) |
| . . . . . |
| (i,0) ... (i,j) ... (i,my-1) |
| . . . . . |
|(mx-1,0) ... (mx-1,j) ... (mx-1,my-1) |
"""
i, j = np.mgrid[0:mx, 0:my]
"""
collapsed i and j in one dimensional array, row-major order
ex :
array([[0, 1, 2], => array([0, 1, 2, 3, *4*, 5])
[3, *4*, 5]])
if we want vertex 4 at (i=1,j=1) we must transform it in i*ny+j = 4
"""
i, j = np.ravel(i), np.ravel(j)
"""
Let's go for the triangles :
(i,j) - (i,j+1) -> y dir
(i+1,j) - (i+1,j+1)
|
v
x dir
in flatten coordinates:
i*ny+j - i*ny+j+1
(i+1)*ny+j - (i+1)*ny+j+1
"""
t1 = (i * ny + j, (i + 1) % nx * ny + j, (i + 1) % nx * ny + (j + 1) % ny)
t2 = (i * ny + j, (i + 1) % nx * ny + (j + 1) % ny, i * ny + (j + 1) % ny)
"""
%nx and %ny are used for wrapx and wrapy :
if (i+1)=nx => (i+1)%nx=0 => close mesh in x direction
if (j+1)=ny => (j+1)%ny=0 => close mesh in y direction
"""
nt = len(t1[0])
triangles = np.zeros((nt * 2, 3), dtype=np.uint32)
triangles[0::2, 0], triangles[0::2, 1], triangles[0::2, 2] = t1
triangles[1::2, 0], triangles[1::2, 1], triangles[1::2, 2] = t2
lines = np.zeros((nt * 4, 2), dtype=np.uint32)
lines[::4, 0], lines[::4, 1] = t1[:2]
lines[1::4, 0], lines[1::4, 1] = t1[0], t2[2]
lines[2::4, 0], lines[2::4, 1] = t2[2:0:-1]
lines[3::4, 0], lines[3::4, 1] = t1[1], t2[1]
return triangles, lines | python | def _make_triangles_lines(shape, wrapx=False, wrapy=False):
"""Transform rectangular regular grid into triangles.
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points
:param bool wrapy: simular for the y coordinate
:return: triangles and lines used to plot Mesh
"""
nx, ny = shape
mx = nx if wrapx else nx - 1
my = ny if wrapy else ny - 1
"""
create all pair of indices (i,j) of the rectangular grid
minus last row if wrapx = False => mx
minus last column if wrapy = False => my
| (0,0) ... (0,j) ... (0,my-1) |
| . . . . . |
| (i,0) ... (i,j) ... (i,my-1) |
| . . . . . |
|(mx-1,0) ... (mx-1,j) ... (mx-1,my-1) |
"""
i, j = np.mgrid[0:mx, 0:my]
"""
collapsed i and j in one dimensional array, row-major order
ex :
array([[0, 1, 2], => array([0, 1, 2, 3, *4*, 5])
[3, *4*, 5]])
if we want vertex 4 at (i=1,j=1) we must transform it in i*ny+j = 4
"""
i, j = np.ravel(i), np.ravel(j)
"""
Let's go for the triangles :
(i,j) - (i,j+1) -> y dir
(i+1,j) - (i+1,j+1)
|
v
x dir
in flatten coordinates:
i*ny+j - i*ny+j+1
(i+1)*ny+j - (i+1)*ny+j+1
"""
t1 = (i * ny + j, (i + 1) % nx * ny + j, (i + 1) % nx * ny + (j + 1) % ny)
t2 = (i * ny + j, (i + 1) % nx * ny + (j + 1) % ny, i * ny + (j + 1) % ny)
"""
%nx and %ny are used for wrapx and wrapy :
if (i+1)=nx => (i+1)%nx=0 => close mesh in x direction
if (j+1)=ny => (j+1)%ny=0 => close mesh in y direction
"""
nt = len(t1[0])
triangles = np.zeros((nt * 2, 3), dtype=np.uint32)
triangles[0::2, 0], triangles[0::2, 1], triangles[0::2, 2] = t1
triangles[1::2, 0], triangles[1::2, 1], triangles[1::2, 2] = t2
lines = np.zeros((nt * 4, 2), dtype=np.uint32)
lines[::4, 0], lines[::4, 1] = t1[:2]
lines[1::4, 0], lines[1::4, 1] = t1[0], t2[2]
lines[2::4, 0], lines[2::4, 1] = t2[2:0:-1]
lines[3::4, 0], lines[3::4, 1] = t1[1], t2[1]
return triangles, lines | [
"def",
"_make_triangles_lines",
"(",
"shape",
",",
"wrapx",
"=",
"False",
",",
"wrapy",
"=",
"False",
")",
":",
"nx",
",",
"ny",
"=",
"shape",
"mx",
"=",
"nx",
"if",
"wrapx",
"else",
"nx",
"-",
"1",
"my",
"=",
"ny",
"if",
"wrapy",
"else",
"ny",
"... | Transform rectangular regular grid into triangles.
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points
:param bool wrapy: simular for the y coordinate
:return: triangles and lines used to plot Mesh | [
"Transform",
"rectangular",
"regular",
"grid",
"into",
"triangles",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L1443-L1513 |
225,852 | maartenbreddels/ipyvolume | ipyvolume/embed.py | save_ipyvolumejs | def save_ipyvolumejs(
target="", devmode=False, version=ipyvolume._version.__version_js__, version3js=__version_threejs__
):
"""Output the ipyvolume javascript to a local file.
:type target: str
:param bool devmode: if True get index.js from js/dist directory
:param str version: version number of ipyvolume
:param str version3js: version number of threejs
"""
url = "https://unpkg.com/ipyvolume@{version}/dist/index.js".format(version=version)
pyv_filename = 'ipyvolume_v{version}.js'.format(version=version)
pyv_filepath = os.path.join(target, pyv_filename)
devfile = os.path.join(os.path.abspath(ipyvolume.__path__[0]), "..", "js", "dist", "index.js")
if devmode:
if not os.path.exists(devfile):
raise IOError('devmode=True but cannot find : {}'.format(devfile))
if target and not os.path.exists(target):
os.makedirs(target)
shutil.copy(devfile, pyv_filepath)
else:
download_to_file(url, pyv_filepath)
# TODO: currently not in use, think about this if we want to have this external for embedding,
# see also https://github.com/jovyan/pythreejs/issues/109
# three_filename = 'three_v{version}.js'.format(version=__version_threejs__)
# three_filepath = os.path.join(target, three_filename)
# threejs = os.path.join(os.path.abspath(ipyvolume.__path__[0]), "static", "three.js")
# shutil.copy(threejs, three_filepath)
return pyv_filename | python | def save_ipyvolumejs(
target="", devmode=False, version=ipyvolume._version.__version_js__, version3js=__version_threejs__
):
"""Output the ipyvolume javascript to a local file.
:type target: str
:param bool devmode: if True get index.js from js/dist directory
:param str version: version number of ipyvolume
:param str version3js: version number of threejs
"""
url = "https://unpkg.com/ipyvolume@{version}/dist/index.js".format(version=version)
pyv_filename = 'ipyvolume_v{version}.js'.format(version=version)
pyv_filepath = os.path.join(target, pyv_filename)
devfile = os.path.join(os.path.abspath(ipyvolume.__path__[0]), "..", "js", "dist", "index.js")
if devmode:
if not os.path.exists(devfile):
raise IOError('devmode=True but cannot find : {}'.format(devfile))
if target and not os.path.exists(target):
os.makedirs(target)
shutil.copy(devfile, pyv_filepath)
else:
download_to_file(url, pyv_filepath)
# TODO: currently not in use, think about this if we want to have this external for embedding,
# see also https://github.com/jovyan/pythreejs/issues/109
# three_filename = 'three_v{version}.js'.format(version=__version_threejs__)
# three_filepath = os.path.join(target, three_filename)
# threejs = os.path.join(os.path.abspath(ipyvolume.__path__[0]), "static", "three.js")
# shutil.copy(threejs, three_filepath)
return pyv_filename | [
"def",
"save_ipyvolumejs",
"(",
"target",
"=",
"\"\"",
",",
"devmode",
"=",
"False",
",",
"version",
"=",
"ipyvolume",
".",
"_version",
".",
"__version_js__",
",",
"version3js",
"=",
"__version_threejs__",
")",
":",
"url",
"=",
"\"https://unpkg.com/ipyvolume@{vers... | Output the ipyvolume javascript to a local file.
:type target: str
:param bool devmode: if True get index.js from js/dist directory
:param str version: version number of ipyvolume
:param str version3js: version number of threejs | [
"Output",
"the",
"ipyvolume",
"javascript",
"to",
"a",
"local",
"file",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/embed.py#L28-L60 |
225,853 | maartenbreddels/ipyvolume | ipyvolume/embed.py | save_requirejs | def save_requirejs(target="", version="2.3.4"):
"""Download and save the require javascript to a local file.
:type target: str
:type version: str
"""
url = "https://cdnjs.cloudflare.com/ajax/libs/require.js/{version}/require.min.js".format(version=version)
filename = "require.min.v{0}.js".format(version)
filepath = os.path.join(target, filename)
download_to_file(url, filepath)
return filename | python | def save_requirejs(target="", version="2.3.4"):
"""Download and save the require javascript to a local file.
:type target: str
:type version: str
"""
url = "https://cdnjs.cloudflare.com/ajax/libs/require.js/{version}/require.min.js".format(version=version)
filename = "require.min.v{0}.js".format(version)
filepath = os.path.join(target, filename)
download_to_file(url, filepath)
return filename | [
"def",
"save_requirejs",
"(",
"target",
"=",
"\"\"",
",",
"version",
"=",
"\"2.3.4\"",
")",
":",
"url",
"=",
"\"https://cdnjs.cloudflare.com/ajax/libs/require.js/{version}/require.min.js\"",
".",
"format",
"(",
"version",
"=",
"version",
")",
"filename",
"=",
"\"requi... | Download and save the require javascript to a local file.
:type target: str
:type version: str | [
"Download",
"and",
"save",
"the",
"require",
"javascript",
"to",
"a",
"local",
"file",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/embed.py#L63-L73 |
225,854 | maartenbreddels/ipyvolume | ipyvolume/embed.py | save_embed_js | def save_embed_js(target="", version=wembed.__html_manager_version__):
"""Download and save the ipywidgets embedding javascript to a local file.
:type target: str
:type version: str
"""
url = u'https://unpkg.com/@jupyter-widgets/html-manager@{0:s}/dist/embed-amd.js'.format(version)
if version.startswith('^'):
version = version[1:]
filename = "embed-amd_v{0:s}.js".format(version)
filepath = os.path.join(target, filename)
download_to_file(url, filepath)
return filename | python | def save_embed_js(target="", version=wembed.__html_manager_version__):
"""Download and save the ipywidgets embedding javascript to a local file.
:type target: str
:type version: str
"""
url = u'https://unpkg.com/@jupyter-widgets/html-manager@{0:s}/dist/embed-amd.js'.format(version)
if version.startswith('^'):
version = version[1:]
filename = "embed-amd_v{0:s}.js".format(version)
filepath = os.path.join(target, filename)
download_to_file(url, filepath)
return filename | [
"def",
"save_embed_js",
"(",
"target",
"=",
"\"\"",
",",
"version",
"=",
"wembed",
".",
"__html_manager_version__",
")",
":",
"url",
"=",
"u'https://unpkg.com/@jupyter-widgets/html-manager@{0:s}/dist/embed-amd.js'",
".",
"format",
"(",
"version",
")",
"if",
"version",
... | Download and save the ipywidgets embedding javascript to a local file.
:type target: str
:type version: str | [
"Download",
"and",
"save",
"the",
"ipywidgets",
"embedding",
"javascript",
"to",
"a",
"local",
"file",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/embed.py#L76-L90 |
225,855 | maartenbreddels/ipyvolume | ipyvolume/embed.py | save_font_awesome | def save_font_awesome(dirpath='', version="4.7.0"):
"""Download and save the font-awesome package to a local directory.
:type dirpath: str
:type url: str
"""
directory_name = "font-awesome-{0:s}".format(version)
directory_path = os.path.join(dirpath, directory_name)
if os.path.exists(directory_path):
return directory_name
url = "https://fontawesome.com/v{0:s}/assets/font-awesome-{0:s}.zip".format(version)
content, _encoding = download_to_bytes(url)
try:
zip_directory = io.BytesIO(content)
unzip = zipfile.ZipFile(zip_directory)
top_level_name = unzip.namelist()[0]
unzip.extractall(dirpath)
except Exception as err:
raise IOError('Could not unzip content from: {0}\n{1}'.format(url, err))
os.rename(os.path.join(dirpath, top_level_name), directory_path)
return directory_name | python | def save_font_awesome(dirpath='', version="4.7.0"):
"""Download and save the font-awesome package to a local directory.
:type dirpath: str
:type url: str
"""
directory_name = "font-awesome-{0:s}".format(version)
directory_path = os.path.join(dirpath, directory_name)
if os.path.exists(directory_path):
return directory_name
url = "https://fontawesome.com/v{0:s}/assets/font-awesome-{0:s}.zip".format(version)
content, _encoding = download_to_bytes(url)
try:
zip_directory = io.BytesIO(content)
unzip = zipfile.ZipFile(zip_directory)
top_level_name = unzip.namelist()[0]
unzip.extractall(dirpath)
except Exception as err:
raise IOError('Could not unzip content from: {0}\n{1}'.format(url, err))
os.rename(os.path.join(dirpath, top_level_name), directory_path)
return directory_name | [
"def",
"save_font_awesome",
"(",
"dirpath",
"=",
"''",
",",
"version",
"=",
"\"4.7.0\"",
")",
":",
"directory_name",
"=",
"\"font-awesome-{0:s}\"",
".",
"format",
"(",
"version",
")",
"directory_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
","... | Download and save the font-awesome package to a local directory.
:type dirpath: str
:type url: str | [
"Download",
"and",
"save",
"the",
"font",
"-",
"awesome",
"package",
"to",
"a",
"local",
"directory",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/embed.py#L94-L118 |
225,856 | maartenbreddels/ipyvolume | ipyvolume/utils.py | download_to_bytes | def download_to_bytes(url, chunk_size=1024 * 1024 * 10, loadbar_length=10):
"""Download a url to bytes.
if chunk_size is not None, prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook)
:param url: str or url
:param chunk_size: None or int in bytes
:param loadbar_length: int length of load bar
:return: (bytes, encoding)
"""
stream = False if chunk_size is None else True
print("Downloading {0:s}: ".format(url), end="")
response = requests.get(url, stream=stream)
# raise error if download was unsuccessful
response.raise_for_status()
encoding = response.encoding
total_length = response.headers.get('content-length')
if total_length is not None:
total_length = float(total_length)
if stream:
print("{0:.2f}Mb/{1:} ".format(total_length / (1024 * 1024), loadbar_length), end="")
else:
print("{0:.2f}Mb ".format(total_length / (1024 * 1024)), end="")
if stream:
print("[", end="")
chunks = []
loaded = 0
loaded_size = 0
for chunk in response.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
# print our progress bar
if total_length is not None:
while loaded < loadbar_length * loaded_size / total_length:
print("=", end='')
loaded += 1
loaded_size += chunk_size
chunks.append(chunk)
if total_length is None:
print("=" * loadbar_length, end='')
else:
while loaded < loadbar_length:
print("=", end='')
loaded += 1
content = b"".join(chunks)
print("] ", end="")
else:
content = response.content
print("Finished")
response.close()
return content, encoding | python | def download_to_bytes(url, chunk_size=1024 * 1024 * 10, loadbar_length=10):
"""Download a url to bytes.
if chunk_size is not None, prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook)
:param url: str or url
:param chunk_size: None or int in bytes
:param loadbar_length: int length of load bar
:return: (bytes, encoding)
"""
stream = False if chunk_size is None else True
print("Downloading {0:s}: ".format(url), end="")
response = requests.get(url, stream=stream)
# raise error if download was unsuccessful
response.raise_for_status()
encoding = response.encoding
total_length = response.headers.get('content-length')
if total_length is not None:
total_length = float(total_length)
if stream:
print("{0:.2f}Mb/{1:} ".format(total_length / (1024 * 1024), loadbar_length), end="")
else:
print("{0:.2f}Mb ".format(total_length / (1024 * 1024)), end="")
if stream:
print("[", end="")
chunks = []
loaded = 0
loaded_size = 0
for chunk in response.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
# print our progress bar
if total_length is not None:
while loaded < loadbar_length * loaded_size / total_length:
print("=", end='')
loaded += 1
loaded_size += chunk_size
chunks.append(chunk)
if total_length is None:
print("=" * loadbar_length, end='')
else:
while loaded < loadbar_length:
print("=", end='')
loaded += 1
content = b"".join(chunks)
print("] ", end="")
else:
content = response.content
print("Finished")
response.close()
return content, encoding | [
"def",
"download_to_bytes",
"(",
"url",
",",
"chunk_size",
"=",
"1024",
"*",
"1024",
"*",
"10",
",",
"loadbar_length",
"=",
"10",
")",
":",
"stream",
"=",
"False",
"if",
"chunk_size",
"is",
"None",
"else",
"True",
"print",
"(",
"\"Downloading {0:s}: \"",
"... | Download a url to bytes.
if chunk_size is not None, prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook)
:param url: str or url
:param chunk_size: None or int in bytes
:param loadbar_length: int length of load bar
:return: (bytes, encoding) | [
"Download",
"a",
"url",
"to",
"bytes",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/utils.py#L40-L95 |
225,857 | maartenbreddels/ipyvolume | ipyvolume/utils.py | download_yield_bytes | def download_yield_bytes(url, chunk_size=1024 * 1024 * 10):
"""Yield a downloaded url as byte chunks.
:param url: str or url
:param chunk_size: None or int in bytes
:yield: byte chunks
"""
response = requests.get(url, stream=True)
# raise error if download was unsuccessful
response.raise_for_status()
total_length = response.headers.get('content-length')
if total_length is not None:
total_length = float(total_length)
length_str = "{0:.2f}Mb ".format(total_length / (1024 * 1024))
else:
length_str = ""
print("Yielding {0:s} {1:s}".format(url, length_str))
for chunk in response.iter_content(chunk_size=chunk_size):
yield chunk
response.close() | python | def download_yield_bytes(url, chunk_size=1024 * 1024 * 10):
"""Yield a downloaded url as byte chunks.
:param url: str or url
:param chunk_size: None or int in bytes
:yield: byte chunks
"""
response = requests.get(url, stream=True)
# raise error if download was unsuccessful
response.raise_for_status()
total_length = response.headers.get('content-length')
if total_length is not None:
total_length = float(total_length)
length_str = "{0:.2f}Mb ".format(total_length / (1024 * 1024))
else:
length_str = ""
print("Yielding {0:s} {1:s}".format(url, length_str))
for chunk in response.iter_content(chunk_size=chunk_size):
yield chunk
response.close() | [
"def",
"download_yield_bytes",
"(",
"url",
",",
"chunk_size",
"=",
"1024",
"*",
"1024",
"*",
"10",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
")",
"# raise error if download was unsuccessful",
"response",
".",
... | Yield a downloaded url as byte chunks.
:param url: str or url
:param chunk_size: None or int in bytes
:yield: byte chunks | [
"Yield",
"a",
"downloaded",
"url",
"as",
"byte",
"chunks",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/utils.py#L98-L119 |
225,858 | maartenbreddels/ipyvolume | ipyvolume/utils.py | download_to_file | def download_to_file(url, filepath, resume=False, overwrite=False, chunk_size=1024 * 1024 * 10, loadbar_length=10):
"""Download a url.
prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook)
:type url: str
:type filepath: str
:param filepath: path to download to
:param resume: if True resume download from existing file chunk
:param overwrite: if True remove any existing filepath
:param chunk_size: None or int in bytes
:param loadbar_length: int length of load bar
:return:
"""
resume_header = None
loaded_size = 0
write_mode = 'wb'
if os.path.exists(filepath):
if overwrite:
os.remove(filepath)
elif resume:
# if we want to resume, first try and see if the file is already complete
loaded_size = os.path.getsize(filepath)
clength = requests.head(url).headers.get('content-length')
if clength is not None:
if int(clength) == loaded_size:
return None
# give the point to resume at
resume_header = {'Range': 'bytes=%s-' % loaded_size}
write_mode = 'ab'
else:
return None
stream = False if chunk_size is None else True
# start printing with no return character, so that we can have everything on one line
print("Downloading {0:s}: ".format(url), end="")
response = requests.get(url, stream=stream, headers=resume_header)
# raise error if download was unsuccessful
response.raise_for_status()
# get the size of the file if available
total_length = response.headers.get('content-length')
if total_length is not None:
total_length = float(total_length) + loaded_size
print("{0:.2f}Mb/{1:} ".format(total_length / (1024 * 1024), loadbar_length), end="")
print("[", end="")
parent = os.path.dirname(filepath)
if not os.path.exists(parent) and parent:
os.makedirs(parent)
with io.open(filepath, write_mode) as f:
loaded = 0
for chunk in response.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
# print our progress bar
if total_length is not None and chunk_size is not None:
while loaded < loadbar_length * loaded_size / total_length:
print("=", end='')
loaded += 1
loaded_size += chunk_size
f.write(chunk)
if total_length is None:
print("=" * loadbar_length, end='')
else:
while loaded < loadbar_length:
print("=", end='')
loaded += 1
print("] Finished") | python | def download_to_file(url, filepath, resume=False, overwrite=False, chunk_size=1024 * 1024 * 10, loadbar_length=10):
"""Download a url.
prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook)
:type url: str
:type filepath: str
:param filepath: path to download to
:param resume: if True resume download from existing file chunk
:param overwrite: if True remove any existing filepath
:param chunk_size: None or int in bytes
:param loadbar_length: int length of load bar
:return:
"""
resume_header = None
loaded_size = 0
write_mode = 'wb'
if os.path.exists(filepath):
if overwrite:
os.remove(filepath)
elif resume:
# if we want to resume, first try and see if the file is already complete
loaded_size = os.path.getsize(filepath)
clength = requests.head(url).headers.get('content-length')
if clength is not None:
if int(clength) == loaded_size:
return None
# give the point to resume at
resume_header = {'Range': 'bytes=%s-' % loaded_size}
write_mode = 'ab'
else:
return None
stream = False if chunk_size is None else True
# start printing with no return character, so that we can have everything on one line
print("Downloading {0:s}: ".format(url), end="")
response = requests.get(url, stream=stream, headers=resume_header)
# raise error if download was unsuccessful
response.raise_for_status()
# get the size of the file if available
total_length = response.headers.get('content-length')
if total_length is not None:
total_length = float(total_length) + loaded_size
print("{0:.2f}Mb/{1:} ".format(total_length / (1024 * 1024), loadbar_length), end="")
print("[", end="")
parent = os.path.dirname(filepath)
if not os.path.exists(parent) and parent:
os.makedirs(parent)
with io.open(filepath, write_mode) as f:
loaded = 0
for chunk in response.iter_content(chunk_size=chunk_size):
if chunk: # filter out keep-alive new chunks
# print our progress bar
if total_length is not None and chunk_size is not None:
while loaded < loadbar_length * loaded_size / total_length:
print("=", end='')
loaded += 1
loaded_size += chunk_size
f.write(chunk)
if total_length is None:
print("=" * loadbar_length, end='')
else:
while loaded < loadbar_length:
print("=", end='')
loaded += 1
print("] Finished") | [
"def",
"download_to_file",
"(",
"url",
",",
"filepath",
",",
"resume",
"=",
"False",
",",
"overwrite",
"=",
"False",
",",
"chunk_size",
"=",
"1024",
"*",
"1024",
"*",
"10",
",",
"loadbar_length",
"=",
"10",
")",
":",
"resume_header",
"=",
"None",
"loaded... | Download a url.
prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook)
:type url: str
:type filepath: str
:param filepath: path to download to
:param resume: if True resume download from existing file chunk
:param overwrite: if True remove any existing filepath
:param chunk_size: None or int in bytes
:param loadbar_length: int length of load bar
:return: | [
"Download",
"a",
"url",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/utils.py#L122-L193 |
225,859 | maartenbreddels/ipyvolume | ipyvolume/astro.py | _randomSO3 | def _randomSO3():
"""Return random rotatation matrix, algo by James Arvo."""
u1 = np.random.random()
u2 = np.random.random()
u3 = np.random.random()
R = np.array(
[
[np.cos(2 * np.pi * u1), np.sin(2 * np.pi * u1), 0],
[-np.sin(2 * np.pi * u1), np.cos(2 * np.pi * u1), 0],
[0, 0, 1],
]
)
v = np.array([np.cos(2 * np.pi * u2) * np.sqrt(u3), np.sin(2 * np.pi * u2) * np.sqrt(u3), np.sqrt(1 - u3)])
H = np.identity(3) - 2 * v * np.transpose([v])
return -np.dot(H, R) | python | def _randomSO3():
"""Return random rotatation matrix, algo by James Arvo."""
u1 = np.random.random()
u2 = np.random.random()
u3 = np.random.random()
R = np.array(
[
[np.cos(2 * np.pi * u1), np.sin(2 * np.pi * u1), 0],
[-np.sin(2 * np.pi * u1), np.cos(2 * np.pi * u1), 0],
[0, 0, 1],
]
)
v = np.array([np.cos(2 * np.pi * u2) * np.sqrt(u3), np.sin(2 * np.pi * u2) * np.sqrt(u3), np.sqrt(1 - u3)])
H = np.identity(3) - 2 * v * np.transpose([v])
return -np.dot(H, R) | [
"def",
"_randomSO3",
"(",
")",
":",
"u1",
"=",
"np",
".",
"random",
".",
"random",
"(",
")",
"u2",
"=",
"np",
".",
"random",
".",
"random",
"(",
")",
"u3",
"=",
"np",
".",
"random",
".",
"random",
"(",
")",
"R",
"=",
"np",
".",
"array",
"(",
... | Return random rotatation matrix, algo by James Arvo. | [
"Return",
"random",
"rotatation",
"matrix",
"algo",
"by",
"James",
"Arvo",
"."
] | e68b72852b61276f8e6793bc8811f5b2432a155f | https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/astro.py#L11-L25 |
225,860 | jaegertracing/jaeger-client-python | jaeger_client/throttler.py | RemoteThrottler._set_client_id | def _set_client_id(self, client_id):
"""
Method for tracer to set client ID of throttler.
"""
with self.lock:
if self.client_id is None:
self.client_id = client_id | python | def _set_client_id(self, client_id):
"""
Method for tracer to set client ID of throttler.
"""
with self.lock:
if self.client_id is None:
self.client_id = client_id | [
"def",
"_set_client_id",
"(",
"self",
",",
"client_id",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"client_id",
"is",
"None",
":",
"self",
".",
"client_id",
"=",
"client_id"
] | Method for tracer to set client ID of throttler. | [
"Method",
"for",
"tracer",
"to",
"set",
"client",
"ID",
"of",
"throttler",
"."
] | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/throttler.py#L81-L87 |
225,861 | jaegertracing/jaeger-client-python | jaeger_client/throttler.py | RemoteThrottler._init_polling | def _init_polling(self):
"""
Bootstrap polling for throttler.
To avoid spiky traffic from throttler clients, we use a random delay
before the first poll.
"""
with self.lock:
if not self.running:
return
r = random.Random()
delay = r.random() * self.refresh_interval
self.channel.io_loop.call_later(
delay=delay, callback=self._delayed_polling)
self.logger.info(
'Delaying throttling credit polling by %d sec', delay) | python | def _init_polling(self):
"""
Bootstrap polling for throttler.
To avoid spiky traffic from throttler clients, we use a random delay
before the first poll.
"""
with self.lock:
if not self.running:
return
r = random.Random()
delay = r.random() * self.refresh_interval
self.channel.io_loop.call_later(
delay=delay, callback=self._delayed_polling)
self.logger.info(
'Delaying throttling credit polling by %d sec', delay) | [
"def",
"_init_polling",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"not",
"self",
".",
"running",
":",
"return",
"r",
"=",
"random",
".",
"Random",
"(",
")",
"delay",
"=",
"r",
".",
"random",
"(",
")",
"*",
"self",
".",
"refre... | Bootstrap polling for throttler.
To avoid spiky traffic from throttler clients, we use a random delay
before the first poll. | [
"Bootstrap",
"polling",
"for",
"throttler",
"."
] | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/throttler.py#L89-L105 |
225,862 | jaegertracing/jaeger-client-python | jaeger_client/reporter.py | Reporter.close | def close(self):
"""
Ensure that all spans from the queue are submitted.
Returns Future that will be completed once the queue is empty.
"""
with self.stop_lock:
self.stopped = True
return ioloop_util.submit(self._flush, io_loop=self.io_loop) | python | def close(self):
"""
Ensure that all spans from the queue are submitted.
Returns Future that will be completed once the queue is empty.
"""
with self.stop_lock:
self.stopped = True
return ioloop_util.submit(self._flush, io_loop=self.io_loop) | [
"def",
"close",
"(",
"self",
")",
":",
"with",
"self",
".",
"stop_lock",
":",
"self",
".",
"stopped",
"=",
"True",
"return",
"ioloop_util",
".",
"submit",
"(",
"self",
".",
"_flush",
",",
"io_loop",
"=",
"self",
".",
"io_loop",
")"
] | Ensure that all spans from the queue are submitted.
Returns Future that will be completed once the queue is empty. | [
"Ensure",
"that",
"all",
"spans",
"from",
"the",
"queue",
"are",
"submitted",
".",
"Returns",
"Future",
"that",
"will",
"be",
"completed",
"once",
"the",
"queue",
"is",
"empty",
"."
] | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/reporter.py#L218-L226 |
225,863 | jaegertracing/jaeger-client-python | jaeger_client/span.py | Span.finish | def finish(self, finish_time=None):
"""Indicate that the work represented by this span has been completed
or terminated, and is ready to be sent to the Reporter.
If any tags / logs need to be added to the span, it should be done
before calling finish(), otherwise they may be ignored.
:param finish_time: an explicit Span finish timestamp as a unix
timestamp per time.time()
"""
if not self.is_sampled():
return
self.end_time = finish_time or time.time() # no locking
self.tracer.report_span(self) | python | def finish(self, finish_time=None):
"""Indicate that the work represented by this span has been completed
or terminated, and is ready to be sent to the Reporter.
If any tags / logs need to be added to the span, it should be done
before calling finish(), otherwise they may be ignored.
:param finish_time: an explicit Span finish timestamp as a unix
timestamp per time.time()
"""
if not self.is_sampled():
return
self.end_time = finish_time or time.time() # no locking
self.tracer.report_span(self) | [
"def",
"finish",
"(",
"self",
",",
"finish_time",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_sampled",
"(",
")",
":",
"return",
"self",
".",
"end_time",
"=",
"finish_time",
"or",
"time",
".",
"time",
"(",
")",
"# no locking",
"self",
".",
"... | Indicate that the work represented by this span has been completed
or terminated, and is ready to be sent to the Reporter.
If any tags / logs need to be added to the span, it should be done
before calling finish(), otherwise they may be ignored.
:param finish_time: an explicit Span finish timestamp as a unix
timestamp per time.time() | [
"Indicate",
"that",
"the",
"work",
"represented",
"by",
"this",
"span",
"has",
"been",
"completed",
"or",
"terminated",
"and",
"is",
"ready",
"to",
"be",
"sent",
"to",
"the",
"Reporter",
"."
] | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/span.py#L60-L74 |
225,864 | jaegertracing/jaeger-client-python | jaeger_client/span.py | Span._set_sampling_priority | def _set_sampling_priority(self, value):
"""
N.B. Caller must be holding update_lock.
"""
# Ignore debug spans trying to re-enable debug.
if self.is_debug() and value:
return False
try:
value_num = int(value)
except ValueError:
return False
if value_num == 0:
self.context.flags &= ~(SAMPLED_FLAG | DEBUG_FLAG)
return False
if self.tracer.is_debug_allowed(self.operation_name):
self.context.flags |= SAMPLED_FLAG | DEBUG_FLAG
return True
return False | python | def _set_sampling_priority(self, value):
"""
N.B. Caller must be holding update_lock.
"""
# Ignore debug spans trying to re-enable debug.
if self.is_debug() and value:
return False
try:
value_num = int(value)
except ValueError:
return False
if value_num == 0:
self.context.flags &= ~(SAMPLED_FLAG | DEBUG_FLAG)
return False
if self.tracer.is_debug_allowed(self.operation_name):
self.context.flags |= SAMPLED_FLAG | DEBUG_FLAG
return True
return False | [
"def",
"_set_sampling_priority",
"(",
"self",
",",
"value",
")",
":",
"# Ignore debug spans trying to re-enable debug.",
"if",
"self",
".",
"is_debug",
"(",
")",
"and",
"value",
":",
"return",
"False",
"try",
":",
"value_num",
"=",
"int",
"(",
"value",
")",
"e... | N.B. Caller must be holding update_lock. | [
"N",
".",
"B",
".",
"Caller",
"must",
"be",
"holding",
"update_lock",
"."
] | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/span.py#L92-L111 |
225,865 | jaegertracing/jaeger-client-python | jaeger_client/TUDPTransport.py | TUDPTransport.write | def write(self, buf):
"""Raw write to the UDP socket."""
return self.transport_sock.sendto(
buf,
(self.transport_host, self.transport_port)
) | python | def write(self, buf):
"""Raw write to the UDP socket."""
return self.transport_sock.sendto(
buf,
(self.transport_host, self.transport_port)
) | [
"def",
"write",
"(",
"self",
",",
"buf",
")",
":",
"return",
"self",
".",
"transport_sock",
".",
"sendto",
"(",
"buf",
",",
"(",
"self",
".",
"transport_host",
",",
"self",
".",
"transport_port",
")",
")"
] | Raw write to the UDP socket. | [
"Raw",
"write",
"to",
"the",
"UDP",
"socket",
"."
] | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/TUDPTransport.py#L39-L44 |
225,866 | jaegertracing/jaeger-client-python | jaeger_client/config.py | Config.initialize_tracer | def initialize_tracer(self, io_loop=None):
"""
Initialize Jaeger Tracer based on the passed `jaeger_client.Config`.
Save it to `opentracing.tracer` global variable.
Only the first call to this method has any effect.
"""
with Config._initialized_lock:
if Config._initialized:
logger.warn('Jaeger tracer already initialized, skipping')
return
Config._initialized = True
tracer = self.new_tracer(io_loop)
self._initialize_global_tracer(tracer=tracer)
return tracer | python | def initialize_tracer(self, io_loop=None):
"""
Initialize Jaeger Tracer based on the passed `jaeger_client.Config`.
Save it to `opentracing.tracer` global variable.
Only the first call to this method has any effect.
"""
with Config._initialized_lock:
if Config._initialized:
logger.warn('Jaeger tracer already initialized, skipping')
return
Config._initialized = True
tracer = self.new_tracer(io_loop)
self._initialize_global_tracer(tracer=tracer)
return tracer | [
"def",
"initialize_tracer",
"(",
"self",
",",
"io_loop",
"=",
"None",
")",
":",
"with",
"Config",
".",
"_initialized_lock",
":",
"if",
"Config",
".",
"_initialized",
":",
"logger",
".",
"warn",
"(",
"'Jaeger tracer already initialized, skipping'",
")",
"return",
... | Initialize Jaeger Tracer based on the passed `jaeger_client.Config`.
Save it to `opentracing.tracer` global variable.
Only the first call to this method has any effect. | [
"Initialize",
"Jaeger",
"Tracer",
"based",
"on",
"the",
"passed",
"jaeger_client",
".",
"Config",
".",
"Save",
"it",
"to",
"opentracing",
".",
"tracer",
"global",
"variable",
".",
"Only",
"the",
"first",
"call",
"to",
"this",
"method",
"has",
"any",
"effect"... | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/config.py#L340-L356 |
225,867 | jaegertracing/jaeger-client-python | jaeger_client/config.py | Config.new_tracer | def new_tracer(self, io_loop=None):
"""
Create a new Jaeger Tracer based on the passed `jaeger_client.Config`.
Does not set `opentracing.tracer` global variable.
"""
channel = self._create_local_agent_channel(io_loop=io_loop)
sampler = self.sampler
if not sampler:
sampler = RemoteControlledSampler(
channel=channel,
service_name=self.service_name,
logger=logger,
metrics_factory=self._metrics_factory,
error_reporter=self.error_reporter,
sampling_refresh_interval=self.sampling_refresh_interval,
max_operations=self.max_operations)
logger.info('Using sampler %s', sampler)
reporter = Reporter(
channel=channel,
queue_capacity=self.reporter_queue_size,
batch_size=self.reporter_batch_size,
flush_interval=self.reporter_flush_interval,
logger=logger,
metrics_factory=self._metrics_factory,
error_reporter=self.error_reporter)
if self.logging:
reporter = CompositeReporter(reporter, LoggingReporter(logger))
if not self.throttler_group() is None:
throttler = RemoteThrottler(
channel,
self.service_name,
refresh_interval=self.throttler_refresh_interval,
logger=logger,
metrics_factory=self._metrics_factory,
error_reporter=self.error_reporter)
else:
throttler = None
return self.create_tracer(
reporter=reporter,
sampler=sampler,
throttler=throttler,
) | python | def new_tracer(self, io_loop=None):
"""
Create a new Jaeger Tracer based on the passed `jaeger_client.Config`.
Does not set `opentracing.tracer` global variable.
"""
channel = self._create_local_agent_channel(io_loop=io_loop)
sampler = self.sampler
if not sampler:
sampler = RemoteControlledSampler(
channel=channel,
service_name=self.service_name,
logger=logger,
metrics_factory=self._metrics_factory,
error_reporter=self.error_reporter,
sampling_refresh_interval=self.sampling_refresh_interval,
max_operations=self.max_operations)
logger.info('Using sampler %s', sampler)
reporter = Reporter(
channel=channel,
queue_capacity=self.reporter_queue_size,
batch_size=self.reporter_batch_size,
flush_interval=self.reporter_flush_interval,
logger=logger,
metrics_factory=self._metrics_factory,
error_reporter=self.error_reporter)
if self.logging:
reporter = CompositeReporter(reporter, LoggingReporter(logger))
if not self.throttler_group() is None:
throttler = RemoteThrottler(
channel,
self.service_name,
refresh_interval=self.throttler_refresh_interval,
logger=logger,
metrics_factory=self._metrics_factory,
error_reporter=self.error_reporter)
else:
throttler = None
return self.create_tracer(
reporter=reporter,
sampler=sampler,
throttler=throttler,
) | [
"def",
"new_tracer",
"(",
"self",
",",
"io_loop",
"=",
"None",
")",
":",
"channel",
"=",
"self",
".",
"_create_local_agent_channel",
"(",
"io_loop",
"=",
"io_loop",
")",
"sampler",
"=",
"self",
".",
"sampler",
"if",
"not",
"sampler",
":",
"sampler",
"=",
... | Create a new Jaeger Tracer based on the passed `jaeger_client.Config`.
Does not set `opentracing.tracer` global variable. | [
"Create",
"a",
"new",
"Jaeger",
"Tracer",
"based",
"on",
"the",
"passed",
"jaeger_client",
".",
"Config",
".",
"Does",
"not",
"set",
"opentracing",
".",
"tracer",
"global",
"variable",
"."
] | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/config.py#L358-L403 |
225,868 | jaegertracing/jaeger-client-python | jaeger_client/config.py | Config._create_local_agent_channel | def _create_local_agent_channel(self, io_loop):
"""
Create an out-of-process channel communicating to local jaeger-agent.
Spans are submitted as SOCK_DGRAM Thrift, sampling strategy is polled
via JSON HTTP.
:param self: instance of Config
"""
logger.info('Initializing Jaeger Tracer with UDP reporter')
return LocalAgentSender(
host=self.local_agent_reporting_host,
sampling_port=self.local_agent_sampling_port,
reporting_port=self.local_agent_reporting_port,
throttling_port=self.throttler_port,
io_loop=io_loop
) | python | def _create_local_agent_channel(self, io_loop):
"""
Create an out-of-process channel communicating to local jaeger-agent.
Spans are submitted as SOCK_DGRAM Thrift, sampling strategy is polled
via JSON HTTP.
:param self: instance of Config
"""
logger.info('Initializing Jaeger Tracer with UDP reporter')
return LocalAgentSender(
host=self.local_agent_reporting_host,
sampling_port=self.local_agent_sampling_port,
reporting_port=self.local_agent_reporting_port,
throttling_port=self.throttler_port,
io_loop=io_loop
) | [
"def",
"_create_local_agent_channel",
"(",
"self",
",",
"io_loop",
")",
":",
"logger",
".",
"info",
"(",
"'Initializing Jaeger Tracer with UDP reporter'",
")",
"return",
"LocalAgentSender",
"(",
"host",
"=",
"self",
".",
"local_agent_reporting_host",
",",
"sampling_port... | Create an out-of-process channel communicating to local jaeger-agent.
Spans are submitted as SOCK_DGRAM Thrift, sampling strategy is polled
via JSON HTTP.
:param self: instance of Config | [
"Create",
"an",
"out",
"-",
"of",
"-",
"process",
"channel",
"communicating",
"to",
"local",
"jaeger",
"-",
"agent",
".",
"Spans",
"are",
"submitted",
"as",
"SOCK_DGRAM",
"Thrift",
"sampling",
"strategy",
"is",
"polled",
"via",
"JSON",
"HTTP",
"."
] | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/config.py#L427-L442 |
225,869 | jaegertracing/jaeger-client-python | jaeger_client/codecs.py | span_context_from_string | def span_context_from_string(value):
"""
Decode span ID from a string into a TraceContext.
Returns None if the string value is malformed.
:param value: formatted {trace_id}:{span_id}:{parent_id}:{flags}
"""
if type(value) is list and len(value) > 0:
# sometimes headers are presented as arrays of values
if len(value) > 1:
raise SpanContextCorruptedException(
'trace context must be a string or array of 1: "%s"' % value)
value = value[0]
if not isinstance(value, six.string_types):
raise SpanContextCorruptedException(
'trace context not a string "%s"' % value)
parts = value.split(':')
if len(parts) != 4:
raise SpanContextCorruptedException(
'malformed trace context "%s"' % value)
try:
trace_id = int(parts[0], 16)
span_id = int(parts[1], 16)
parent_id = int(parts[2], 16)
flags = int(parts[3], 16)
if trace_id < 1 or span_id < 1 or parent_id < 0 or flags < 0:
raise SpanContextCorruptedException(
'malformed trace context "%s"' % value)
if parent_id == 0:
parent_id = None
return trace_id, span_id, parent_id, flags
except ValueError as e:
raise SpanContextCorruptedException(
'malformed trace context "%s": %s' % (value, e)) | python | def span_context_from_string(value):
"""
Decode span ID from a string into a TraceContext.
Returns None if the string value is malformed.
:param value: formatted {trace_id}:{span_id}:{parent_id}:{flags}
"""
if type(value) is list and len(value) > 0:
# sometimes headers are presented as arrays of values
if len(value) > 1:
raise SpanContextCorruptedException(
'trace context must be a string or array of 1: "%s"' % value)
value = value[0]
if not isinstance(value, six.string_types):
raise SpanContextCorruptedException(
'trace context not a string "%s"' % value)
parts = value.split(':')
if len(parts) != 4:
raise SpanContextCorruptedException(
'malformed trace context "%s"' % value)
try:
trace_id = int(parts[0], 16)
span_id = int(parts[1], 16)
parent_id = int(parts[2], 16)
flags = int(parts[3], 16)
if trace_id < 1 or span_id < 1 or parent_id < 0 or flags < 0:
raise SpanContextCorruptedException(
'malformed trace context "%s"' % value)
if parent_id == 0:
parent_id = None
return trace_id, span_id, parent_id, flags
except ValueError as e:
raise SpanContextCorruptedException(
'malformed trace context "%s": %s' % (value, e)) | [
"def",
"span_context_from_string",
"(",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"list",
"and",
"len",
"(",
"value",
")",
">",
"0",
":",
"# sometimes headers are presented as arrays of values",
"if",
"len",
"(",
"value",
")",
">",
"1",
":",
... | Decode span ID from a string into a TraceContext.
Returns None if the string value is malformed.
:param value: formatted {trace_id}:{span_id}:{parent_id}:{flags} | [
"Decode",
"span",
"ID",
"from",
"a",
"string",
"into",
"a",
"TraceContext",
".",
"Returns",
"None",
"if",
"the",
"string",
"value",
"is",
"malformed",
"."
] | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/codecs.py#L173-L206 |
225,870 | jaegertracing/jaeger-client-python | jaeger_client/thrift.py | parse_sampling_strategy | def parse_sampling_strategy(response):
"""
Parse SamplingStrategyResponse and converts to a Sampler.
:param response:
:return: Returns Go-style (value, error) pair
"""
s_type = response.strategyType
if s_type == sampling_manager.SamplingStrategyType.PROBABILISTIC:
if response.probabilisticSampling is None:
return None, 'probabilisticSampling field is None'
sampling_rate = response.probabilisticSampling.samplingRate
if 0 <= sampling_rate <= 1.0:
from jaeger_client.sampler import ProbabilisticSampler
return ProbabilisticSampler(rate=sampling_rate), None
return None, (
'Probabilistic sampling rate not in [0, 1] range: %s' %
sampling_rate
)
elif s_type == sampling_manager.SamplingStrategyType.RATE_LIMITING:
if response.rateLimitingSampling is None:
return None, 'rateLimitingSampling field is None'
mtps = response.rateLimitingSampling.maxTracesPerSecond
if 0 <= mtps < 500:
from jaeger_client.sampler import RateLimitingSampler
return RateLimitingSampler(max_traces_per_second=mtps), None
return None, (
'Rate limiting parameter not in [0, 500] range: %s' % mtps
)
return None, (
'Unsupported sampling strategy type: %s' % s_type
) | python | def parse_sampling_strategy(response):
"""
Parse SamplingStrategyResponse and converts to a Sampler.
:param response:
:return: Returns Go-style (value, error) pair
"""
s_type = response.strategyType
if s_type == sampling_manager.SamplingStrategyType.PROBABILISTIC:
if response.probabilisticSampling is None:
return None, 'probabilisticSampling field is None'
sampling_rate = response.probabilisticSampling.samplingRate
if 0 <= sampling_rate <= 1.0:
from jaeger_client.sampler import ProbabilisticSampler
return ProbabilisticSampler(rate=sampling_rate), None
return None, (
'Probabilistic sampling rate not in [0, 1] range: %s' %
sampling_rate
)
elif s_type == sampling_manager.SamplingStrategyType.RATE_LIMITING:
if response.rateLimitingSampling is None:
return None, 'rateLimitingSampling field is None'
mtps = response.rateLimitingSampling.maxTracesPerSecond
if 0 <= mtps < 500:
from jaeger_client.sampler import RateLimitingSampler
return RateLimitingSampler(max_traces_per_second=mtps), None
return None, (
'Rate limiting parameter not in [0, 500] range: %s' % mtps
)
return None, (
'Unsupported sampling strategy type: %s' % s_type
) | [
"def",
"parse_sampling_strategy",
"(",
"response",
")",
":",
"s_type",
"=",
"response",
".",
"strategyType",
"if",
"s_type",
"==",
"sampling_manager",
".",
"SamplingStrategyType",
".",
"PROBABILISTIC",
":",
"if",
"response",
".",
"probabilisticSampling",
"is",
"None... | Parse SamplingStrategyResponse and converts to a Sampler.
:param response:
:return: Returns Go-style (value, error) pair | [
"Parse",
"SamplingStrategyResponse",
"and",
"converts",
"to",
"a",
"Sampler",
"."
] | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/thrift.py#L208-L239 |
225,871 | jaegertracing/jaeger-client-python | jaeger_client/span_context.py | SpanContext.with_debug_id | def with_debug_id(debug_id):
"""Deprecated, not used by Jaeger."""
ctx = SpanContext(
trace_id=None, span_id=None, parent_id=None, flags=None
)
ctx._debug_id = debug_id
return ctx | python | def with_debug_id(debug_id):
"""Deprecated, not used by Jaeger."""
ctx = SpanContext(
trace_id=None, span_id=None, parent_id=None, flags=None
)
ctx._debug_id = debug_id
return ctx | [
"def",
"with_debug_id",
"(",
"debug_id",
")",
":",
"ctx",
"=",
"SpanContext",
"(",
"trace_id",
"=",
"None",
",",
"span_id",
"=",
"None",
",",
"parent_id",
"=",
"None",
",",
"flags",
"=",
"None",
")",
"ctx",
".",
"_debug_id",
"=",
"debug_id",
"return",
... | Deprecated, not used by Jaeger. | [
"Deprecated",
"not",
"used",
"by",
"Jaeger",
"."
] | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/span_context.py#L65-L71 |
225,872 | jaegertracing/jaeger-client-python | jaeger_client/tracer.py | Tracer.start_span | def start_span(self,
operation_name=None,
child_of=None,
references=None,
tags=None,
start_time=None,
ignore_active_span=False,
):
"""
Start and return a new Span representing a unit of work.
:param operation_name: name of the operation represented by the new
span from the perspective of the current service.
:param child_of: shortcut for 'child_of' reference
:param references: (optional) either a single Reference object or a
list of Reference objects that identify one or more parent
SpanContexts. (See the opentracing.Reference documentation for detail)
:param tags: optional dictionary of Span Tags. The caller gives up
ownership of that dictionary, because the Tracer may use it as-is
to avoid extra data copying.
:param start_time: an explicit Span start time as a unix timestamp per
time.time()
:param ignore_active_span: an explicit flag that ignores the current
active :class:`Scope` and creates a root :class:`Span`
:return: Returns an already-started Span instance.
"""
parent = child_of
if self.active_span is not None \
and not ignore_active_span \
and not parent:
parent = self.active_span
# allow Span to be passed as reference, not just SpanContext
if isinstance(parent, Span):
parent = parent.context
valid_references = None
if references:
valid_references = list()
if not isinstance(references, list):
references = [references]
for reference in references:
if reference.referenced_context is not None:
valid_references.append(reference)
# setting first reference as parent
if valid_references and (parent is None or not parent.has_trace):
parent = valid_references[0].referenced_context
rpc_server = tags and \
tags.get(ext_tags.SPAN_KIND) == ext_tags.SPAN_KIND_RPC_SERVER
if parent is None or not parent.has_trace:
trace_id = self._random_id(self.max_trace_id_bits)
span_id = self._random_id(constants._max_id_bits)
parent_id = None
flags = 0
baggage = None
if parent is None:
sampled, sampler_tags = \
self.sampler.is_sampled(trace_id, operation_name)
if sampled:
flags = SAMPLED_FLAG
tags = tags or {}
for k, v in six.iteritems(sampler_tags):
tags[k] = v
elif parent.debug_id and self.is_debug_allowed(operation_name):
flags = SAMPLED_FLAG | DEBUG_FLAG
tags = tags or {}
tags[self.debug_id_header] = parent.debug_id
if parent and parent.baggage:
baggage = dict(parent.baggage) # TODO do we need to clone?
else:
trace_id = parent.trace_id
if rpc_server and self.one_span_per_rpc:
# Zipkin-style one-span-per-RPC
span_id = parent.span_id
parent_id = parent.parent_id
else:
span_id = self._random_id(constants._max_id_bits)
parent_id = parent.span_id
flags = parent.flags
baggage = dict(parent.baggage) # TODO do we need to clone?
span_ctx = SpanContext(trace_id=trace_id, span_id=span_id,
parent_id=parent_id, flags=flags,
baggage=baggage)
span = Span(context=span_ctx, tracer=self,
operation_name=operation_name,
tags=tags, start_time=start_time, references=valid_references)
self._emit_span_metrics(span=span, join=rpc_server)
return span | python | def start_span(self,
operation_name=None,
child_of=None,
references=None,
tags=None,
start_time=None,
ignore_active_span=False,
):
"""
Start and return a new Span representing a unit of work.
:param operation_name: name of the operation represented by the new
span from the perspective of the current service.
:param child_of: shortcut for 'child_of' reference
:param references: (optional) either a single Reference object or a
list of Reference objects that identify one or more parent
SpanContexts. (See the opentracing.Reference documentation for detail)
:param tags: optional dictionary of Span Tags. The caller gives up
ownership of that dictionary, because the Tracer may use it as-is
to avoid extra data copying.
:param start_time: an explicit Span start time as a unix timestamp per
time.time()
:param ignore_active_span: an explicit flag that ignores the current
active :class:`Scope` and creates a root :class:`Span`
:return: Returns an already-started Span instance.
"""
parent = child_of
if self.active_span is not None \
and not ignore_active_span \
and not parent:
parent = self.active_span
# allow Span to be passed as reference, not just SpanContext
if isinstance(parent, Span):
parent = parent.context
valid_references = None
if references:
valid_references = list()
if not isinstance(references, list):
references = [references]
for reference in references:
if reference.referenced_context is not None:
valid_references.append(reference)
# setting first reference as parent
if valid_references and (parent is None or not parent.has_trace):
parent = valid_references[0].referenced_context
rpc_server = tags and \
tags.get(ext_tags.SPAN_KIND) == ext_tags.SPAN_KIND_RPC_SERVER
if parent is None or not parent.has_trace:
trace_id = self._random_id(self.max_trace_id_bits)
span_id = self._random_id(constants._max_id_bits)
parent_id = None
flags = 0
baggage = None
if parent is None:
sampled, sampler_tags = \
self.sampler.is_sampled(trace_id, operation_name)
if sampled:
flags = SAMPLED_FLAG
tags = tags or {}
for k, v in six.iteritems(sampler_tags):
tags[k] = v
elif parent.debug_id and self.is_debug_allowed(operation_name):
flags = SAMPLED_FLAG | DEBUG_FLAG
tags = tags or {}
tags[self.debug_id_header] = parent.debug_id
if parent and parent.baggage:
baggage = dict(parent.baggage) # TODO do we need to clone?
else:
trace_id = parent.trace_id
if rpc_server and self.one_span_per_rpc:
# Zipkin-style one-span-per-RPC
span_id = parent.span_id
parent_id = parent.parent_id
else:
span_id = self._random_id(constants._max_id_bits)
parent_id = parent.span_id
flags = parent.flags
baggage = dict(parent.baggage) # TODO do we need to clone?
span_ctx = SpanContext(trace_id=trace_id, span_id=span_id,
parent_id=parent_id, flags=flags,
baggage=baggage)
span = Span(context=span_ctx, tracer=self,
operation_name=operation_name,
tags=tags, start_time=start_time, references=valid_references)
self._emit_span_metrics(span=span, join=rpc_server)
return span | [
"def",
"start_span",
"(",
"self",
",",
"operation_name",
"=",
"None",
",",
"child_of",
"=",
"None",
",",
"references",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"start_time",
"=",
"None",
",",
"ignore_active_span",
"=",
"False",
",",
")",
":",
"parent"... | Start and return a new Span representing a unit of work.
:param operation_name: name of the operation represented by the new
span from the perspective of the current service.
:param child_of: shortcut for 'child_of' reference
:param references: (optional) either a single Reference object or a
list of Reference objects that identify one or more parent
SpanContexts. (See the opentracing.Reference documentation for detail)
:param tags: optional dictionary of Span Tags. The caller gives up
ownership of that dictionary, because the Tracer may use it as-is
to avoid extra data copying.
:param start_time: an explicit Span start time as a unix timestamp per
time.time()
:param ignore_active_span: an explicit flag that ignores the current
active :class:`Scope` and creates a root :class:`Span`
:return: Returns an already-started Span instance. | [
"Start",
"and",
"return",
"a",
"new",
"Span",
"representing",
"a",
"unit",
"of",
"work",
"."
] | 06face094757c645a6d81f0e073c001931a22a05 | https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/tracer.py#L118-L213 |
225,873 | RedHatInsights/insights-core | insights/combiners/lvm.py | merge_lvm_data | def merge_lvm_data(primary, secondary, name_key):
"""
Returns a dictionary containing the set of data from primary and secondary
where values in primary will always be returned if present, and values in
secondary will only be returned if not present in primary, or if the value
in primary is `None`.
Sample input Data::
primary = [
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'name_key': 'xyz'},
{'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'qrs'},
{'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'def'},
]
secondary = [
{'a': 31, 'e': 33, 'name_key': 'xyz'},
{'a': 11, 'e': 23, 'name_key': 'qrs'},
{'a': 1, 'e': 3, 'name_key': 'ghi'},
]
Returns:
dict: Dictionary of key value pairs from obj1 and obj2::
{
'xyz': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 33, 'name_key': 'xyz'},
'qrs': {'a': 11, 'b': 12, 'c': 13, d: 14, e: 23, 'name_key': 'qrs'},
'def': {'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'def'},
'ghi': {'a': 1, 'e': 3, 'name_key': 'ghi'}
}
"""
pri_data = to_name_key_dict(primary, name_key)
# Prime results with secondary data, to be updated with primary data
combined_data = to_name_key_dict(secondary, name_key)
for name in pri_data:
if name not in combined_data:
# Data only in primary
combined_data[name] = pri_data[name]
else:
# Data in both primary and secondary, pick primary if better or no secondary
combined_data[name].update(dict(
(k, v) for k, v in pri_data[name].items()
if v is not None or k not in combined_data[name]
))
return set_defaults(combined_data) | python | def merge_lvm_data(primary, secondary, name_key):
"""
Returns a dictionary containing the set of data from primary and secondary
where values in primary will always be returned if present, and values in
secondary will only be returned if not present in primary, or if the value
in primary is `None`.
Sample input Data::
primary = [
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'name_key': 'xyz'},
{'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'qrs'},
{'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'def'},
]
secondary = [
{'a': 31, 'e': 33, 'name_key': 'xyz'},
{'a': 11, 'e': 23, 'name_key': 'qrs'},
{'a': 1, 'e': 3, 'name_key': 'ghi'},
]
Returns:
dict: Dictionary of key value pairs from obj1 and obj2::
{
'xyz': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 33, 'name_key': 'xyz'},
'qrs': {'a': 11, 'b': 12, 'c': 13, d: 14, e: 23, 'name_key': 'qrs'},
'def': {'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'def'},
'ghi': {'a': 1, 'e': 3, 'name_key': 'ghi'}
}
"""
pri_data = to_name_key_dict(primary, name_key)
# Prime results with secondary data, to be updated with primary data
combined_data = to_name_key_dict(secondary, name_key)
for name in pri_data:
if name not in combined_data:
# Data only in primary
combined_data[name] = pri_data[name]
else:
# Data in both primary and secondary, pick primary if better or no secondary
combined_data[name].update(dict(
(k, v) for k, v in pri_data[name].items()
if v is not None or k not in combined_data[name]
))
return set_defaults(combined_data) | [
"def",
"merge_lvm_data",
"(",
"primary",
",",
"secondary",
",",
"name_key",
")",
":",
"pri_data",
"=",
"to_name_key_dict",
"(",
"primary",
",",
"name_key",
")",
"# Prime results with secondary data, to be updated with primary data",
"combined_data",
"=",
"to_name_key_dict",... | Returns a dictionary containing the set of data from primary and secondary
where values in primary will always be returned if present, and values in
secondary will only be returned if not present in primary, or if the value
in primary is `None`.
Sample input Data::
primary = [
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'name_key': 'xyz'},
{'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'qrs'},
{'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'def'},
]
secondary = [
{'a': 31, 'e': 33, 'name_key': 'xyz'},
{'a': 11, 'e': 23, 'name_key': 'qrs'},
{'a': 1, 'e': 3, 'name_key': 'ghi'},
]
Returns:
dict: Dictionary of key value pairs from obj1 and obj2::
{
'xyz': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 33, 'name_key': 'xyz'},
'qrs': {'a': 11, 'b': 12, 'c': 13, d: 14, e: 23, 'name_key': 'qrs'},
'def': {'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'def'},
'ghi': {'a': 1, 'e': 3, 'name_key': 'ghi'}
} | [
"Returns",
"a",
"dictionary",
"containing",
"the",
"set",
"of",
"data",
"from",
"primary",
"and",
"secondary",
"where",
"values",
"in",
"primary",
"will",
"always",
"be",
"returned",
"if",
"present",
"and",
"values",
"in",
"secondary",
"will",
"only",
"be",
... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/combiners/lvm.py#L112-L157 |
225,874 | RedHatInsights/insights-core | insights/client/insights_spec.py | InsightsFile.get_output | def get_output(self):
'''
Get file content, selecting only lines we are interested in
'''
if not os.path.isfile(self.real_path):
logger.debug('File %s does not exist', self.real_path)
return
cmd = []
cmd.append('sed')
cmd.append('-rf')
cmd.append(constants.default_sed_file)
cmd.append(self.real_path)
sedcmd = Popen(cmd,
stdout=PIPE)
if self.exclude is not None:
exclude_file = NamedTemporaryFile()
exclude_file.write("\n".join(self.exclude).encode('utf-8'))
exclude_file.flush()
cmd = "grep -v -F -f %s" % exclude_file.name
args = shlex.split(cmd)
proc = Popen(args, stdin=sedcmd.stdout, stdout=PIPE)
sedcmd.stdout.close()
stdin = proc.stdout
if self.pattern is None:
output = proc.communicate()[0]
else:
sedcmd = proc
if self.pattern is not None:
pattern_file = NamedTemporaryFile()
pattern_file.write("\n".join(self.pattern).encode('utf-8'))
pattern_file.flush()
cmd = "grep -F -f %s" % pattern_file.name
args = shlex.split(cmd)
proc1 = Popen(args, stdin=sedcmd.stdout, stdout=PIPE)
sedcmd.stdout.close()
if self.exclude is not None:
stdin.close()
output = proc1.communicate()[0]
if self.pattern is None and self.exclude is None:
output = sedcmd.communicate()[0]
return output.decode('utf-8', 'ignore').strip() | python | def get_output(self):
'''
Get file content, selecting only lines we are interested in
'''
if not os.path.isfile(self.real_path):
logger.debug('File %s does not exist', self.real_path)
return
cmd = []
cmd.append('sed')
cmd.append('-rf')
cmd.append(constants.default_sed_file)
cmd.append(self.real_path)
sedcmd = Popen(cmd,
stdout=PIPE)
if self.exclude is not None:
exclude_file = NamedTemporaryFile()
exclude_file.write("\n".join(self.exclude).encode('utf-8'))
exclude_file.flush()
cmd = "grep -v -F -f %s" % exclude_file.name
args = shlex.split(cmd)
proc = Popen(args, stdin=sedcmd.stdout, stdout=PIPE)
sedcmd.stdout.close()
stdin = proc.stdout
if self.pattern is None:
output = proc.communicate()[0]
else:
sedcmd = proc
if self.pattern is not None:
pattern_file = NamedTemporaryFile()
pattern_file.write("\n".join(self.pattern).encode('utf-8'))
pattern_file.flush()
cmd = "grep -F -f %s" % pattern_file.name
args = shlex.split(cmd)
proc1 = Popen(args, stdin=sedcmd.stdout, stdout=PIPE)
sedcmd.stdout.close()
if self.exclude is not None:
stdin.close()
output = proc1.communicate()[0]
if self.pattern is None and self.exclude is None:
output = sedcmd.communicate()[0]
return output.decode('utf-8', 'ignore').strip() | [
"def",
"get_output",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"real_path",
")",
":",
"logger",
".",
"debug",
"(",
"'File %s does not exist'",
",",
"self",
".",
"real_path",
")",
"return",
"cmd",
"=",
"[",
... | Get file content, selecting only lines we are interested in | [
"Get",
"file",
"content",
"selecting",
"only",
"lines",
"we",
"are",
"interested",
"in"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/insights_spec.py#L147-L196 |
225,875 | RedHatInsights/insights-core | insights/parsers/openvswitch_logs.py | OpenVSwitchLog._parse_line | def _parse_line(self, line):
"""
Parse line into fields.
"""
fields = line.split('|', 4) # stop splitting after fourth | found
line_info = {'raw_message': line}
if len(fields) == 5:
line_info.update(dict(zip(self._fieldnames, fields)))
return line_info | python | def _parse_line(self, line):
"""
Parse line into fields.
"""
fields = line.split('|', 4) # stop splitting after fourth | found
line_info = {'raw_message': line}
if len(fields) == 5:
line_info.update(dict(zip(self._fieldnames, fields)))
return line_info | [
"def",
"_parse_line",
"(",
"self",
",",
"line",
")",
":",
"fields",
"=",
"line",
".",
"split",
"(",
"'|'",
",",
"4",
")",
"# stop splitting after fourth | found",
"line_info",
"=",
"{",
"'raw_message'",
":",
"line",
"}",
"if",
"len",
"(",
"fields",
")",
... | Parse line into fields. | [
"Parse",
"line",
"into",
"fields",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/openvswitch_logs.py#L52-L60 |
225,876 | RedHatInsights/insights-core | insights/core/dr.py | _import_component | def _import_component(name):
"""
Returns a class, function, or class method specified by the fully qualified
name.
"""
for f in (_get_from_module, _get_from_class):
try:
return f(name)
except:
pass
log.debug("Couldn't load %s" % name) | python | def _import_component(name):
"""
Returns a class, function, or class method specified by the fully qualified
name.
"""
for f in (_get_from_module, _get_from_class):
try:
return f(name)
except:
pass
log.debug("Couldn't load %s" % name) | [
"def",
"_import_component",
"(",
"name",
")",
":",
"for",
"f",
"in",
"(",
"_get_from_module",
",",
"_get_from_class",
")",
":",
"try",
":",
"return",
"f",
"(",
"name",
")",
"except",
":",
"pass",
"log",
".",
"debug",
"(",
"\"Couldn't load %s\"",
"%",
"na... | Returns a class, function, or class method specified by the fully qualified
name. | [
"Returns",
"a",
"class",
"function",
"or",
"class",
"method",
"specified",
"by",
"the",
"fully",
"qualified",
"name",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L151-L161 |
225,877 | RedHatInsights/insights-core | insights/core/dr.py | get_name | def get_name(component):
"""
Attempt to get the string name of component, including module and class if
applicable.
"""
if six.callable(component):
name = getattr(component, "__qualname__", component.__name__)
return '.'.join([component.__module__, name])
return str(component) | python | def get_name(component):
"""
Attempt to get the string name of component, including module and class if
applicable.
"""
if six.callable(component):
name = getattr(component, "__qualname__", component.__name__)
return '.'.join([component.__module__, name])
return str(component) | [
"def",
"get_name",
"(",
"component",
")",
":",
"if",
"six",
".",
"callable",
"(",
"component",
")",
":",
"name",
"=",
"getattr",
"(",
"component",
",",
"\"__qualname__\"",
",",
"component",
".",
"__name__",
")",
"return",
"'.'",
".",
"join",
"(",
"[",
... | Attempt to get the string name of component, including module and class if
applicable. | [
"Attempt",
"to",
"get",
"the",
"string",
"name",
"of",
"component",
"including",
"module",
"and",
"class",
"if",
"applicable",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L237-L245 |
225,878 | RedHatInsights/insights-core | insights/core/dr.py | walk_dependencies | def walk_dependencies(root, visitor):
"""
Call visitor on root and all dependencies reachable from it in breadth
first order.
Args:
root (component): component function or class
visitor (function): signature is `func(component, parent)`. The
call on root is `visitor(root, None)`.
"""
def visit(parent, visitor):
for d in get_dependencies(parent):
visitor(d, parent)
visit(d, visitor)
visitor(root, None)
visit(root, visitor) | python | def walk_dependencies(root, visitor):
"""
Call visitor on root and all dependencies reachable from it in breadth
first order.
Args:
root (component): component function or class
visitor (function): signature is `func(component, parent)`. The
call on root is `visitor(root, None)`.
"""
def visit(parent, visitor):
for d in get_dependencies(parent):
visitor(d, parent)
visit(d, visitor)
visitor(root, None)
visit(root, visitor) | [
"def",
"walk_dependencies",
"(",
"root",
",",
"visitor",
")",
":",
"def",
"visit",
"(",
"parent",
",",
"visitor",
")",
":",
"for",
"d",
"in",
"get_dependencies",
"(",
"parent",
")",
":",
"visitor",
"(",
"d",
",",
"parent",
")",
"visit",
"(",
"d",
","... | Call visitor on root and all dependencies reachable from it in breadth
first order.
Args:
root (component): component function or class
visitor (function): signature is `func(component, parent)`. The
call on root is `visitor(root, None)`. | [
"Call",
"visitor",
"on",
"root",
"and",
"all",
"dependencies",
"reachable",
"from",
"it",
"in",
"breadth",
"first",
"order",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L303-L319 |
225,879 | RedHatInsights/insights-core | insights/core/dr.py | get_subgraphs | def get_subgraphs(graph=None):
"""
Given a graph of possibly disconnected components, generate all graphs of
connected components. graph is a dictionary of dependencies. Keys are
components, and values are sets of components on which they depend.
"""
graph = graph or DEPENDENCIES
keys = set(graph)
frontier = set()
seen = set()
while keys:
frontier.add(keys.pop())
while frontier:
component = frontier.pop()
seen.add(component)
frontier |= set([d for d in get_dependencies(component) if d in graph])
frontier |= set([d for d in get_dependents(component) if d in graph])
frontier -= seen
yield dict((s, get_dependencies(s)) for s in seen)
keys -= seen
seen.clear() | python | def get_subgraphs(graph=None):
"""
Given a graph of possibly disconnected components, generate all graphs of
connected components. graph is a dictionary of dependencies. Keys are
components, and values are sets of components on which they depend.
"""
graph = graph or DEPENDENCIES
keys = set(graph)
frontier = set()
seen = set()
while keys:
frontier.add(keys.pop())
while frontier:
component = frontier.pop()
seen.add(component)
frontier |= set([d for d in get_dependencies(component) if d in graph])
frontier |= set([d for d in get_dependents(component) if d in graph])
frontier -= seen
yield dict((s, get_dependencies(s)) for s in seen)
keys -= seen
seen.clear() | [
"def",
"get_subgraphs",
"(",
"graph",
"=",
"None",
")",
":",
"graph",
"=",
"graph",
"or",
"DEPENDENCIES",
"keys",
"=",
"set",
"(",
"graph",
")",
"frontier",
"=",
"set",
"(",
")",
"seen",
"=",
"set",
"(",
")",
"while",
"keys",
":",
"frontier",
".",
... | Given a graph of possibly disconnected components, generate all graphs of
connected components. graph is a dictionary of dependencies. Keys are
components, and values are sets of components on which they depend. | [
"Given",
"a",
"graph",
"of",
"possibly",
"disconnected",
"components",
"generate",
"all",
"graphs",
"of",
"connected",
"components",
".",
"graph",
"is",
"a",
"dictionary",
"of",
"dependencies",
".",
"Keys",
"are",
"components",
"and",
"values",
"are",
"sets",
... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L352-L372 |
225,880 | RedHatInsights/insights-core | insights/core/dr.py | load_components | def load_components(*paths, **kwargs):
"""
Loads all components on the paths. Each path should be a package or module.
All components beneath a path are loaded.
Args:
paths (str): A package or module to load
Keyword Args:
include (str): A regular expression of packages and modules to include.
Defaults to '.*'
exclude (str): A regular expression of packges and modules to exclude.
Defaults to 'test'
continue_on_error (bool): If True, continue importing even if something
raises an ImportError. If False, raise the first ImportError.
Returns:
int: The total number of modules loaded.
Raises:
ImportError
"""
num_loaded = 0
for path in paths:
num_loaded += _load_components(path, **kwargs)
return num_loaded | python | def load_components(*paths, **kwargs):
"""
Loads all components on the paths. Each path should be a package or module.
All components beneath a path are loaded.
Args:
paths (str): A package or module to load
Keyword Args:
include (str): A regular expression of packages and modules to include.
Defaults to '.*'
exclude (str): A regular expression of packges and modules to exclude.
Defaults to 'test'
continue_on_error (bool): If True, continue importing even if something
raises an ImportError. If False, raise the first ImportError.
Returns:
int: The total number of modules loaded.
Raises:
ImportError
"""
num_loaded = 0
for path in paths:
num_loaded += _load_components(path, **kwargs)
return num_loaded | [
"def",
"load_components",
"(",
"*",
"paths",
",",
"*",
"*",
"kwargs",
")",
":",
"num_loaded",
"=",
"0",
"for",
"path",
"in",
"paths",
":",
"num_loaded",
"+=",
"_load_components",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
"return",
"num_loaded"
] | Loads all components on the paths. Each path should be a package or module.
All components beneath a path are loaded.
Args:
paths (str): A package or module to load
Keyword Args:
include (str): A regular expression of packages and modules to include.
Defaults to '.*'
exclude (str): A regular expression of packges and modules to exclude.
Defaults to 'test'
continue_on_error (bool): If True, continue importing even if something
raises an ImportError. If False, raise the first ImportError.
Returns:
int: The total number of modules loaded.
Raises:
ImportError | [
"Loads",
"all",
"components",
"on",
"the",
"paths",
".",
"Each",
"path",
"should",
"be",
"a",
"package",
"or",
"module",
".",
"All",
"components",
"beneath",
"a",
"path",
"are",
"loaded",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L418-L443 |
225,881 | RedHatInsights/insights-core | insights/core/dr.py | run | def run(components=None, broker=None):
"""
Executes components in an order that satisfies their dependency
relationships.
Keyword Args:
components: Can be one of a dependency graph, a single component, a
component group, or a component type. If it's anything other than a
dependency graph, the appropriate graph is built for you and before
evaluation.
broker (Broker): Optionally pass a broker to use for evaluation. One is
created by default, but it's often useful to seed a broker with an
initial dependency.
Returns:
Broker: The broker after evaluation.
"""
components = components or COMPONENTS[GROUPS.single]
components = _determine_components(components)
broker = broker or Broker()
for component in run_order(components):
start = time.time()
try:
if component not in broker and component in DELEGATES and is_enabled(component):
log.info("Trying %s" % get_name(component))
result = DELEGATES[component].process(broker)
broker[component] = result
except MissingRequirements as mr:
if log.isEnabledFor(logging.DEBUG):
name = get_name(component)
reqs = stringify_requirements(mr.requirements)
log.debug("%s missing requirements %s" % (name, reqs))
broker.add_exception(component, mr)
except SkipComponent:
pass
except Exception as ex:
tb = traceback.format_exc()
log.warn(tb)
broker.add_exception(component, ex, tb)
finally:
broker.exec_times[component] = time.time() - start
broker.fire_observers(component)
return broker | python | def run(components=None, broker=None):
"""
Executes components in an order that satisfies their dependency
relationships.
Keyword Args:
components: Can be one of a dependency graph, a single component, a
component group, or a component type. If it's anything other than a
dependency graph, the appropriate graph is built for you and before
evaluation.
broker (Broker): Optionally pass a broker to use for evaluation. One is
created by default, but it's often useful to seed a broker with an
initial dependency.
Returns:
Broker: The broker after evaluation.
"""
components = components or COMPONENTS[GROUPS.single]
components = _determine_components(components)
broker = broker or Broker()
for component in run_order(components):
start = time.time()
try:
if component not in broker and component in DELEGATES and is_enabled(component):
log.info("Trying %s" % get_name(component))
result = DELEGATES[component].process(broker)
broker[component] = result
except MissingRequirements as mr:
if log.isEnabledFor(logging.DEBUG):
name = get_name(component)
reqs = stringify_requirements(mr.requirements)
log.debug("%s missing requirements %s" % (name, reqs))
broker.add_exception(component, mr)
except SkipComponent:
pass
except Exception as ex:
tb = traceback.format_exc()
log.warn(tb)
broker.add_exception(component, ex, tb)
finally:
broker.exec_times[component] = time.time() - start
broker.fire_observers(component)
return broker | [
"def",
"run",
"(",
"components",
"=",
"None",
",",
"broker",
"=",
"None",
")",
":",
"components",
"=",
"components",
"or",
"COMPONENTS",
"[",
"GROUPS",
".",
"single",
"]",
"components",
"=",
"_determine_components",
"(",
"components",
")",
"broker",
"=",
"... | Executes components in an order that satisfies their dependency
relationships.
Keyword Args:
components: Can be one of a dependency graph, a single component, a
component group, or a component type. If it's anything other than a
dependency graph, the appropriate graph is built for you and before
evaluation.
broker (Broker): Optionally pass a broker to use for evaluation. One is
created by default, but it's often useful to seed a broker with an
initial dependency.
Returns:
Broker: The broker after evaluation. | [
"Executes",
"components",
"in",
"an",
"order",
"that",
"satisfies",
"their",
"dependency",
"relationships",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L927-L970 |
225,882 | RedHatInsights/insights-core | insights/core/dr.py | run_incremental | def run_incremental(components=None, broker=None):
"""
Executes components in an order that satisfies their dependency
relationships. Disjoint subgraphs are executed one at a time and a broker
containing the results for each is yielded. If a broker is passed here, its
instances are used to seed the broker used to hold state for each sub
graph.
Keyword Args:
components: Can be one of a dependency graph, a single component, a
component group, or a component type. If it's anything other than a
dependency graph, the appropriate graph is built for you and before
evaluation.
broker (Broker): Optionally pass a broker to use for evaluation. One is
created by default, but it's often useful to seed a broker with an
initial dependency.
Yields:
Broker: the broker used to evaluate each subgraph.
"""
for graph, _broker in generate_incremental(components, broker):
yield run(graph, broker=_broker) | python | def run_incremental(components=None, broker=None):
"""
Executes components in an order that satisfies their dependency
relationships. Disjoint subgraphs are executed one at a time and a broker
containing the results for each is yielded. If a broker is passed here, its
instances are used to seed the broker used to hold state for each sub
graph.
Keyword Args:
components: Can be one of a dependency graph, a single component, a
component group, or a component type. If it's anything other than a
dependency graph, the appropriate graph is built for you and before
evaluation.
broker (Broker): Optionally pass a broker to use for evaluation. One is
created by default, but it's often useful to seed a broker with an
initial dependency.
Yields:
Broker: the broker used to evaluate each subgraph.
"""
for graph, _broker in generate_incremental(components, broker):
yield run(graph, broker=_broker) | [
"def",
"run_incremental",
"(",
"components",
"=",
"None",
",",
"broker",
"=",
"None",
")",
":",
"for",
"graph",
",",
"_broker",
"in",
"generate_incremental",
"(",
"components",
",",
"broker",
")",
":",
"yield",
"run",
"(",
"graph",
",",
"broker",
"=",
"_... | Executes components in an order that satisfies their dependency
relationships. Disjoint subgraphs are executed one at a time and a broker
containing the results for each is yielded. If a broker is passed here, its
instances are used to seed the broker used to hold state for each sub
graph.
Keyword Args:
components: Can be one of a dependency graph, a single component, a
component group, or a component type. If it's anything other than a
dependency graph, the appropriate graph is built for you and before
evaluation.
broker (Broker): Optionally pass a broker to use for evaluation. One is
created by default, but it's often useful to seed a broker with an
initial dependency.
Yields:
Broker: the broker used to evaluate each subgraph. | [
"Executes",
"components",
"in",
"an",
"order",
"that",
"satisfies",
"their",
"dependency",
"relationships",
".",
"Disjoint",
"subgraphs",
"are",
"executed",
"one",
"at",
"a",
"time",
"and",
"a",
"broker",
"containing",
"the",
"results",
"for",
"each",
"is",
"y... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L982-L1002 |
225,883 | RedHatInsights/insights-core | insights/core/dr.py | ComponentType.invoke | def invoke(self, results):
"""
Handles invocation of the component. The default implementation invokes
it with positional arguments based on order of dependency declaration.
"""
args = [results.get(d) for d in self.deps]
return self.component(*args) | python | def invoke(self, results):
"""
Handles invocation of the component. The default implementation invokes
it with positional arguments based on order of dependency declaration.
"""
args = [results.get(d) for d in self.deps]
return self.component(*args) | [
"def",
"invoke",
"(",
"self",
",",
"results",
")",
":",
"args",
"=",
"[",
"results",
".",
"get",
"(",
"d",
")",
"for",
"d",
"in",
"self",
".",
"deps",
"]",
"return",
"self",
".",
"component",
"(",
"*",
"args",
")"
] | Handles invocation of the component. The default implementation invokes
it with positional arguments based on order of dependency declaration. | [
"Handles",
"invocation",
"of",
"the",
"component",
".",
"The",
"default",
"implementation",
"invokes",
"it",
"with",
"positional",
"arguments",
"based",
"on",
"order",
"of",
"dependency",
"declaration",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L647-L653 |
225,884 | RedHatInsights/insights-core | insights/core/dr.py | ComponentType.get_missing_dependencies | def get_missing_dependencies(self, broker):
"""
Gets required and at-least-one dependencies not provided by the broker.
"""
missing_required = [r for r in self.requires if r not in broker]
missing_at_least_one = [d for d in self.at_least_one if not set(d).intersection(broker)]
if missing_required or missing_at_least_one:
return (missing_required, missing_at_least_one) | python | def get_missing_dependencies(self, broker):
"""
Gets required and at-least-one dependencies not provided by the broker.
"""
missing_required = [r for r in self.requires if r not in broker]
missing_at_least_one = [d for d in self.at_least_one if not set(d).intersection(broker)]
if missing_required or missing_at_least_one:
return (missing_required, missing_at_least_one) | [
"def",
"get_missing_dependencies",
"(",
"self",
",",
"broker",
")",
":",
"missing_required",
"=",
"[",
"r",
"for",
"r",
"in",
"self",
".",
"requires",
"if",
"r",
"not",
"in",
"broker",
"]",
"missing_at_least_one",
"=",
"[",
"d",
"for",
"d",
"in",
"self",... | Gets required and at-least-one dependencies not provided by the broker. | [
"Gets",
"required",
"and",
"at",
"-",
"least",
"-",
"one",
"dependencies",
"not",
"provided",
"by",
"the",
"broker",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L655-L662 |
225,885 | RedHatInsights/insights-core | insights/core/dr.py | Broker.observer | def observer(self, component_type=ComponentType):
"""
You can use ``@broker.observer()`` as a decorator to your callback
instead of :func:`Broker.add_observer`.
"""
def inner(func):
self.add_observer(func, component_type)
return func
return inner | python | def observer(self, component_type=ComponentType):
"""
You can use ``@broker.observer()`` as a decorator to your callback
instead of :func:`Broker.add_observer`.
"""
def inner(func):
self.add_observer(func, component_type)
return func
return inner | [
"def",
"observer",
"(",
"self",
",",
"component_type",
"=",
"ComponentType",
")",
":",
"def",
"inner",
"(",
"func",
")",
":",
"self",
".",
"add_observer",
"(",
"func",
",",
"component_type",
")",
"return",
"func",
"return",
"inner"
] | You can use ``@broker.observer()`` as a decorator to your callback
instead of :func:`Broker.add_observer`. | [
"You",
"can",
"use"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L735-L743 |
225,886 | RedHatInsights/insights-core | insights/core/dr.py | Broker.add_observer | def add_observer(self, o, component_type=ComponentType):
"""
Add a callback that will get invoked after each component is called.
Args:
o (func): the callback function
Keyword Args:
component_type (ComponentType): the :class:`ComponentType` to observe.
The callback will fire any time an instance of the class or its
subclasses is invoked.
The callback should look like this:
.. code-block:: python
def callback(comp, broker):
value = broker.get(comp)
# do something with value
pass
"""
self.observers[component_type].add(o) | python | def add_observer(self, o, component_type=ComponentType):
"""
Add a callback that will get invoked after each component is called.
Args:
o (func): the callback function
Keyword Args:
component_type (ComponentType): the :class:`ComponentType` to observe.
The callback will fire any time an instance of the class or its
subclasses is invoked.
The callback should look like this:
.. code-block:: python
def callback(comp, broker):
value = broker.get(comp)
# do something with value
pass
"""
self.observers[component_type].add(o) | [
"def",
"add_observer",
"(",
"self",
",",
"o",
",",
"component_type",
"=",
"ComponentType",
")",
":",
"self",
".",
"observers",
"[",
"component_type",
"]",
".",
"add",
"(",
"o",
")"
] | Add a callback that will get invoked after each component is called.
Args:
o (func): the callback function
Keyword Args:
component_type (ComponentType): the :class:`ComponentType` to observe.
The callback will fire any time an instance of the class or its
subclasses is invoked.
The callback should look like this:
.. code-block:: python
def callback(comp, broker):
value = broker.get(comp)
# do something with value
pass | [
"Add",
"a",
"callback",
"that",
"will",
"get",
"invoked",
"after",
"each",
"component",
"is",
"called",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L745-L767 |
225,887 | RedHatInsights/insights-core | insights/combiners/logrotate_conf.py | get_tree | def get_tree(root=None):
"""
This is a helper function to get a logrotate configuration component for
your local machine or an archive. It's for use in interactive sessions.
"""
from insights import run
return run(LogRotateConfTree, root=root).get(LogRotateConfTree) | python | def get_tree(root=None):
"""
This is a helper function to get a logrotate configuration component for
your local machine or an archive. It's for use in interactive sessions.
"""
from insights import run
return run(LogRotateConfTree, root=root).get(LogRotateConfTree) | [
"def",
"get_tree",
"(",
"root",
"=",
"None",
")",
":",
"from",
"insights",
"import",
"run",
"return",
"run",
"(",
"LogRotateConfTree",
",",
"root",
"=",
"root",
")",
".",
"get",
"(",
"LogRotateConfTree",
")"
] | This is a helper function to get a logrotate configuration component for
your local machine or an archive. It's for use in interactive sessions. | [
"This",
"is",
"a",
"helper",
"function",
"to",
"get",
"a",
"logrotate",
"configuration",
"component",
"for",
"your",
"local",
"machine",
"or",
"an",
"archive",
".",
"It",
"s",
"for",
"use",
"in",
"interactive",
"sessions",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/combiners/logrotate_conf.py#L231-L237 |
225,888 | RedHatInsights/insights-core | insights/formats/_syslog.py | SysLogFormat.logit | def logit(self, msg, pid, user, cname, priority=None):
"""Function for formatting content and logging to syslog"""
if self.stream:
print(msg, file=self.stream)
elif priority == logging.WARNING:
self.logger.warning("{0}[pid:{1}] user:{2}: WARNING - {3}".format(cname, pid, user, msg))
elif priority == logging.ERROR:
self.logger.error("{0}[pid:{1}] user:{2}: ERROR - {3}".format(cname, pid, user, msg))
else:
self.logger.info("{0}[pid:{1}] user:{2}: INFO - {3}".format(cname, pid, user, msg)) | python | def logit(self, msg, pid, user, cname, priority=None):
"""Function for formatting content and logging to syslog"""
if self.stream:
print(msg, file=self.stream)
elif priority == logging.WARNING:
self.logger.warning("{0}[pid:{1}] user:{2}: WARNING - {3}".format(cname, pid, user, msg))
elif priority == logging.ERROR:
self.logger.error("{0}[pid:{1}] user:{2}: ERROR - {3}".format(cname, pid, user, msg))
else:
self.logger.info("{0}[pid:{1}] user:{2}: INFO - {3}".format(cname, pid, user, msg)) | [
"def",
"logit",
"(",
"self",
",",
"msg",
",",
"pid",
",",
"user",
",",
"cname",
",",
"priority",
"=",
"None",
")",
":",
"if",
"self",
".",
"stream",
":",
"print",
"(",
"msg",
",",
"file",
"=",
"self",
".",
"stream",
")",
"elif",
"priority",
"==",... | Function for formatting content and logging to syslog | [
"Function",
"for",
"formatting",
"content",
"and",
"logging",
"to",
"syslog"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/formats/_syslog.py#L45-L55 |
225,889 | RedHatInsights/insights-core | insights/formats/_syslog.py | SysLogFormat.log_exceptions | def log_exceptions(self, c, broker):
"""Gets exceptions to be logged and sends to logit function to be logged to syslog"""
if c in broker.exceptions:
ex = broker.exceptions.get(c)
ex = "Exception in {0} - {1}".format(dr.get_name(c), str(ex))
self.logit(ex, self.pid, self.user, "insights-run", logging.ERROR) | python | def log_exceptions(self, c, broker):
"""Gets exceptions to be logged and sends to logit function to be logged to syslog"""
if c in broker.exceptions:
ex = broker.exceptions.get(c)
ex = "Exception in {0} - {1}".format(dr.get_name(c), str(ex))
self.logit(ex, self.pid, self.user, "insights-run", logging.ERROR) | [
"def",
"log_exceptions",
"(",
"self",
",",
"c",
",",
"broker",
")",
":",
"if",
"c",
"in",
"broker",
".",
"exceptions",
":",
"ex",
"=",
"broker",
".",
"exceptions",
".",
"get",
"(",
"c",
")",
"ex",
"=",
"\"Exception in {0} - {1}\"",
".",
"format",
"(",
... | Gets exceptions to be logged and sends to logit function to be logged to syslog | [
"Gets",
"exceptions",
"to",
"be",
"logged",
"and",
"sends",
"to",
"logit",
"function",
"to",
"be",
"logged",
"to",
"syslog"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/formats/_syslog.py#L57-L63 |
225,890 | RedHatInsights/insights-core | insights/formats/_syslog.py | SysLogFormat.log_rule_info | def log_rule_info(self):
"""Collects rule information and send to logit function to log to syslog"""
for c in sorted(self.broker.get_by_type(rule), key=dr.get_name):
v = self.broker[c]
_type = v.get("type")
if _type:
if _type != "skip":
msg = "Running {0} ".format(dr.get_name(c))
self.logit(msg, self.pid, self.user, "insights-run", logging.INFO)
else:
msg = "Rule skipped {0} ".format(dr.get_name(c))
self.logit(msg, self.pid, self.user, "insights-run", logging.WARNING) | python | def log_rule_info(self):
"""Collects rule information and send to logit function to log to syslog"""
for c in sorted(self.broker.get_by_type(rule), key=dr.get_name):
v = self.broker[c]
_type = v.get("type")
if _type:
if _type != "skip":
msg = "Running {0} ".format(dr.get_name(c))
self.logit(msg, self.pid, self.user, "insights-run", logging.INFO)
else:
msg = "Rule skipped {0} ".format(dr.get_name(c))
self.logit(msg, self.pid, self.user, "insights-run", logging.WARNING) | [
"def",
"log_rule_info",
"(",
"self",
")",
":",
"for",
"c",
"in",
"sorted",
"(",
"self",
".",
"broker",
".",
"get_by_type",
"(",
"rule",
")",
",",
"key",
"=",
"dr",
".",
"get_name",
")",
":",
"v",
"=",
"self",
".",
"broker",
"[",
"c",
"]",
"_type"... | Collects rule information and send to logit function to log to syslog | [
"Collects",
"rule",
"information",
"and",
"send",
"to",
"logit",
"function",
"to",
"log",
"to",
"syslog"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/formats/_syslog.py#L72-L84 |
225,891 | RedHatInsights/insights-core | insights/client/data_collector.py | DataCollector._run_pre_command | def _run_pre_command(self, pre_cmd):
'''
Run a pre command to get external args for a command
'''
logger.debug('Executing pre-command: %s', pre_cmd)
try:
pre_proc = Popen(pre_cmd, stdout=PIPE, stderr=STDOUT, shell=True)
except OSError as err:
if err.errno == errno.ENOENT:
logger.debug('Command %s not found', pre_cmd)
return
stdout, stderr = pre_proc.communicate()
the_return_code = pre_proc.poll()
logger.debug("Pre-command results:")
logger.debug("STDOUT: %s", stdout)
logger.debug("STDERR: %s", stderr)
logger.debug("Return Code: %s", the_return_code)
if the_return_code != 0:
return []
if six.PY3:
stdout = stdout.decode('utf-8')
return stdout.splitlines() | python | def _run_pre_command(self, pre_cmd):
'''
Run a pre command to get external args for a command
'''
logger.debug('Executing pre-command: %s', pre_cmd)
try:
pre_proc = Popen(pre_cmd, stdout=PIPE, stderr=STDOUT, shell=True)
except OSError as err:
if err.errno == errno.ENOENT:
logger.debug('Command %s not found', pre_cmd)
return
stdout, stderr = pre_proc.communicate()
the_return_code = pre_proc.poll()
logger.debug("Pre-command results:")
logger.debug("STDOUT: %s", stdout)
logger.debug("STDERR: %s", stderr)
logger.debug("Return Code: %s", the_return_code)
if the_return_code != 0:
return []
if six.PY3:
stdout = stdout.decode('utf-8')
return stdout.splitlines() | [
"def",
"_run_pre_command",
"(",
"self",
",",
"pre_cmd",
")",
":",
"logger",
".",
"debug",
"(",
"'Executing pre-command: %s'",
",",
"pre_cmd",
")",
"try",
":",
"pre_proc",
"=",
"Popen",
"(",
"pre_cmd",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"STDOUT... | Run a pre command to get external args for a command | [
"Run",
"a",
"pre",
"command",
"to",
"get",
"external",
"args",
"for",
"a",
"command"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/data_collector.py#L51-L72 |
225,892 | RedHatInsights/insights-core | insights/client/data_collector.py | DataCollector._parse_file_spec | def _parse_file_spec(self, spec):
'''
Separate wildcard specs into more specs
'''
# separate wildcard specs into more specs
if '*' in spec['file']:
expanded_paths = _expand_paths(spec['file'])
if not expanded_paths:
return []
expanded_specs = []
for p in expanded_paths:
_spec = copy.copy(spec)
_spec['file'] = p
expanded_specs.append(_spec)
return expanded_specs
else:
return [spec] | python | def _parse_file_spec(self, spec):
'''
Separate wildcard specs into more specs
'''
# separate wildcard specs into more specs
if '*' in spec['file']:
expanded_paths = _expand_paths(spec['file'])
if not expanded_paths:
return []
expanded_specs = []
for p in expanded_paths:
_spec = copy.copy(spec)
_spec['file'] = p
expanded_specs.append(_spec)
return expanded_specs
else:
return [spec] | [
"def",
"_parse_file_spec",
"(",
"self",
",",
"spec",
")",
":",
"# separate wildcard specs into more specs",
"if",
"'*'",
"in",
"spec",
"[",
"'file'",
"]",
":",
"expanded_paths",
"=",
"_expand_paths",
"(",
"spec",
"[",
"'file'",
"]",
")",
"if",
"not",
"expanded... | Separate wildcard specs into more specs | [
"Separate",
"wildcard",
"specs",
"into",
"more",
"specs"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/data_collector.py#L74-L91 |
225,893 | RedHatInsights/insights-core | insights/client/data_collector.py | DataCollector._parse_glob_spec | def _parse_glob_spec(self, spec):
'''
Grab globs of things
'''
some_globs = glob.glob(spec['glob'])
if not some_globs:
return []
el_globs = []
for g in some_globs:
_spec = copy.copy(spec)
_spec['file'] = g
el_globs.append(_spec)
return el_globs | python | def _parse_glob_spec(self, spec):
'''
Grab globs of things
'''
some_globs = glob.glob(spec['glob'])
if not some_globs:
return []
el_globs = []
for g in some_globs:
_spec = copy.copy(spec)
_spec['file'] = g
el_globs.append(_spec)
return el_globs | [
"def",
"_parse_glob_spec",
"(",
"self",
",",
"spec",
")",
":",
"some_globs",
"=",
"glob",
".",
"glob",
"(",
"spec",
"[",
"'glob'",
"]",
")",
"if",
"not",
"some_globs",
":",
"return",
"[",
"]",
"el_globs",
"=",
"[",
"]",
"for",
"g",
"in",
"some_globs"... | Grab globs of things | [
"Grab",
"globs",
"of",
"things"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/data_collector.py#L93-L105 |
225,894 | RedHatInsights/insights-core | insights/client/data_collector.py | DataCollector.run_collection | def run_collection(self, conf, rm_conf, branch_info):
'''
Run specs and collect all the data
'''
if rm_conf is None:
rm_conf = {}
logger.debug('Beginning to run collection spec...')
exclude = None
if rm_conf:
try:
exclude = rm_conf['patterns']
logger.warn("WARNING: Skipping patterns found in remove.conf")
except LookupError:
logger.debug('Patterns section of remove.conf is empty.')
for c in conf['commands']:
# remember hostname archive path
if c.get('symbolic_name') == 'hostname':
self.hostname_path = os.path.join(
'insights_commands', mangle.mangle_command(c['command']))
rm_commands = rm_conf.get('commands', [])
if c['command'] in rm_commands or c.get('symbolic_name') in rm_commands:
logger.warn("WARNING: Skipping command %s", c['command'])
elif self.mountpoint == "/" or c.get("image"):
cmd_specs = self._parse_command_spec(c, conf['pre_commands'])
for s in cmd_specs:
cmd_spec = InsightsCommand(self.config, s, exclude, self.mountpoint)
self.archive.add_to_archive(cmd_spec)
for f in conf['files']:
rm_files = rm_conf.get('files', [])
if f['file'] in rm_files or f.get('symbolic_name') in rm_files:
logger.warn("WARNING: Skipping file %s", f['file'])
else:
file_specs = self._parse_file_spec(f)
for s in file_specs:
# filter files post-wildcard parsing
if s['file'] in rm_conf.get('files', []):
logger.warn("WARNING: Skipping file %s", s['file'])
else:
file_spec = InsightsFile(s, exclude, self.mountpoint)
self.archive.add_to_archive(file_spec)
if 'globs' in conf:
for g in conf['globs']:
glob_specs = self._parse_glob_spec(g)
for g in glob_specs:
if g['file'] in rm_conf.get('files', []):
logger.warn("WARNING: Skipping file %s", g)
else:
glob_spec = InsightsFile(g, exclude, self.mountpoint)
self.archive.add_to_archive(glob_spec)
logger.debug('Spec collection finished.')
# collect metadata
logger.debug('Collecting metadata...')
self._write_branch_info(branch_info)
logger.debug('Metadata collection finished.') | python | def run_collection(self, conf, rm_conf, branch_info):
'''
Run specs and collect all the data
'''
if rm_conf is None:
rm_conf = {}
logger.debug('Beginning to run collection spec...')
exclude = None
if rm_conf:
try:
exclude = rm_conf['patterns']
logger.warn("WARNING: Skipping patterns found in remove.conf")
except LookupError:
logger.debug('Patterns section of remove.conf is empty.')
for c in conf['commands']:
# remember hostname archive path
if c.get('symbolic_name') == 'hostname':
self.hostname_path = os.path.join(
'insights_commands', mangle.mangle_command(c['command']))
rm_commands = rm_conf.get('commands', [])
if c['command'] in rm_commands or c.get('symbolic_name') in rm_commands:
logger.warn("WARNING: Skipping command %s", c['command'])
elif self.mountpoint == "/" or c.get("image"):
cmd_specs = self._parse_command_spec(c, conf['pre_commands'])
for s in cmd_specs:
cmd_spec = InsightsCommand(self.config, s, exclude, self.mountpoint)
self.archive.add_to_archive(cmd_spec)
for f in conf['files']:
rm_files = rm_conf.get('files', [])
if f['file'] in rm_files or f.get('symbolic_name') in rm_files:
logger.warn("WARNING: Skipping file %s", f['file'])
else:
file_specs = self._parse_file_spec(f)
for s in file_specs:
# filter files post-wildcard parsing
if s['file'] in rm_conf.get('files', []):
logger.warn("WARNING: Skipping file %s", s['file'])
else:
file_spec = InsightsFile(s, exclude, self.mountpoint)
self.archive.add_to_archive(file_spec)
if 'globs' in conf:
for g in conf['globs']:
glob_specs = self._parse_glob_spec(g)
for g in glob_specs:
if g['file'] in rm_conf.get('files', []):
logger.warn("WARNING: Skipping file %s", g)
else:
glob_spec = InsightsFile(g, exclude, self.mountpoint)
self.archive.add_to_archive(glob_spec)
logger.debug('Spec collection finished.')
# collect metadata
logger.debug('Collecting metadata...')
self._write_branch_info(branch_info)
logger.debug('Metadata collection finished.') | [
"def",
"run_collection",
"(",
"self",
",",
"conf",
",",
"rm_conf",
",",
"branch_info",
")",
":",
"if",
"rm_conf",
"is",
"None",
":",
"rm_conf",
"=",
"{",
"}",
"logger",
".",
"debug",
"(",
"'Beginning to run collection spec...'",
")",
"exclude",
"=",
"None",
... | Run specs and collect all the data | [
"Run",
"specs",
"and",
"collect",
"all",
"the",
"data"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/data_collector.py#L148-L203 |
225,895 | RedHatInsights/insights-core | insights/client/data_collector.py | DataCollector.done | def done(self, conf, rm_conf):
"""
Do finalization stuff
"""
if self.config.obfuscate:
cleaner = SOSCleaner(quiet=True)
clean_opts = CleanOptions(
self.config, self.archive.tmp_dir, rm_conf, self.hostname_path)
fresh = cleaner.clean_report(clean_opts, self.archive.archive_dir)
if clean_opts.keyword_file is not None:
os.remove(clean_opts.keyword_file.name)
logger.warn("WARNING: Skipping keywords found in remove.conf")
return fresh[0]
return self.archive.create_tar_file() | python | def done(self, conf, rm_conf):
"""
Do finalization stuff
"""
if self.config.obfuscate:
cleaner = SOSCleaner(quiet=True)
clean_opts = CleanOptions(
self.config, self.archive.tmp_dir, rm_conf, self.hostname_path)
fresh = cleaner.clean_report(clean_opts, self.archive.archive_dir)
if clean_opts.keyword_file is not None:
os.remove(clean_opts.keyword_file.name)
logger.warn("WARNING: Skipping keywords found in remove.conf")
return fresh[0]
return self.archive.create_tar_file() | [
"def",
"done",
"(",
"self",
",",
"conf",
",",
"rm_conf",
")",
":",
"if",
"self",
".",
"config",
".",
"obfuscate",
":",
"cleaner",
"=",
"SOSCleaner",
"(",
"quiet",
"=",
"True",
")",
"clean_opts",
"=",
"CleanOptions",
"(",
"self",
".",
"config",
",",
"... | Do finalization stuff | [
"Do",
"finalization",
"stuff"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/data_collector.py#L205-L218 |
225,896 | RedHatInsights/insights-core | insights/specs/default.py | DefaultSpecs.sap_sid_nr | def sap_sid_nr(broker):
"""
Get the SID and Instance Number
Typical output of saphostctrl_listinstances::
# /usr/sap/hostctrl/exe/saphostctrl -function ListInstances
Inst Info : SR1 - 01 - liuxc-rhel7-hana-ent - 749, patch 418, changelist 1816226
Returns:
(list): List of tuple of SID and Instance Number.
"""
insts = broker[DefaultSpecs.saphostctrl_listinstances].content
hn = broker[DefaultSpecs.hostname].content[0].split('.')[0].strip()
results = set()
for ins in insts:
ins_splits = ins.split(' - ')
# Local Instance
if ins_splits[2].strip() == hn:
# (sid, nr)
results.add((ins_splits[0].split()[-1].lower(), ins_splits[1].strip()))
return list(results) | python | def sap_sid_nr(broker):
"""
Get the SID and Instance Number
Typical output of saphostctrl_listinstances::
# /usr/sap/hostctrl/exe/saphostctrl -function ListInstances
Inst Info : SR1 - 01 - liuxc-rhel7-hana-ent - 749, patch 418, changelist 1816226
Returns:
(list): List of tuple of SID and Instance Number.
"""
insts = broker[DefaultSpecs.saphostctrl_listinstances].content
hn = broker[DefaultSpecs.hostname].content[0].split('.')[0].strip()
results = set()
for ins in insts:
ins_splits = ins.split(' - ')
# Local Instance
if ins_splits[2].strip() == hn:
# (sid, nr)
results.add((ins_splits[0].split()[-1].lower(), ins_splits[1].strip()))
return list(results) | [
"def",
"sap_sid_nr",
"(",
"broker",
")",
":",
"insts",
"=",
"broker",
"[",
"DefaultSpecs",
".",
"saphostctrl_listinstances",
"]",
".",
"content",
"hn",
"=",
"broker",
"[",
"DefaultSpecs",
".",
"hostname",
"]",
".",
"content",
"[",
"0",
"]",
".",
"split",
... | Get the SID and Instance Number
Typical output of saphostctrl_listinstances::
# /usr/sap/hostctrl/exe/saphostctrl -function ListInstances
Inst Info : SR1 - 01 - liuxc-rhel7-hana-ent - 749, patch 418, changelist 1816226
Returns:
(list): List of tuple of SID and Instance Number. | [
"Get",
"the",
"SID",
"and",
"Instance",
"Number"
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/specs/default.py#L724-L745 |
225,897 | RedHatInsights/insights-core | insights/util/file_permissions.py | FilePermissions.from_dict | def from_dict(self, dirent):
"""
Create a new FilePermissions object from the given dictionary. This
works with the FileListing parser class, which has already done the
hard work of pulling many of these fields out. We create an object
with all the dictionary keys available as properties, and also split
the ``perms`` string up into owner, group
"""
# Check that we have at least as much data as the __init__ requires
for k in ['perms', 'owner', 'group', 'name', 'dir']:
if k not in dirent:
raise ValueError("Need required key '{k}'".format(k=k))
# Copy all values across
for k in dirent:
setattr(self, k, dirent[k])
# Create perms parts
self.perms_owner = self.perms[0:3]
self.perms_group = self.perms[3:6]
self.perms_other = self.perms[6:9]
return self | python | def from_dict(self, dirent):
"""
Create a new FilePermissions object from the given dictionary. This
works with the FileListing parser class, which has already done the
hard work of pulling many of these fields out. We create an object
with all the dictionary keys available as properties, and also split
the ``perms`` string up into owner, group
"""
# Check that we have at least as much data as the __init__ requires
for k in ['perms', 'owner', 'group', 'name', 'dir']:
if k not in dirent:
raise ValueError("Need required key '{k}'".format(k=k))
# Copy all values across
for k in dirent:
setattr(self, k, dirent[k])
# Create perms parts
self.perms_owner = self.perms[0:3]
self.perms_group = self.perms[3:6]
self.perms_other = self.perms[6:9]
return self | [
"def",
"from_dict",
"(",
"self",
",",
"dirent",
")",
":",
"# Check that we have at least as much data as the __init__ requires",
"for",
"k",
"in",
"[",
"'perms'",
",",
"'owner'",
",",
"'group'",
",",
"'name'",
",",
"'dir'",
"]",
":",
"if",
"k",
"not",
"in",
"d... | Create a new FilePermissions object from the given dictionary. This
works with the FileListing parser class, which has already done the
hard work of pulling many of these fields out. We create an object
with all the dictionary keys available as properties, and also split
the ``perms`` string up into owner, group | [
"Create",
"a",
"new",
"FilePermissions",
"object",
"from",
"the",
"given",
"dictionary",
".",
"This",
"works",
"with",
"the",
"FileListing",
"parser",
"class",
"which",
"has",
"already",
"done",
"the",
"hard",
"work",
"of",
"pulling",
"many",
"of",
"these",
... | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/file_permissions.py#L88-L107 |
225,898 | RedHatInsights/insights-core | insights/util/file_permissions.py | FilePermissions.owned_by | def owned_by(self, owner, also_check_group=False):
"""
Checks if the specified user or user and group own the file.
Args:
owner (str): the user (or group) name for which we ask about ownership
also_check_group (bool): if set to True, both user owner and group owner checked
if set to False, only user owner checked
Returns:
bool: True if owner of the file is the specified owner
"""
if also_check_group:
return self.owner == owner and self.group == owner
else:
return self.owner == owner | python | def owned_by(self, owner, also_check_group=False):
"""
Checks if the specified user or user and group own the file.
Args:
owner (str): the user (or group) name for which we ask about ownership
also_check_group (bool): if set to True, both user owner and group owner checked
if set to False, only user owner checked
Returns:
bool: True if owner of the file is the specified owner
"""
if also_check_group:
return self.owner == owner and self.group == owner
else:
return self.owner == owner | [
"def",
"owned_by",
"(",
"self",
",",
"owner",
",",
"also_check_group",
"=",
"False",
")",
":",
"if",
"also_check_group",
":",
"return",
"self",
".",
"owner",
"==",
"owner",
"and",
"self",
".",
"group",
"==",
"owner",
"else",
":",
"return",
"self",
".",
... | Checks if the specified user or user and group own the file.
Args:
owner (str): the user (or group) name for which we ask about ownership
also_check_group (bool): if set to True, both user owner and group owner checked
if set to False, only user owner checked
Returns:
bool: True if owner of the file is the specified owner | [
"Checks",
"if",
"the",
"specified",
"user",
"or",
"user",
"and",
"group",
"own",
"the",
"file",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/file_permissions.py#L109-L124 |
225,899 | RedHatInsights/insights-core | insights/parsers/multipath_conf.py | get_tree | def get_tree(root=None):
"""
This is a helper function to get a multipath configuration component for
your local machine or an archive. It's for use in interactive sessions.
"""
from insights import run
return run(MultipathConfTree, root=root).get(MultipathConfTree) | python | def get_tree(root=None):
"""
This is a helper function to get a multipath configuration component for
your local machine or an archive. It's for use in interactive sessions.
"""
from insights import run
return run(MultipathConfTree, root=root).get(MultipathConfTree) | [
"def",
"get_tree",
"(",
"root",
"=",
"None",
")",
":",
"from",
"insights",
"import",
"run",
"return",
"run",
"(",
"MultipathConfTree",
",",
"root",
"=",
"root",
")",
".",
"get",
"(",
"MultipathConfTree",
")"
] | This is a helper function to get a multipath configuration component for
your local machine or an archive. It's for use in interactive sessions. | [
"This",
"is",
"a",
"helper",
"function",
"to",
"get",
"a",
"multipath",
"configuration",
"component",
"for",
"your",
"local",
"machine",
"or",
"an",
"archive",
".",
"It",
"s",
"for",
"use",
"in",
"interactive",
"sessions",
"."
] | b57cbf8ed7c089672426ede0441e0a4f789ef4a1 | https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/multipath_conf.py#L188-L194 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.