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
partition
stringclasses
1 value
olitheolix/qtmacs
qtmacs/qtmacsmain_macros.py
RecordKeysequenceCore.qteStartRecordingHook
def qteStartRecordingHook(self, msgObj): """ Commence macro recording. Macros are recorded by connecting to the 'keypressed' signal it emits. If the recording has already commenced, or if this method was called during a macro replay, then return immediately. """ if self.qteRecording: self.qteMain.qteStatus('Macro recording already enabled') return # Update status flag. self.qteRecording = True # Reset the variables. self.qteMain.qteStatus('Macro recording started') self.recorded_keysequence = QtmacsKeysequence() # Connect the 'keypressed' and 'abort' signals. self.qteMain.qtesigKeyparsed.connect(self.qteKeyPress) self.qteMain.qtesigAbort.connect(self.qteStopRecordingHook)
python
def qteStartRecordingHook(self, msgObj): """ Commence macro recording. Macros are recorded by connecting to the 'keypressed' signal it emits. If the recording has already commenced, or if this method was called during a macro replay, then return immediately. """ if self.qteRecording: self.qteMain.qteStatus('Macro recording already enabled') return # Update status flag. self.qteRecording = True # Reset the variables. self.qteMain.qteStatus('Macro recording started') self.recorded_keysequence = QtmacsKeysequence() # Connect the 'keypressed' and 'abort' signals. self.qteMain.qtesigKeyparsed.connect(self.qteKeyPress) self.qteMain.qtesigAbort.connect(self.qteStopRecordingHook)
[ "def", "qteStartRecordingHook", "(", "self", ",", "msgObj", ")", ":", "if", "self", ".", "qteRecording", ":", "self", ".", "qteMain", ".", "qteStatus", "(", "'Macro recording already enabled'", ")", "return", "# Update status flag.", "self", ".", "qteRecording", "=", "True", "# Reset the variables.", "self", ".", "qteMain", ".", "qteStatus", "(", "'Macro recording started'", ")", "self", ".", "recorded_keysequence", "=", "QtmacsKeysequence", "(", ")", "# Connect the 'keypressed' and 'abort' signals.", "self", ".", "qteMain", ".", "qtesigKeyparsed", ".", "connect", "(", "self", ".", "qteKeyPress", ")", "self", ".", "qteMain", ".", "qtesigAbort", ".", "connect", "(", "self", ".", "qteStopRecordingHook", ")" ]
Commence macro recording. Macros are recorded by connecting to the 'keypressed' signal it emits. If the recording has already commenced, or if this method was called during a macro replay, then return immediately.
[ "Commence", "macro", "recording", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain_macros.py#L254-L277
train
olitheolix/qtmacs
qtmacs/qtmacsmain_macros.py
RecordKeysequenceCore.qteStopRecordingHook
def qteStopRecordingHook(self, msgObj): """ Stop macro recording. The signals from the event handler are disconnected and the event handler policy set to default. """ # Update status flag and disconnect all signals. if self.qteRecording: self.qteRecording = False self.qteMain.qteStatus('Macro recording stopped') self.qteMain.qtesigKeyparsed.disconnect(self.qteKeyPress) self.qteMain.qtesigAbort.disconnect(self.qteStopRecordingHook)
python
def qteStopRecordingHook(self, msgObj): """ Stop macro recording. The signals from the event handler are disconnected and the event handler policy set to default. """ # Update status flag and disconnect all signals. if self.qteRecording: self.qteRecording = False self.qteMain.qteStatus('Macro recording stopped') self.qteMain.qtesigKeyparsed.disconnect(self.qteKeyPress) self.qteMain.qtesigAbort.disconnect(self.qteStopRecordingHook)
[ "def", "qteStopRecordingHook", "(", "self", ",", "msgObj", ")", ":", "# Update status flag and disconnect all signals.", "if", "self", ".", "qteRecording", ":", "self", ".", "qteRecording", "=", "False", "self", ".", "qteMain", ".", "qteStatus", "(", "'Macro recording stopped'", ")", "self", ".", "qteMain", ".", "qtesigKeyparsed", ".", "disconnect", "(", "self", ".", "qteKeyPress", ")", "self", ".", "qteMain", ".", "qtesigAbort", ".", "disconnect", "(", "self", ".", "qteStopRecordingHook", ")" ]
Stop macro recording. The signals from the event handler are disconnected and the event handler policy set to default.
[ "Stop", "macro", "recording", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain_macros.py#L279-L291
train
olitheolix/qtmacs
qtmacs/qtmacsmain_macros.py
RecordKeysequenceCore.qteReplayKeysequenceHook
def qteReplayKeysequenceHook(self, msgObj): """ Replay the macro sequence. """ # Quit if there is nothing to replay. if self.recorded_keysequence.toString() == '': return # Stop the recording before the replay, if necessary. if self.qteRecording: return # Simulate the key presses. self.qteMain.qteEmulateKeypresses(self.recorded_keysequence)
python
def qteReplayKeysequenceHook(self, msgObj): """ Replay the macro sequence. """ # Quit if there is nothing to replay. if self.recorded_keysequence.toString() == '': return # Stop the recording before the replay, if necessary. if self.qteRecording: return # Simulate the key presses. self.qteMain.qteEmulateKeypresses(self.recorded_keysequence)
[ "def", "qteReplayKeysequenceHook", "(", "self", ",", "msgObj", ")", ":", "# Quit if there is nothing to replay.", "if", "self", ".", "recorded_keysequence", ".", "toString", "(", ")", "==", "''", ":", "return", "# Stop the recording before the replay, if necessary.", "if", "self", ".", "qteRecording", ":", "return", "# Simulate the key presses.", "self", ".", "qteMain", ".", "qteEmulateKeypresses", "(", "self", ".", "recorded_keysequence", ")" ]
Replay the macro sequence.
[ "Replay", "the", "macro", "sequence", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain_macros.py#L293-L307
train
olitheolix/qtmacs
qtmacs/qtmacsmain_macros.py
MacroProxyDemo.qteKeyPress
def qteKeyPress(self, msgObj): """ Record the key presses. """ # Unpack the data structure. (srcObj, keysequence, macroName) = msgObj.data # Return immediately if the key sequence does not specify a # macro (yet). if macroName is None: return # If the macro to repeat is this very macro then disable the # macro proxy, otherwise execute the macro that would have run # originally. if macroName == self.qteMacroName(): self.abort() else: msg = 'Executing macro {} through {}' msg = msg.format(macroName, self.qteMacroName()) self.qteMain.qteStatus(msg) self.qteMain.qteRunMacro(macroName, srcObj, keysequence)
python
def qteKeyPress(self, msgObj): """ Record the key presses. """ # Unpack the data structure. (srcObj, keysequence, macroName) = msgObj.data # Return immediately if the key sequence does not specify a # macro (yet). if macroName is None: return # If the macro to repeat is this very macro then disable the # macro proxy, otherwise execute the macro that would have run # originally. if macroName == self.qteMacroName(): self.abort() else: msg = 'Executing macro {} through {}' msg = msg.format(macroName, self.qteMacroName()) self.qteMain.qteStatus(msg) self.qteMain.qteRunMacro(macroName, srcObj, keysequence)
[ "def", "qteKeyPress", "(", "self", ",", "msgObj", ")", ":", "# Unpack the data structure.", "(", "srcObj", ",", "keysequence", ",", "macroName", ")", "=", "msgObj", ".", "data", "# Return immediately if the key sequence does not specify a", "# macro (yet).", "if", "macroName", "is", "None", ":", "return", "# If the macro to repeat is this very macro then disable the", "# macro proxy, otherwise execute the macro that would have run", "# originally.", "if", "macroName", "==", "self", ".", "qteMacroName", "(", ")", ":", "self", ".", "abort", "(", ")", "else", ":", "msg", "=", "'Executing macro {} through {}'", "msg", "=", "msg", ".", "format", "(", "macroName", ",", "self", ".", "qteMacroName", "(", ")", ")", "self", ".", "qteMain", ".", "qteStatus", "(", "msg", ")", "self", ".", "qteMain", ".", "qteRunMacro", "(", "macroName", ",", "srcObj", ",", "keysequence", ")" ]
Record the key presses.
[ "Record", "the", "key", "presses", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain_macros.py#L460-L481
train
olitheolix/qtmacs
qtmacs/qtmacsmain_macros.py
MacroProxyDemo.abort
def abort(self, msgObj): """ Disconnect all signals and turn macro processing in the event handler back on. """ self.qteMain.qtesigKeyparsed.disconnect(self.qteKeyPress) self.qteMain.qtesigAbort.disconnect(self.abort) self.qteActive = False self.qteMain.qteEnableMacroProcessing()
python
def abort(self, msgObj): """ Disconnect all signals and turn macro processing in the event handler back on. """ self.qteMain.qtesigKeyparsed.disconnect(self.qteKeyPress) self.qteMain.qtesigAbort.disconnect(self.abort) self.qteActive = False self.qteMain.qteEnableMacroProcessing()
[ "def", "abort", "(", "self", ",", "msgObj", ")", ":", "self", ".", "qteMain", ".", "qtesigKeyparsed", ".", "disconnect", "(", "self", ".", "qteKeyPress", ")", "self", ".", "qteMain", ".", "qtesigAbort", ".", "disconnect", "(", "self", ".", "abort", ")", "self", ".", "qteActive", "=", "False", "self", ".", "qteMain", ".", "qteEnableMacroProcessing", "(", ")" ]
Disconnect all signals and turn macro processing in the event handler back on.
[ "Disconnect", "all", "signals", "and", "turn", "macro", "processing", "in", "the", "event", "handler", "back", "on", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/qtmacsmain_macros.py#L483-L491
train
AASHE/python-membersuite-api-client
membersuite_api_client/utils.py
get_new_client
def get_new_client(request_session=False): """Return a new ConciergeClient, pulling secrets from the environment. """ from .client import ConciergeClient client = ConciergeClient(access_key=os.environ["MS_ACCESS_KEY"], secret_key=os.environ["MS_SECRET_KEY"], association_id=os.environ["MS_ASSOCIATION_ID"]) if request_session: client.request_session() return client
python
def get_new_client(request_session=False): """Return a new ConciergeClient, pulling secrets from the environment. """ from .client import ConciergeClient client = ConciergeClient(access_key=os.environ["MS_ACCESS_KEY"], secret_key=os.environ["MS_SECRET_KEY"], association_id=os.environ["MS_ASSOCIATION_ID"]) if request_session: client.request_session() return client
[ "def", "get_new_client", "(", "request_session", "=", "False", ")", ":", "from", ".", "client", "import", "ConciergeClient", "client", "=", "ConciergeClient", "(", "access_key", "=", "os", ".", "environ", "[", "\"MS_ACCESS_KEY\"", "]", ",", "secret_key", "=", "os", ".", "environ", "[", "\"MS_SECRET_KEY\"", "]", ",", "association_id", "=", "os", ".", "environ", "[", "\"MS_ASSOCIATION_ID\"", "]", ")", "if", "request_session", ":", "client", ".", "request_session", "(", ")", "return", "client" ]
Return a new ConciergeClient, pulling secrets from the environment.
[ "Return", "a", "new", "ConciergeClient", "pulling", "secrets", "from", "the", "environment", "." ]
221f5ed8bc7d4424237a4669c5af9edc11819ee9
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/utils.py#L44-L54
train
AASHE/python-membersuite-api-client
membersuite_api_client/utils.py
submit_msql_object_query
def submit_msql_object_query(object_query, client=None): """Submit `object_query` to MemberSuite, returning .models.MemberSuiteObjects. So this is a converter from MSQL to .models.MemberSuiteObjects. Returns query results as a list of MemberSuiteObjects. """ client = client or get_new_client() if not client.session_id: client.request_session() result = client.execute_object_query(object_query) execute_msql_result = result["body"]["ExecuteMSQLResult"] membersuite_object_list = [] if execute_msql_result["Success"]: result_value = execute_msql_result["ResultValue"] if result_value["ObjectSearchResult"]["Objects"]: # Multiple results. membersuite_object_list = [] for obj in (result_value["ObjectSearchResult"]["Objects"] ["MemberSuiteObject"]): membersuite_object = membersuite_object_factory(obj) membersuite_object_list.append(membersuite_object) elif result_value["SingleObject"]["ClassType"]: # Only one result. membersuite_object = membersuite_object_factory( execute_msql_result["ResultValue"]["SingleObject"]) membersuite_object_list.append(membersuite_object) elif (result_value["ObjectSearchResult"]["Objects"] is None and result_value["SingleObject"]["ClassType"] is None): raise NoResultsError(result=execute_msql_result) return membersuite_object_list else: # @TODO Fix - exposing only the first of possibly many errors here. raise ExecuteMSQLError(result=execute_msql_result)
python
def submit_msql_object_query(object_query, client=None): """Submit `object_query` to MemberSuite, returning .models.MemberSuiteObjects. So this is a converter from MSQL to .models.MemberSuiteObjects. Returns query results as a list of MemberSuiteObjects. """ client = client or get_new_client() if not client.session_id: client.request_session() result = client.execute_object_query(object_query) execute_msql_result = result["body"]["ExecuteMSQLResult"] membersuite_object_list = [] if execute_msql_result["Success"]: result_value = execute_msql_result["ResultValue"] if result_value["ObjectSearchResult"]["Objects"]: # Multiple results. membersuite_object_list = [] for obj in (result_value["ObjectSearchResult"]["Objects"] ["MemberSuiteObject"]): membersuite_object = membersuite_object_factory(obj) membersuite_object_list.append(membersuite_object) elif result_value["SingleObject"]["ClassType"]: # Only one result. membersuite_object = membersuite_object_factory( execute_msql_result["ResultValue"]["SingleObject"]) membersuite_object_list.append(membersuite_object) elif (result_value["ObjectSearchResult"]["Objects"] is None and result_value["SingleObject"]["ClassType"] is None): raise NoResultsError(result=execute_msql_result) return membersuite_object_list else: # @TODO Fix - exposing only the first of possibly many errors here. raise ExecuteMSQLError(result=execute_msql_result)
[ "def", "submit_msql_object_query", "(", "object_query", ",", "client", "=", "None", ")", ":", "client", "=", "client", "or", "get_new_client", "(", ")", "if", "not", "client", ".", "session_id", ":", "client", ".", "request_session", "(", ")", "result", "=", "client", ".", "execute_object_query", "(", "object_query", ")", "execute_msql_result", "=", "result", "[", "\"body\"", "]", "[", "\"ExecuteMSQLResult\"", "]", "membersuite_object_list", "=", "[", "]", "if", "execute_msql_result", "[", "\"Success\"", "]", ":", "result_value", "=", "execute_msql_result", "[", "\"ResultValue\"", "]", "if", "result_value", "[", "\"ObjectSearchResult\"", "]", "[", "\"Objects\"", "]", ":", "# Multiple results.", "membersuite_object_list", "=", "[", "]", "for", "obj", "in", "(", "result_value", "[", "\"ObjectSearchResult\"", "]", "[", "\"Objects\"", "]", "[", "\"MemberSuiteObject\"", "]", ")", ":", "membersuite_object", "=", "membersuite_object_factory", "(", "obj", ")", "membersuite_object_list", ".", "append", "(", "membersuite_object", ")", "elif", "result_value", "[", "\"SingleObject\"", "]", "[", "\"ClassType\"", "]", ":", "# Only one result.", "membersuite_object", "=", "membersuite_object_factory", "(", "execute_msql_result", "[", "\"ResultValue\"", "]", "[", "\"SingleObject\"", "]", ")", "membersuite_object_list", ".", "append", "(", "membersuite_object", ")", "elif", "(", "result_value", "[", "\"ObjectSearchResult\"", "]", "[", "\"Objects\"", "]", "is", "None", "and", "result_value", "[", "\"SingleObject\"", "]", "[", "\"ClassType\"", "]", "is", "None", ")", ":", "raise", "NoResultsError", "(", "result", "=", "execute_msql_result", ")", "return", "membersuite_object_list", "else", ":", "# @TODO Fix - exposing only the first of possibly many errors here.", "raise", "ExecuteMSQLError", "(", "result", "=", "execute_msql_result", ")" ]
Submit `object_query` to MemberSuite, returning .models.MemberSuiteObjects. So this is a converter from MSQL to .models.MemberSuiteObjects. Returns query results as a list of MemberSuiteObjects.
[ "Submit", "object_query", "to", "MemberSuite", "returning", ".", "models", ".", "MemberSuiteObjects", "." ]
221f5ed8bc7d4424237a4669c5af9edc11819ee9
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/utils.py#L57-L99
train
AASHE/python-membersuite-api-client
membersuite_api_client/utils.py
value_for_key
def value_for_key(membersuite_object_data, key): """Return the value for `key` of membersuite_object_data. """ key_value_dicts = { d['Key']: d['Value'] for d in membersuite_object_data["Fields"]["KeyValueOfstringanyType"]} return key_value_dicts[key]
python
def value_for_key(membersuite_object_data, key): """Return the value for `key` of membersuite_object_data. """ key_value_dicts = { d['Key']: d['Value'] for d in membersuite_object_data["Fields"]["KeyValueOfstringanyType"]} return key_value_dicts[key]
[ "def", "value_for_key", "(", "membersuite_object_data", ",", "key", ")", ":", "key_value_dicts", "=", "{", "d", "[", "'Key'", "]", ":", "d", "[", "'Value'", "]", "for", "d", "in", "membersuite_object_data", "[", "\"Fields\"", "]", "[", "\"KeyValueOfstringanyType\"", "]", "}", "return", "key_value_dicts", "[", "key", "]" ]
Return the value for `key` of membersuite_object_data.
[ "Return", "the", "value", "for", "key", "of", "membersuite_object_data", "." ]
221f5ed8bc7d4424237a4669c5af9edc11819ee9
https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/utils.py#L102-L108
train
OpenGov/og-python-utils
ogutils/loggers/flask.py
OrderedFormatsFormatter.usesTime
def usesTime(self, fmt=None): ''' Check if the format uses the creation time of the record. ''' if fmt is None: fmt = self._fmt if not isinstance(fmt, basestring): fmt = fmt[0] return fmt.find('%(asctime)') >= 0
python
def usesTime(self, fmt=None): ''' Check if the format uses the creation time of the record. ''' if fmt is None: fmt = self._fmt if not isinstance(fmt, basestring): fmt = fmt[0] return fmt.find('%(asctime)') >= 0
[ "def", "usesTime", "(", "self", ",", "fmt", "=", "None", ")", ":", "if", "fmt", "is", "None", ":", "fmt", "=", "self", ".", "_fmt", "if", "not", "isinstance", "(", "fmt", ",", "basestring", ")", ":", "fmt", "=", "fmt", "[", "0", "]", "return", "fmt", ".", "find", "(", "'%(asctime)'", ")", ">=", "0" ]
Check if the format uses the creation time of the record.
[ "Check", "if", "the", "format", "uses", "the", "creation", "time", "of", "the", "record", "." ]
00f44927383dd1bd6348f47302c4453d56963479
https://github.com/OpenGov/og-python-utils/blob/00f44927383dd1bd6348f47302c4453d56963479/ogutils/loggers/flask.py#L20-L28
train
olitheolix/qtmacs
qtmacs/auxiliary.py
qteIsQtmacsWidget
def qteIsQtmacsWidget(widgetObj): """ Determine if a widget is part of Qtmacs widget hierarchy. A widget belongs to the Qtmacs hierarchy if it, or one of its parents, has a "_qteAdmin" attribute (added via ``qteAddWidget``). Since every applet has this attribute is guaranteed that the function returns **True** if the widget is embedded inside somewhere. |Args| * ``widgetObj`` (**QWidget**): the widget to test. |Returns| * **bool**: **True** if the widget, or one of its ancestors in the Qt hierarchy have a '_qteAdmin' attribute. |Raises| * **None** """ if widgetObj is None: return False if hasattr(widgetObj, '_qteAdmin'): return True # Keep track of the already visited objects to avoid infinite loops. visited = [widgetObj] # Traverse the hierarchy until a parent features the '_qteAdmin' # attribute, the parent is None, or the parent is an already # visited widget. wid = widgetObj.parent() while wid not in visited: if hasattr(wid, '_qteAdmin'): return True elif wid is None: return False else: visited.append(wid) wid = wid.parent() return False
python
def qteIsQtmacsWidget(widgetObj): """ Determine if a widget is part of Qtmacs widget hierarchy. A widget belongs to the Qtmacs hierarchy if it, or one of its parents, has a "_qteAdmin" attribute (added via ``qteAddWidget``). Since every applet has this attribute is guaranteed that the function returns **True** if the widget is embedded inside somewhere. |Args| * ``widgetObj`` (**QWidget**): the widget to test. |Returns| * **bool**: **True** if the widget, or one of its ancestors in the Qt hierarchy have a '_qteAdmin' attribute. |Raises| * **None** """ if widgetObj is None: return False if hasattr(widgetObj, '_qteAdmin'): return True # Keep track of the already visited objects to avoid infinite loops. visited = [widgetObj] # Traverse the hierarchy until a parent features the '_qteAdmin' # attribute, the parent is None, or the parent is an already # visited widget. wid = widgetObj.parent() while wid not in visited: if hasattr(wid, '_qteAdmin'): return True elif wid is None: return False else: visited.append(wid) wid = wid.parent() return False
[ "def", "qteIsQtmacsWidget", "(", "widgetObj", ")", ":", "if", "widgetObj", "is", "None", ":", "return", "False", "if", "hasattr", "(", "widgetObj", ",", "'_qteAdmin'", ")", ":", "return", "True", "# Keep track of the already visited objects to avoid infinite loops.", "visited", "=", "[", "widgetObj", "]", "# Traverse the hierarchy until a parent features the '_qteAdmin'", "# attribute, the parent is None, or the parent is an already", "# visited widget.", "wid", "=", "widgetObj", ".", "parent", "(", ")", "while", "wid", "not", "in", "visited", ":", "if", "hasattr", "(", "wid", ",", "'_qteAdmin'", ")", ":", "return", "True", "elif", "wid", "is", "None", ":", "return", "False", "else", ":", "visited", ".", "append", "(", "wid", ")", "wid", "=", "wid", ".", "parent", "(", ")", "return", "False" ]
Determine if a widget is part of Qtmacs widget hierarchy. A widget belongs to the Qtmacs hierarchy if it, or one of its parents, has a "_qteAdmin" attribute (added via ``qteAddWidget``). Since every applet has this attribute is guaranteed that the function returns **True** if the widget is embedded inside somewhere. |Args| * ``widgetObj`` (**QWidget**): the widget to test. |Returns| * **bool**: **True** if the widget, or one of its ancestors in the Qt hierarchy have a '_qteAdmin' attribute. |Raises| * **None**
[ "Determine", "if", "a", "widget", "is", "part", "of", "Qtmacs", "widget", "hierarchy", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L1057-L1101
train
olitheolix/qtmacs
qtmacs/auxiliary.py
qteGetAppletFromWidget
def qteGetAppletFromWidget(widgetObj): """ Return the parent applet of ``widgetObj``. |Args| * ``widgetObj`` (**QWidget**): widget (if any) for which the containing applet is requested. |Returns| * **QtmacsApplet**: the applet containing ``widgetObj`` or **None**. |Raises| * **None** """ if widgetObj is None: return None if hasattr(widgetObj, '_qteAdmin'): return widgetObj._qteAdmin.qteApplet # Keep track of the already visited objects to avoid infinite loops. visited = [widgetObj] # Traverse the hierarchy until a parent features the '_qteAdmin' # attribute, the parent is None, or the parent is an already # visited widget. wid = widgetObj.parent() while wid not in visited: if hasattr(wid, '_qteAdmin'): return wid._qteAdmin.qteApplet elif wid is None: return None else: visited.append(wid) wid = wid.parent() return None
python
def qteGetAppletFromWidget(widgetObj): """ Return the parent applet of ``widgetObj``. |Args| * ``widgetObj`` (**QWidget**): widget (if any) for which the containing applet is requested. |Returns| * **QtmacsApplet**: the applet containing ``widgetObj`` or **None**. |Raises| * **None** """ if widgetObj is None: return None if hasattr(widgetObj, '_qteAdmin'): return widgetObj._qteAdmin.qteApplet # Keep track of the already visited objects to avoid infinite loops. visited = [widgetObj] # Traverse the hierarchy until a parent features the '_qteAdmin' # attribute, the parent is None, or the parent is an already # visited widget. wid = widgetObj.parent() while wid not in visited: if hasattr(wid, '_qteAdmin'): return wid._qteAdmin.qteApplet elif wid is None: return None else: visited.append(wid) wid = wid.parent() return None
[ "def", "qteGetAppletFromWidget", "(", "widgetObj", ")", ":", "if", "widgetObj", "is", "None", ":", "return", "None", "if", "hasattr", "(", "widgetObj", ",", "'_qteAdmin'", ")", ":", "return", "widgetObj", ".", "_qteAdmin", ".", "qteApplet", "# Keep track of the already visited objects to avoid infinite loops.", "visited", "=", "[", "widgetObj", "]", "# Traverse the hierarchy until a parent features the '_qteAdmin'", "# attribute, the parent is None, or the parent is an already", "# visited widget.", "wid", "=", "widgetObj", ".", "parent", "(", ")", "while", "wid", "not", "in", "visited", ":", "if", "hasattr", "(", "wid", ",", "'_qteAdmin'", ")", ":", "return", "wid", ".", "_qteAdmin", ".", "qteApplet", "elif", "wid", "is", "None", ":", "return", "None", "else", ":", "visited", ".", "append", "(", "wid", ")", "wid", "=", "wid", ".", "parent", "(", ")", "return", "None" ]
Return the parent applet of ``widgetObj``. |Args| * ``widgetObj`` (**QWidget**): widget (if any) for which the containing applet is requested. |Returns| * **QtmacsApplet**: the applet containing ``widgetObj`` or **None**. |Raises| * **None**
[ "Return", "the", "parent", "applet", "of", "widgetObj", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L1104-L1142
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsMessage.setHookName
def setHookName(self, name: str): """ Specify that the message will be delivered with the hook ``name``. """ self.isHook = True self.messengerName = name
python
def setHookName(self, name: str): """ Specify that the message will be delivered with the hook ``name``. """ self.isHook = True self.messengerName = name
[ "def", "setHookName", "(", "self", ",", "name", ":", "str", ")", ":", "self", ".", "isHook", "=", "True", "self", ".", "messengerName", "=", "name" ]
Specify that the message will be delivered with the hook ``name``.
[ "Specify", "that", "the", "message", "will", "be", "delivered", "with", "the", "hook", "name", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L86-L91
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsMessage.setSignalName
def setSignalName(self, name: str): """ Specify that the message will be delivered with the signal ``name``. """ self.isHook = False self.messengerName = name
python
def setSignalName(self, name: str): """ Specify that the message will be delivered with the signal ``name``. """ self.isHook = False self.messengerName = name
[ "def", "setSignalName", "(", "self", ",", "name", ":", "str", ")", ":", "self", ".", "isHook", "=", "False", "self", ".", "messengerName", "=", "name" ]
Specify that the message will be delivered with the signal ``name``.
[ "Specify", "that", "the", "message", "will", "be", "delivered", "with", "the", "signal", "name", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L94-L99
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsAdminStructure.qteSetKeyFilterPolicy
def qteSetKeyFilterPolicy(self, receiveBefore: bool=False, useQtmacs: bool=None, receiveAfter: bool=False): """ Set the policy on how Qtmacs filters keyboard events for a particular widgets. The options can be arbitrarily combined, eg. :: widget.qteSetKeyFilterPolicy(True, True, False) will first pass the event to the applet's ``keyPressEvent`` method and afterwards pass the same event to Qtmacs' keyboard filter. For all text-processing widgets (eg. ``QLineEdit``, ``QTextEdit``, ``QWebView``, etc.) it is almost always a good idea to use the default, ie. (False, True, False, False), which lets Qtmacs process everything. In this case the only way to interact with the widget is via macros (and the mouse). If ``receiveBefore`` and/or ``receiveAfter`` is set then ``qteKeyPressEventBefore`` and/or ``qteKeyPressEventAfter`` of the QtmacsApplet (not widget) is called to inspect the event. .. note:: The default behaviour is to let Qtmacs handle all keyboard events and interact with the applet only via macros. It may be more convenient for a programmer to handle keyboard events directly in the keyPressEvent routine, as is customary with Qt applications, but this compromises the customisation ability of Qtmacs. As a rule of thumb, applet classes should not implement keyPressEvent at all. However, since there is an exception to every rule Qtmacs allows it. .. note:: This method must be part of the qteAdmin object because which is attached to every object under the control of Qtmacs. |Args| * ``receiveBefore`` (**bool**): pass the keyEvent to the applet before Qtmacs processes it. * ``useQtmacs`` (**bool**): let Qtmacs parse the key. * ``receiveAfter`` (**bool**): pass the keyEvent to the applet after Qtmacs processed it. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Store key filter policy flags. self.filterKeyEvents = useQtmacs self.receiveBeforeQtmacsParser = receiveBefore self.receiveAfterQtmacsParser = receiveAfter
python
def qteSetKeyFilterPolicy(self, receiveBefore: bool=False, useQtmacs: bool=None, receiveAfter: bool=False): """ Set the policy on how Qtmacs filters keyboard events for a particular widgets. The options can be arbitrarily combined, eg. :: widget.qteSetKeyFilterPolicy(True, True, False) will first pass the event to the applet's ``keyPressEvent`` method and afterwards pass the same event to Qtmacs' keyboard filter. For all text-processing widgets (eg. ``QLineEdit``, ``QTextEdit``, ``QWebView``, etc.) it is almost always a good idea to use the default, ie. (False, True, False, False), which lets Qtmacs process everything. In this case the only way to interact with the widget is via macros (and the mouse). If ``receiveBefore`` and/or ``receiveAfter`` is set then ``qteKeyPressEventBefore`` and/or ``qteKeyPressEventAfter`` of the QtmacsApplet (not widget) is called to inspect the event. .. note:: The default behaviour is to let Qtmacs handle all keyboard events and interact with the applet only via macros. It may be more convenient for a programmer to handle keyboard events directly in the keyPressEvent routine, as is customary with Qt applications, but this compromises the customisation ability of Qtmacs. As a rule of thumb, applet classes should not implement keyPressEvent at all. However, since there is an exception to every rule Qtmacs allows it. .. note:: This method must be part of the qteAdmin object because which is attached to every object under the control of Qtmacs. |Args| * ``receiveBefore`` (**bool**): pass the keyEvent to the applet before Qtmacs processes it. * ``useQtmacs`` (**bool**): let Qtmacs parse the key. * ``receiveAfter`` (**bool**): pass the keyEvent to the applet after Qtmacs processed it. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Store key filter policy flags. self.filterKeyEvents = useQtmacs self.receiveBeforeQtmacsParser = receiveBefore self.receiveAfterQtmacsParser = receiveAfter
[ "def", "qteSetKeyFilterPolicy", "(", "self", ",", "receiveBefore", ":", "bool", "=", "False", ",", "useQtmacs", ":", "bool", "=", "None", ",", "receiveAfter", ":", "bool", "=", "False", ")", ":", "# Store key filter policy flags.", "self", ".", "filterKeyEvents", "=", "useQtmacs", "self", ".", "receiveBeforeQtmacsParser", "=", "receiveBefore", "self", ".", "receiveAfterQtmacsParser", "=", "receiveAfter" ]
Set the policy on how Qtmacs filters keyboard events for a particular widgets. The options can be arbitrarily combined, eg. :: widget.qteSetKeyFilterPolicy(True, True, False) will first pass the event to the applet's ``keyPressEvent`` method and afterwards pass the same event to Qtmacs' keyboard filter. For all text-processing widgets (eg. ``QLineEdit``, ``QTextEdit``, ``QWebView``, etc.) it is almost always a good idea to use the default, ie. (False, True, False, False), which lets Qtmacs process everything. In this case the only way to interact with the widget is via macros (and the mouse). If ``receiveBefore`` and/or ``receiveAfter`` is set then ``qteKeyPressEventBefore`` and/or ``qteKeyPressEventAfter`` of the QtmacsApplet (not widget) is called to inspect the event. .. note:: The default behaviour is to let Qtmacs handle all keyboard events and interact with the applet only via macros. It may be more convenient for a programmer to handle keyboard events directly in the keyPressEvent routine, as is customary with Qt applications, but this compromises the customisation ability of Qtmacs. As a rule of thumb, applet classes should not implement keyPressEvent at all. However, since there is an exception to every rule Qtmacs allows it. .. note:: This method must be part of the qteAdmin object because which is attached to every object under the control of Qtmacs. |Args| * ``receiveBefore`` (**bool**): pass the keyEvent to the applet before Qtmacs processes it. * ``useQtmacs`` (**bool**): let Qtmacs parse the key. * ``receiveAfter`` (**bool**): pass the keyEvent to the applet after Qtmacs processed it. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Set", "the", "policy", "on", "how", "Qtmacs", "filters", "keyboard", "events", "for", "a", "particular", "widgets", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L229-L287
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsKeysequence.appendQKeyEvent
def appendQKeyEvent(self, keyEvent: QtGui.QKeyEvent): """ Append another key to the key sequence represented by this object. |Args| * ``keyEvent`` (**QKeyEvent**): the key to add. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Store the QKeyEvent. self.keylistKeyEvent.append(keyEvent) # Convenience shortcuts. mod = keyEvent.modifiers() key = keyEvent.key() # Add the modifier and key to the list. The modifier is a # QFlag structure and must by typecast to an integer to avoid # difficulties with the hashing in the ``match`` routine of # the ``QtmacsKeymap`` object. self.keylistQtConstants.append((int(mod), key))
python
def appendQKeyEvent(self, keyEvent: QtGui.QKeyEvent): """ Append another key to the key sequence represented by this object. |Args| * ``keyEvent`` (**QKeyEvent**): the key to add. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Store the QKeyEvent. self.keylistKeyEvent.append(keyEvent) # Convenience shortcuts. mod = keyEvent.modifiers() key = keyEvent.key() # Add the modifier and key to the list. The modifier is a # QFlag structure and must by typecast to an integer to avoid # difficulties with the hashing in the ``match`` routine of # the ``QtmacsKeymap`` object. self.keylistQtConstants.append((int(mod), key))
[ "def", "appendQKeyEvent", "(", "self", ",", "keyEvent", ":", "QtGui", ".", "QKeyEvent", ")", ":", "# Store the QKeyEvent.", "self", ".", "keylistKeyEvent", ".", "append", "(", "keyEvent", ")", "# Convenience shortcuts.", "mod", "=", "keyEvent", ".", "modifiers", "(", ")", "key", "=", "keyEvent", ".", "key", "(", ")", "# Add the modifier and key to the list. The modifier is a", "# QFlag structure and must by typecast to an integer to avoid", "# difficulties with the hashing in the ``match`` routine of", "# the ``QtmacsKeymap`` object.", "self", ".", "keylistQtConstants", ".", "append", "(", "(", "int", "(", "mod", ")", ",", "key", ")", ")" ]
Append another key to the key sequence represented by this object. |Args| * ``keyEvent`` (**QKeyEvent**): the key to add. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Append", "another", "key", "to", "the", "key", "sequence", "represented", "by", "this", "object", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L694-L721
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsKeymap.qteInsertKey
def qteInsertKey(self, keysequence: QtmacsKeysequence, macroName: str): """ Insert a new key into the key map and associate it with a macro. If the key sequence is already associated with a macro then it will be overwritten. |Args| * ``keysequence`` (**QtmacsKeysequence**): associate a macro with a key sequence in this key map. * ``macroName`` (**str**): macro name. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Get a dedicated reference to self to facilitate traversing # through the key map. keyMap = self # Get the key sequence as a list of tuples, where each tuple # contains the the control modifier and the key code, and both # are specified as Qt constants. keysequence = keysequence.toQtKeylist() # Traverse the shortcut sequence and generate new keys as # necessary. for key in keysequence[:-1]: # If the key does not yet exist add an empty dictionary # (it will be filled later). if key not in keyMap: keyMap[key] = {} # Similarly, if the key does exist but references anything # other than a dictionary (eg. a previously installed # ``QtmacdMacro`` instance), then delete it. if not isinstance(keyMap[key], dict): keyMap[key] = {} # Go one level down in the key-map tree. keyMap = keyMap[key] # Assign the new macro object associated with this key. keyMap[keysequence[-1]] = macroName
python
def qteInsertKey(self, keysequence: QtmacsKeysequence, macroName: str): """ Insert a new key into the key map and associate it with a macro. If the key sequence is already associated with a macro then it will be overwritten. |Args| * ``keysequence`` (**QtmacsKeysequence**): associate a macro with a key sequence in this key map. * ``macroName`` (**str**): macro name. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Get a dedicated reference to self to facilitate traversing # through the key map. keyMap = self # Get the key sequence as a list of tuples, where each tuple # contains the the control modifier and the key code, and both # are specified as Qt constants. keysequence = keysequence.toQtKeylist() # Traverse the shortcut sequence and generate new keys as # necessary. for key in keysequence[:-1]: # If the key does not yet exist add an empty dictionary # (it will be filled later). if key not in keyMap: keyMap[key] = {} # Similarly, if the key does exist but references anything # other than a dictionary (eg. a previously installed # ``QtmacdMacro`` instance), then delete it. if not isinstance(keyMap[key], dict): keyMap[key] = {} # Go one level down in the key-map tree. keyMap = keyMap[key] # Assign the new macro object associated with this key. keyMap[keysequence[-1]] = macroName
[ "def", "qteInsertKey", "(", "self", ",", "keysequence", ":", "QtmacsKeysequence", ",", "macroName", ":", "str", ")", ":", "# Get a dedicated reference to self to facilitate traversing", "# through the key map.", "keyMap", "=", "self", "# Get the key sequence as a list of tuples, where each tuple", "# contains the the control modifier and the key code, and both", "# are specified as Qt constants.", "keysequence", "=", "keysequence", ".", "toQtKeylist", "(", ")", "# Traverse the shortcut sequence and generate new keys as", "# necessary.", "for", "key", "in", "keysequence", "[", ":", "-", "1", "]", ":", "# If the key does not yet exist add an empty dictionary", "# (it will be filled later).", "if", "key", "not", "in", "keyMap", ":", "keyMap", "[", "key", "]", "=", "{", "}", "# Similarly, if the key does exist but references anything", "# other than a dictionary (eg. a previously installed", "# ``QtmacdMacro`` instance), then delete it.", "if", "not", "isinstance", "(", "keyMap", "[", "key", "]", ",", "dict", ")", ":", "keyMap", "[", "key", "]", "=", "{", "}", "# Go one level down in the key-map tree.", "keyMap", "=", "keyMap", "[", "key", "]", "# Assign the new macro object associated with this key.", "keyMap", "[", "keysequence", "[", "-", "1", "]", "]", "=", "macroName" ]
Insert a new key into the key map and associate it with a macro. If the key sequence is already associated with a macro then it will be overwritten. |Args| * ``keysequence`` (**QtmacsKeysequence**): associate a macro with a key sequence in this key map. * ``macroName`` (**str**): macro name. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Insert", "a", "new", "key", "into", "the", "key", "map", "and", "associate", "it", "with", "a", "macro", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L873-L922
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsKeymap.qteRemoveKey
def qteRemoveKey(self, keysequence: QtmacsKeysequence): """ Remove ``keysequence`` from this key map. |Args| * ``keysequence`` (**QtmacsKeysequence**): key sequence to remove from this key map. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Get a dedicated reference to self to facilitate traversing # through the key map. keyMap = self # Keep a reference to the root element in the key map. keyMapRef = keyMap # Get the key sequence as a list of tuples, where each tuple # contains the the control modifier and the key code, and both # are specified as Qt constants. keysequence = keysequence.toQtKeylist() # ------------------------------------------------------------ # Remove the leaf element from the tree. # ------------------------------------------------------------ for key in keysequence[:-1]: # Quit if the key does not exist. This can happen if the # user tries to remove a key that has never been # registered. if key not in keyMap: return # Go one level down in the key-map tree. keyMap = keyMap[key] # The specified key sequence does not exist if the leaf # element (ie. last entry in the key sequence) is missing. if keysequence[-1] not in keyMap: return else: # Remove the leaf. keyMap.pop(keysequence[-1]) # ------------------------------------------------------------ # Prune the prefix path defined by ``keysequence`` and remove # all empty dictionaries. Start at the leaf level. # ------------------------------------------------------------ # Drop the last element in the key sequence, because it was # removed in the above code fragment already. keysequence = keysequence[:-1] # Now successively remove the key sequence in reverse order. while(len(keysequence)): # Start at the root and move to the last branch level # before the leaf level. keyMap = keyMapRef for key in keysequence[:-1]: keyMap = keyMap[key] # If the leaf is a non-empty dictionary then another key # with the same prefix still exists. In this case do # nothing. However, if the leaf is now empty it must be # removed. if len(keyMap[key]): return else: keyMap.pop(key)
python
def qteRemoveKey(self, keysequence: QtmacsKeysequence): """ Remove ``keysequence`` from this key map. |Args| * ``keysequence`` (**QtmacsKeysequence**): key sequence to remove from this key map. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Get a dedicated reference to self to facilitate traversing # through the key map. keyMap = self # Keep a reference to the root element in the key map. keyMapRef = keyMap # Get the key sequence as a list of tuples, where each tuple # contains the the control modifier and the key code, and both # are specified as Qt constants. keysequence = keysequence.toQtKeylist() # ------------------------------------------------------------ # Remove the leaf element from the tree. # ------------------------------------------------------------ for key in keysequence[:-1]: # Quit if the key does not exist. This can happen if the # user tries to remove a key that has never been # registered. if key not in keyMap: return # Go one level down in the key-map tree. keyMap = keyMap[key] # The specified key sequence does not exist if the leaf # element (ie. last entry in the key sequence) is missing. if keysequence[-1] not in keyMap: return else: # Remove the leaf. keyMap.pop(keysequence[-1]) # ------------------------------------------------------------ # Prune the prefix path defined by ``keysequence`` and remove # all empty dictionaries. Start at the leaf level. # ------------------------------------------------------------ # Drop the last element in the key sequence, because it was # removed in the above code fragment already. keysequence = keysequence[:-1] # Now successively remove the key sequence in reverse order. while(len(keysequence)): # Start at the root and move to the last branch level # before the leaf level. keyMap = keyMapRef for key in keysequence[:-1]: keyMap = keyMap[key] # If the leaf is a non-empty dictionary then another key # with the same prefix still exists. In this case do # nothing. However, if the leaf is now empty it must be # removed. if len(keyMap[key]): return else: keyMap.pop(key)
[ "def", "qteRemoveKey", "(", "self", ",", "keysequence", ":", "QtmacsKeysequence", ")", ":", "# Get a dedicated reference to self to facilitate traversing", "# through the key map.", "keyMap", "=", "self", "# Keep a reference to the root element in the key map.", "keyMapRef", "=", "keyMap", "# Get the key sequence as a list of tuples, where each tuple", "# contains the the control modifier and the key code, and both", "# are specified as Qt constants.", "keysequence", "=", "keysequence", ".", "toQtKeylist", "(", ")", "# ------------------------------------------------------------", "# Remove the leaf element from the tree.", "# ------------------------------------------------------------", "for", "key", "in", "keysequence", "[", ":", "-", "1", "]", ":", "# Quit if the key does not exist. This can happen if the", "# user tries to remove a key that has never been", "# registered.", "if", "key", "not", "in", "keyMap", ":", "return", "# Go one level down in the key-map tree.", "keyMap", "=", "keyMap", "[", "key", "]", "# The specified key sequence does not exist if the leaf", "# element (ie. last entry in the key sequence) is missing.", "if", "keysequence", "[", "-", "1", "]", "not", "in", "keyMap", ":", "return", "else", ":", "# Remove the leaf.", "keyMap", ".", "pop", "(", "keysequence", "[", "-", "1", "]", ")", "# ------------------------------------------------------------", "# Prune the prefix path defined by ``keysequence`` and remove", "# all empty dictionaries. Start at the leaf level.", "# ------------------------------------------------------------", "# Drop the last element in the key sequence, because it was", "# removed in the above code fragment already.", "keysequence", "=", "keysequence", "[", ":", "-", "1", "]", "# Now successively remove the key sequence in reverse order.", "while", "(", "len", "(", "keysequence", ")", ")", ":", "# Start at the root and move to the last branch level", "# before the leaf level.", "keyMap", "=", "keyMapRef", "for", "key", "in", "keysequence", "[", ":", "-", "1", "]", ":", "keyMap", "=", "keyMap", "[", "key", "]", "# If the leaf is a non-empty dictionary then another key", "# with the same prefix still exists. In this case do", "# nothing. However, if the leaf is now empty it must be", "# removed.", "if", "len", "(", "keyMap", "[", "key", "]", ")", ":", "return", "else", ":", "keyMap", ".", "pop", "(", "key", ")" ]
Remove ``keysequence`` from this key map. |Args| * ``keysequence`` (**QtmacsKeysequence**): key sequence to remove from this key map. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Remove", "keysequence", "from", "this", "key", "map", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L925-L999
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsKeymap.match
def match(self, keysequence: QtmacsKeysequence): """ Look up the key sequence in key map. If ``keysequence`` leads to a macro in the key map represented by this object then the method returns ``(macroName, True)``. If it does not lead to a macro but is nonetheless valid (ie. the sequence is still incomplete), then it returns ``(None, True)``. Finally, if the sequence cannot lead to a macro because it is invalid then the return value is ``(None, False)``. |Args| * ``keysequence`` (**QtmacsKeysequence**): associate a macro with a key sequence in this key map. * ``macroName`` (**str**): macro name. |Returns| (**str**: macro name, **bool**: partial match) |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ try: # Look up the ``keysequence`` in the current key map (ie. # this very object which inherits from ``dict``). If # ``keysequence`` does not lead to a valid macro then # return **None**. macroName = self for _ in keysequence.toQtKeylist(): macroName = macroName[_] except KeyError: # This error occurs if the keyboard sequence does not lead # to any macro and is therefore invalid. return (None, False) # At this point we know that the key sequence entered so far # exists. Two possibilities from here on forward: 1) the key # sequence now points to a macro or 2) the key sequence is # still incomplete. if isinstance(macroName, dict): # Another dictionary --> key sequence is still incomplete. return (None, True) else: # Macro object --> return it. return (macroName, True)
python
def match(self, keysequence: QtmacsKeysequence): """ Look up the key sequence in key map. If ``keysequence`` leads to a macro in the key map represented by this object then the method returns ``(macroName, True)``. If it does not lead to a macro but is nonetheless valid (ie. the sequence is still incomplete), then it returns ``(None, True)``. Finally, if the sequence cannot lead to a macro because it is invalid then the return value is ``(None, False)``. |Args| * ``keysequence`` (**QtmacsKeysequence**): associate a macro with a key sequence in this key map. * ``macroName`` (**str**): macro name. |Returns| (**str**: macro name, **bool**: partial match) |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ try: # Look up the ``keysequence`` in the current key map (ie. # this very object which inherits from ``dict``). If # ``keysequence`` does not lead to a valid macro then # return **None**. macroName = self for _ in keysequence.toQtKeylist(): macroName = macroName[_] except KeyError: # This error occurs if the keyboard sequence does not lead # to any macro and is therefore invalid. return (None, False) # At this point we know that the key sequence entered so far # exists. Two possibilities from here on forward: 1) the key # sequence now points to a macro or 2) the key sequence is # still incomplete. if isinstance(macroName, dict): # Another dictionary --> key sequence is still incomplete. return (None, True) else: # Macro object --> return it. return (macroName, True)
[ "def", "match", "(", "self", ",", "keysequence", ":", "QtmacsKeysequence", ")", ":", "try", ":", "# Look up the ``keysequence`` in the current key map (ie.", "# this very object which inherits from ``dict``). If", "# ``keysequence`` does not lead to a valid macro then", "# return **None**.", "macroName", "=", "self", "for", "_", "in", "keysequence", ".", "toQtKeylist", "(", ")", ":", "macroName", "=", "macroName", "[", "_", "]", "except", "KeyError", ":", "# This error occurs if the keyboard sequence does not lead", "# to any macro and is therefore invalid.", "return", "(", "None", ",", "False", ")", "# At this point we know that the key sequence entered so far", "# exists. Two possibilities from here on forward: 1) the key", "# sequence now points to a macro or 2) the key sequence is", "# still incomplete.", "if", "isinstance", "(", "macroName", ",", "dict", ")", ":", "# Another dictionary --> key sequence is still incomplete.", "return", "(", "None", ",", "True", ")", "else", ":", "# Macro object --> return it.", "return", "(", "macroName", ",", "True", ")" ]
Look up the key sequence in key map. If ``keysequence`` leads to a macro in the key map represented by this object then the method returns ``(macroName, True)``. If it does not lead to a macro but is nonetheless valid (ie. the sequence is still incomplete), then it returns ``(None, True)``. Finally, if the sequence cannot lead to a macro because it is invalid then the return value is ``(None, False)``. |Args| * ``keysequence`` (**QtmacsKeysequence**): associate a macro with a key sequence in this key map. * ``macroName`` (**str**): macro name. |Returns| (**str**: macro name, **bool**: partial match) |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Look", "up", "the", "key", "sequence", "in", "key", "map", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L1002-L1050
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsModeBar._qteGetLabelInstance
def _qteGetLabelInstance(self): """ Return an instance of a ``QLabel`` with the correct color scheme. |Args| * **None** |Returns| * **QLabel** |Raises| * **None** """ # Create a label with the proper colour appearance. layout = self.layout() label = QtGui.QLabel(self) style = 'QLabel { background-color : white; color : blue; }' label.setStyleSheet(style) return label
python
def _qteGetLabelInstance(self): """ Return an instance of a ``QLabel`` with the correct color scheme. |Args| * **None** |Returns| * **QLabel** |Raises| * **None** """ # Create a label with the proper colour appearance. layout = self.layout() label = QtGui.QLabel(self) style = 'QLabel { background-color : white; color : blue; }' label.setStyleSheet(style) return label
[ "def", "_qteGetLabelInstance", "(", "self", ")", ":", "# Create a label with the proper colour appearance.", "layout", "=", "self", ".", "layout", "(", ")", "label", "=", "QtGui", ".", "QLabel", "(", "self", ")", "style", "=", "'QLabel { background-color : white; color : blue; }'", "label", ".", "setStyleSheet", "(", "style", ")", "return", "label" ]
Return an instance of a ``QLabel`` with the correct color scheme. |Args| * **None** |Returns| * **QLabel** |Raises| * **None**
[ "Return", "an", "instance", "of", "a", "QLabel", "with", "the", "correct", "color", "scheme", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L1190-L1211
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsModeBar._qteUpdateLabelWidths
def _qteUpdateLabelWidths(self): """ Ensure all but the last ``QLabel`` are only as wide as necessary. The width of the last label is manually set to a large value to ensure that it stretches as much as possible. The height of all widgets is also set appropriately. The method also takes care or rearranging the widgets in the correct order, ie. in the order specified by ``self._qteModeList``. |Args| * **None** |Returns| * **None** |Raises| * **None** """ layout = self.layout() # Remove all labels from the list and add them again in the # new order. for ii in range(layout.count()): label = layout.itemAt(ii) layout.removeItem(label) # Add all labels and ensure they have appropriate width. for item in self._qteModeList: label = item[2] width = label.fontMetrics().size(0, str(item[1])).width() label.setMaximumWidth(width) label.setMinimumWidth(width) layout.addWidget(label) # Remove the width constraint from the last label so that # it can expand to the right. _, _, label = self._qteModeList[-1] label.setMaximumWidth(1600000)
python
def _qteUpdateLabelWidths(self): """ Ensure all but the last ``QLabel`` are only as wide as necessary. The width of the last label is manually set to a large value to ensure that it stretches as much as possible. The height of all widgets is also set appropriately. The method also takes care or rearranging the widgets in the correct order, ie. in the order specified by ``self._qteModeList``. |Args| * **None** |Returns| * **None** |Raises| * **None** """ layout = self.layout() # Remove all labels from the list and add them again in the # new order. for ii in range(layout.count()): label = layout.itemAt(ii) layout.removeItem(label) # Add all labels and ensure they have appropriate width. for item in self._qteModeList: label = item[2] width = label.fontMetrics().size(0, str(item[1])).width() label.setMaximumWidth(width) label.setMinimumWidth(width) layout.addWidget(label) # Remove the width constraint from the last label so that # it can expand to the right. _, _, label = self._qteModeList[-1] label.setMaximumWidth(1600000)
[ "def", "_qteUpdateLabelWidths", "(", "self", ")", ":", "layout", "=", "self", ".", "layout", "(", ")", "# Remove all labels from the list and add them again in the", "# new order.", "for", "ii", "in", "range", "(", "layout", ".", "count", "(", ")", ")", ":", "label", "=", "layout", ".", "itemAt", "(", "ii", ")", "layout", ".", "removeItem", "(", "label", ")", "# Add all labels and ensure they have appropriate width.", "for", "item", "in", "self", ".", "_qteModeList", ":", "label", "=", "item", "[", "2", "]", "width", "=", "label", ".", "fontMetrics", "(", ")", ".", "size", "(", "0", ",", "str", "(", "item", "[", "1", "]", ")", ")", ".", "width", "(", ")", "label", ".", "setMaximumWidth", "(", "width", ")", "label", ".", "setMinimumWidth", "(", "width", ")", "layout", ".", "addWidget", "(", "label", ")", "# Remove the width constraint from the last label so that", "# it can expand to the right.", "_", ",", "_", ",", "label", "=", "self", ".", "_qteModeList", "[", "-", "1", "]", "label", ".", "setMaximumWidth", "(", "1600000", ")" ]
Ensure all but the last ``QLabel`` are only as wide as necessary. The width of the last label is manually set to a large value to ensure that it stretches as much as possible. The height of all widgets is also set appropriately. The method also takes care or rearranging the widgets in the correct order, ie. in the order specified by ``self._qteModeList``. |Args| * **None** |Returns| * **None** |Raises| * **None**
[ "Ensure", "all", "but", "the", "last", "QLabel", "are", "only", "as", "wide", "as", "necessary", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L1213-L1253
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsModeBar.qteGetMode
def qteGetMode(self, mode: str): """ Return a tuple containing the ``mode``, its value, and its associated ``QLabel`` instance. |Args| * ``mode`` (**str**): size and position of new window. |Returns| * (**str**, **object**, **QLabel**: (mode, value, label). |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ for item in self._qteModeList: if item[0] == mode: return item return None
python
def qteGetMode(self, mode: str): """ Return a tuple containing the ``mode``, its value, and its associated ``QLabel`` instance. |Args| * ``mode`` (**str**): size and position of new window. |Returns| * (**str**, **object**, **QLabel**: (mode, value, label). |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ for item in self._qteModeList: if item[0] == mode: return item return None
[ "def", "qteGetMode", "(", "self", ",", "mode", ":", "str", ")", ":", "for", "item", "in", "self", ".", "_qteModeList", ":", "if", "item", "[", "0", "]", "==", "mode", ":", "return", "item", "return", "None" ]
Return a tuple containing the ``mode``, its value, and its associated ``QLabel`` instance. |Args| * ``mode`` (**str**): size and position of new window. |Returns| * (**str**, **object**, **QLabel**: (mode, value, label). |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Return", "a", "tuple", "containing", "the", "mode", "its", "value", "and", "its", "associated", "QLabel", "instance", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L1256-L1276
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsModeBar.qteAddMode
def qteAddMode(self, mode: str, value): """ Append label for ``mode`` and display ``value`` on it. |Args| * ``mode`` (**str**): mode of mode. * ``value`` (**object**): value of mode. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Add the label to the layout and the local mode list. label = self._qteGetLabelInstance() label.setText(value) self._qteModeList.append((mode, value, label)) self._qteUpdateLabelWidths()
python
def qteAddMode(self, mode: str, value): """ Append label for ``mode`` and display ``value`` on it. |Args| * ``mode`` (**str**): mode of mode. * ``value`` (**object**): value of mode. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Add the label to the layout and the local mode list. label = self._qteGetLabelInstance() label.setText(value) self._qteModeList.append((mode, value, label)) self._qteUpdateLabelWidths()
[ "def", "qteAddMode", "(", "self", ",", "mode", ":", "str", ",", "value", ")", ":", "# Add the label to the layout and the local mode list.", "label", "=", "self", ".", "_qteGetLabelInstance", "(", ")", "label", ".", "setText", "(", "value", ")", "self", ".", "_qteModeList", ".", "append", "(", "(", "mode", ",", "value", ",", "label", ")", ")", "self", ".", "_qteUpdateLabelWidths", "(", ")" ]
Append label for ``mode`` and display ``value`` on it. |Args| * ``mode`` (**str**): mode of mode. * ``value`` (**object**): value of mode. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Append", "label", "for", "mode", "and", "display", "value", "on", "it", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L1279-L1300
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsModeBar.qteChangeModeValue
def qteChangeModeValue(self, mode: str, value): """ Change the value of ``mode`` to ``value``. If ``mode`` does not exist then nothing happens and the method returns **False**, otherwise **True**. |Args| * ``mode`` (**str**): mode of mode. * ``value`` (**object**): value of mode. |Returns| * **bool**: **True** if the item was removed and **False** if there was an error (most likely ``mode`` does not exist). |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Search through the list for ``mode``. for idx, item in enumerate(self._qteModeList): if item[0] == mode: # Update the displayed value in the label. label = item[2] label.setText(value) # Overwrite the old data record with the updated one # and adjust the widths of the modes. self._qteModeList[idx] = (mode, value, label) self._qteUpdateLabelWidths() return True return False
python
def qteChangeModeValue(self, mode: str, value): """ Change the value of ``mode`` to ``value``. If ``mode`` does not exist then nothing happens and the method returns **False**, otherwise **True**. |Args| * ``mode`` (**str**): mode of mode. * ``value`` (**object**): value of mode. |Returns| * **bool**: **True** if the item was removed and **False** if there was an error (most likely ``mode`` does not exist). |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Search through the list for ``mode``. for idx, item in enumerate(self._qteModeList): if item[0] == mode: # Update the displayed value in the label. label = item[2] label.setText(value) # Overwrite the old data record with the updated one # and adjust the widths of the modes. self._qteModeList[idx] = (mode, value, label) self._qteUpdateLabelWidths() return True return False
[ "def", "qteChangeModeValue", "(", "self", ",", "mode", ":", "str", ",", "value", ")", ":", "# Search through the list for ``mode``.", "for", "idx", ",", "item", "in", "enumerate", "(", "self", ".", "_qteModeList", ")", ":", "if", "item", "[", "0", "]", "==", "mode", ":", "# Update the displayed value in the label.", "label", "=", "item", "[", "2", "]", "label", ".", "setText", "(", "value", ")", "# Overwrite the old data record with the updated one", "# and adjust the widths of the modes.", "self", ".", "_qteModeList", "[", "idx", "]", "=", "(", "mode", ",", "value", ",", "label", ")", "self", ".", "_qteUpdateLabelWidths", "(", ")", "return", "True", "return", "False" ]
Change the value of ``mode`` to ``value``. If ``mode`` does not exist then nothing happens and the method returns **False**, otherwise **True**. |Args| * ``mode`` (**str**): mode of mode. * ``value`` (**object**): value of mode. |Returns| * **bool**: **True** if the item was removed and **False** if there was an error (most likely ``mode`` does not exist). |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Change", "the", "value", "of", "mode", "to", "value", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L1303-L1336
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsModeBar.qteInsertMode
def qteInsertMode(self, pos: int, mode: str, value): """ Insert ``mode`` at position ``pos``. If ``pos`` is negative then this is equivalent to ``pos=0``. If it is larger than the number of modes in the list then it is appended as the last element. |Args| * ``pos`` (**int**): insertion point. * ``mode`` (**str**): name of mode. * ``value`` (**object**) value associated with ``mode``. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Add the label to the list. label = self._qteGetLabelInstance() label.setText(value) self._qteModeList.insert(pos, (mode, value, label)) self._qteUpdateLabelWidths()
python
def qteInsertMode(self, pos: int, mode: str, value): """ Insert ``mode`` at position ``pos``. If ``pos`` is negative then this is equivalent to ``pos=0``. If it is larger than the number of modes in the list then it is appended as the last element. |Args| * ``pos`` (**int**): insertion point. * ``mode`` (**str**): name of mode. * ``value`` (**object**) value associated with ``mode``. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Add the label to the list. label = self._qteGetLabelInstance() label.setText(value) self._qteModeList.insert(pos, (mode, value, label)) self._qteUpdateLabelWidths()
[ "def", "qteInsertMode", "(", "self", ",", "pos", ":", "int", ",", "mode", ":", "str", ",", "value", ")", ":", "# Add the label to the list.", "label", "=", "self", ".", "_qteGetLabelInstance", "(", ")", "label", ".", "setText", "(", "value", ")", "self", ".", "_qteModeList", ".", "insert", "(", "pos", ",", "(", "mode", ",", "value", ",", "label", ")", ")", "self", ".", "_qteUpdateLabelWidths", "(", ")" ]
Insert ``mode`` at position ``pos``. If ``pos`` is negative then this is equivalent to ``pos=0``. If it is larger than the number of modes in the list then it is appended as the last element. |Args| * ``pos`` (**int**): insertion point. * ``mode`` (**str**): name of mode. * ``value`` (**object**) value associated with ``mode``. |Returns| * **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Insert", "mode", "at", "position", "pos", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L1339-L1365
train
olitheolix/qtmacs
qtmacs/auxiliary.py
QtmacsModeBar.qteRemoveMode
def qteRemoveMode(self, mode: str): """ Remove ``mode`` and associated label. If ``mode`` does not exist then nothing happens and the method returns **False**, otherwise **True**. |Args| * ``pos`` (**QRect**): size and position of new window. * ``windowID`` (**str**): unique window ID. |Returns| * **bool**: **True** if the item was removed and **False** if there was an error (most likely ``mode`` does not exist). |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Search through the list for ``mode``. for idx, item in enumerate(self._qteModeList): if item[0] == mode: # Remove the record and delete the label. self._qteModeList.remove(item) item[2].hide() item[2].deleteLater() self._qteUpdateLabelWidths() return True return False
python
def qteRemoveMode(self, mode: str): """ Remove ``mode`` and associated label. If ``mode`` does not exist then nothing happens and the method returns **False**, otherwise **True**. |Args| * ``pos`` (**QRect**): size and position of new window. * ``windowID`` (**str**): unique window ID. |Returns| * **bool**: **True** if the item was removed and **False** if there was an error (most likely ``mode`` does not exist). |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type. """ # Search through the list for ``mode``. for idx, item in enumerate(self._qteModeList): if item[0] == mode: # Remove the record and delete the label. self._qteModeList.remove(item) item[2].hide() item[2].deleteLater() self._qteUpdateLabelWidths() return True return False
[ "def", "qteRemoveMode", "(", "self", ",", "mode", ":", "str", ")", ":", "# Search through the list for ``mode``.", "for", "idx", ",", "item", "in", "enumerate", "(", "self", ".", "_qteModeList", ")", ":", "if", "item", "[", "0", "]", "==", "mode", ":", "# Remove the record and delete the label.", "self", ".", "_qteModeList", ".", "remove", "(", "item", ")", "item", "[", "2", "]", ".", "hide", "(", ")", "item", "[", "2", "]", ".", "deleteLater", "(", ")", "self", ".", "_qteUpdateLabelWidths", "(", ")", "return", "True", "return", "False" ]
Remove ``mode`` and associated label. If ``mode`` does not exist then nothing happens and the method returns **False**, otherwise **True**. |Args| * ``pos`` (**QRect**): size and position of new window. * ``windowID`` (**str**): unique window ID. |Returns| * **bool**: **True** if the item was removed and **False** if there was an error (most likely ``mode`` does not exist). |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
[ "Remove", "mode", "and", "associated", "label", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/auxiliary.py#L1368-L1398
train
contains-io/typet
typet/validation.py
_BoundedMeta._get_bases
def _get_bases(type_): # type: (type) -> Tuple[type, type] """Get the base and meta classes to use in creating a subclass. Args: type_: The type to subclass. Returns: A tuple containing two values: a base class, and a metaclass. """ try: class _(type_): # type: ignore """Check if type_ is subclassable.""" BaseClass = type_ except TypeError: BaseClass = object class MetaClass(_ValidationMeta, BaseClass.__class__): # type: ignore """Use the type_ meta and include base validation functionality.""" return BaseClass, MetaClass
python
def _get_bases(type_): # type: (type) -> Tuple[type, type] """Get the base and meta classes to use in creating a subclass. Args: type_: The type to subclass. Returns: A tuple containing two values: a base class, and a metaclass. """ try: class _(type_): # type: ignore """Check if type_ is subclassable.""" BaseClass = type_ except TypeError: BaseClass = object class MetaClass(_ValidationMeta, BaseClass.__class__): # type: ignore """Use the type_ meta and include base validation functionality.""" return BaseClass, MetaClass
[ "def", "_get_bases", "(", "type_", ")", ":", "# type: (type) -> Tuple[type, type]", "try", ":", "class", "_", "(", "type_", ")", ":", "# type: ignore", "\"\"\"Check if type_ is subclassable.\"\"\"", "BaseClass", "=", "type_", "except", "TypeError", ":", "BaseClass", "=", "object", "class", "MetaClass", "(", "_ValidationMeta", ",", "BaseClass", ".", "__class__", ")", ":", "# type: ignore", "\"\"\"Use the type_ meta and include base validation functionality.\"\"\"", "return", "BaseClass", ",", "MetaClass" ]
Get the base and meta classes to use in creating a subclass. Args: type_: The type to subclass. Returns: A tuple containing two values: a base class, and a metaclass.
[ "Get", "the", "base", "and", "meta", "classes", "to", "use", "in", "creating", "a", "subclass", "." ]
ad5087c567af84db299eca186776e1cee228e442
https://github.com/contains-io/typet/blob/ad5087c567af84db299eca186776e1cee228e442/typet/validation.py#L158-L180
train
contains-io/typet
typet/validation.py
_BoundedMeta._instantiate
def _instantiate(class_, type_, __value, *args, **kwargs): """Instantiate the object if possible. Args: class_: The class to instantiate. type_: The the class is uninstantiable, attempt to cast to a base type. __value: The value to return if the class and type are uninstantiable. *args: The positional arguments to pass to the class. **kwargs: The keyword arguments to pass to the class. Returns: The class or base type instantiated using the arguments. If it is not possible to instantiate either, returns __value. """ try: return class_(__value, *args, **kwargs) except TypeError: try: return type_(__value, *args, **kwargs) except Exception: # pylint: disable=broad-except return __value
python
def _instantiate(class_, type_, __value, *args, **kwargs): """Instantiate the object if possible. Args: class_: The class to instantiate. type_: The the class is uninstantiable, attempt to cast to a base type. __value: The value to return if the class and type are uninstantiable. *args: The positional arguments to pass to the class. **kwargs: The keyword arguments to pass to the class. Returns: The class or base type instantiated using the arguments. If it is not possible to instantiate either, returns __value. """ try: return class_(__value, *args, **kwargs) except TypeError: try: return type_(__value, *args, **kwargs) except Exception: # pylint: disable=broad-except return __value
[ "def", "_instantiate", "(", "class_", ",", "type_", ",", "__value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "class_", "(", "__value", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "TypeError", ":", "try", ":", "return", "type_", "(", "__value", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "return", "__value" ]
Instantiate the object if possible. Args: class_: The class to instantiate. type_: The the class is uninstantiable, attempt to cast to a base type. __value: The value to return if the class and type are uninstantiable. *args: The positional arguments to pass to the class. **kwargs: The keyword arguments to pass to the class. Returns: The class or base type instantiated using the arguments. If it is not possible to instantiate either, returns __value.
[ "Instantiate", "the", "object", "if", "possible", "." ]
ad5087c567af84db299eca186776e1cee228e442
https://github.com/contains-io/typet/blob/ad5087c567af84db299eca186776e1cee228e442/typet/validation.py#L183-L205
train
contains-io/typet
typet/validation.py
_BoundedMeta._get_fullname
def _get_fullname(obj): # type: (Any) -> str """Get the full name of an object including the module. Args: obj: An object. Returns: The full class name of the object. """ if not hasattr(obj, "__name__"): obj = obj.__class__ if obj.__module__ in ("builtins", "__builtin__"): return obj.__name__ return "{}.{}".format(obj.__module__, obj.__name__)
python
def _get_fullname(obj): # type: (Any) -> str """Get the full name of an object including the module. Args: obj: An object. Returns: The full class name of the object. """ if not hasattr(obj, "__name__"): obj = obj.__class__ if obj.__module__ in ("builtins", "__builtin__"): return obj.__name__ return "{}.{}".format(obj.__module__, obj.__name__)
[ "def", "_get_fullname", "(", "obj", ")", ":", "# type: (Any) -> str", "if", "not", "hasattr", "(", "obj", ",", "\"__name__\"", ")", ":", "obj", "=", "obj", ".", "__class__", "if", "obj", ".", "__module__", "in", "(", "\"builtins\"", ",", "\"__builtin__\"", ")", ":", "return", "obj", ".", "__name__", "return", "\"{}.{}\"", ".", "format", "(", "obj", ".", "__module__", ",", "obj", ".", "__name__", ")" ]
Get the full name of an object including the module. Args: obj: An object. Returns: The full class name of the object.
[ "Get", "the", "full", "name", "of", "an", "object", "including", "the", "module", "." ]
ad5087c567af84db299eca186776e1cee228e442
https://github.com/contains-io/typet/blob/ad5087c567af84db299eca186776e1cee228e442/typet/validation.py#L297-L311
train
sublee/etc
etc/client.py
Client.get
def get(self, key, recursive=False, sorted=False, quorum=False, timeout=None): """Gets a value of key.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, timeout=timeout)
python
def get(self, key, recursive=False, sorted=False, quorum=False, timeout=None): """Gets a value of key.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, timeout=timeout)
[ "def", "get", "(", "self", ",", "key", ",", "recursive", "=", "False", ",", "sorted", "=", "False", ",", "quorum", "=", "False", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "adapter", ".", "get", "(", "key", ",", "recursive", "=", "recursive", ",", "sorted", "=", "sorted", ",", "quorum", "=", "quorum", ",", "timeout", "=", "timeout", ")" ]
Gets a value of key.
[ "Gets", "a", "value", "of", "key", "." ]
f2be64604da5af0d7739cfacf36f55712f0fc5cb
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L29-L33
train
sublee/etc
etc/client.py
Client.wait
def wait(self, key, index=0, recursive=False, sorted=False, quorum=False, timeout=None): """Waits until a node changes.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, wait=True, wait_index=index, timeout=timeout)
python
def wait(self, key, index=0, recursive=False, sorted=False, quorum=False, timeout=None): """Waits until a node changes.""" return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, wait=True, wait_index=index, timeout=timeout)
[ "def", "wait", "(", "self", ",", "key", ",", "index", "=", "0", ",", "recursive", "=", "False", ",", "sorted", "=", "False", ",", "quorum", "=", "False", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "adapter", ".", "get", "(", "key", ",", "recursive", "=", "recursive", ",", "sorted", "=", "sorted", ",", "quorum", "=", "quorum", ",", "wait", "=", "True", ",", "wait_index", "=", "index", ",", "timeout", "=", "timeout", ")" ]
Waits until a node changes.
[ "Waits", "until", "a", "node", "changes", "." ]
f2be64604da5af0d7739cfacf36f55712f0fc5cb
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L35-L40
train
sublee/etc
etc/client.py
Client.refresh
def refresh(self, key, ttl, prev_value=None, prev_index=None, timeout=None): """Sets only a TTL of a key. The waiters doesn't receive notification by this operation. """ return self.adapter.set(key, ttl=ttl, refresh=True, prev_value=prev_value, prev_index=prev_index, timeout=timeout)
python
def refresh(self, key, ttl, prev_value=None, prev_index=None, timeout=None): """Sets only a TTL of a key. The waiters doesn't receive notification by this operation. """ return self.adapter.set(key, ttl=ttl, refresh=True, prev_value=prev_value, prev_index=prev_index, timeout=timeout)
[ "def", "refresh", "(", "self", ",", "key", ",", "ttl", ",", "prev_value", "=", "None", ",", "prev_index", "=", "None", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "adapter", ".", "set", "(", "key", ",", "ttl", "=", "ttl", ",", "refresh", "=", "True", ",", "prev_value", "=", "prev_value", ",", "prev_index", "=", "prev_index", ",", "timeout", "=", "timeout", ")" ]
Sets only a TTL of a key. The waiters doesn't receive notification by this operation.
[ "Sets", "only", "a", "TTL", "of", "a", "key", ".", "The", "waiters", "doesn", "t", "receive", "notification", "by", "this", "operation", "." ]
f2be64604da5af0d7739cfacf36f55712f0fc5cb
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L49-L56
train
sublee/etc
etc/client.py
Client.create
def create(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, prev_exist=False, timeout=timeout)
python
def create(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, prev_exist=False, timeout=timeout)
[ "def", "create", "(", "self", ",", "key", ",", "value", "=", "None", ",", "dir", "=", "False", ",", "ttl", "=", "None", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "adapter", ".", "set", "(", "key", ",", "value", ",", "dir", "=", "dir", ",", "ttl", "=", "ttl", ",", "prev_exist", "=", "False", ",", "timeout", "=", "timeout", ")" ]
Creates a new key.
[ "Creates", "a", "new", "key", "." ]
f2be64604da5af0d7739cfacf36f55712f0fc5cb
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L58-L61
train
sublee/etc
etc/client.py
Client.update
def update(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Updates an existing key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, prev_exist=True, timeout=timeout)
python
def update(self, key, value=None, dir=False, ttl=None, refresh=False, prev_value=None, prev_index=None, timeout=None): """Updates an existing key.""" return self.adapter.set(key, value, dir=dir, ttl=ttl, refresh=refresh, prev_value=prev_value, prev_index=prev_index, prev_exist=True, timeout=timeout)
[ "def", "update", "(", "self", ",", "key", ",", "value", "=", "None", ",", "dir", "=", "False", ",", "ttl", "=", "None", ",", "refresh", "=", "False", ",", "prev_value", "=", "None", ",", "prev_index", "=", "None", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "adapter", ".", "set", "(", "key", ",", "value", ",", "dir", "=", "dir", ",", "ttl", "=", "ttl", ",", "refresh", "=", "refresh", ",", "prev_value", "=", "prev_value", ",", "prev_index", "=", "prev_index", ",", "prev_exist", "=", "True", ",", "timeout", "=", "timeout", ")" ]
Updates an existing key.
[ "Updates", "an", "existing", "key", "." ]
f2be64604da5af0d7739cfacf36f55712f0fc5cb
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L63-L68
train
sublee/etc
etc/client.py
Client.append
def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new automatically increasing key in the given directory key. """ return self.adapter.append(key, value, dir=dir, ttl=ttl, timeout=timeout)
python
def append(self, key, value=None, dir=False, ttl=None, timeout=None): """Creates a new automatically increasing key in the given directory key. """ return self.adapter.append(key, value, dir=dir, ttl=ttl, timeout=timeout)
[ "def", "append", "(", "self", ",", "key", ",", "value", "=", "None", ",", "dir", "=", "False", ",", "ttl", "=", "None", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "adapter", ".", "append", "(", "key", ",", "value", ",", "dir", "=", "dir", ",", "ttl", "=", "ttl", ",", "timeout", "=", "timeout", ")" ]
Creates a new automatically increasing key in the given directory key.
[ "Creates", "a", "new", "automatically", "increasing", "key", "in", "the", "given", "directory", "key", "." ]
f2be64604da5af0d7739cfacf36f55712f0fc5cb
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L70-L75
train
sublee/etc
etc/client.py
Client.delete
def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Deletes a key.""" return self.adapter.delete(key, dir=dir, recursive=recursive, prev_value=prev_value, prev_index=prev_index, timeout=timeout)
python
def delete(self, key, dir=False, recursive=False, prev_value=None, prev_index=None, timeout=None): """Deletes a key.""" return self.adapter.delete(key, dir=dir, recursive=recursive, prev_value=prev_value, prev_index=prev_index, timeout=timeout)
[ "def", "delete", "(", "self", ",", "key", ",", "dir", "=", "False", ",", "recursive", "=", "False", ",", "prev_value", "=", "None", ",", "prev_index", "=", "None", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "adapter", ".", "delete", "(", "key", ",", "dir", "=", "dir", ",", "recursive", "=", "recursive", ",", "prev_value", "=", "prev_value", ",", "prev_index", "=", "prev_index", ",", "timeout", "=", "timeout", ")" ]
Deletes a key.
[ "Deletes", "a", "key", "." ]
f2be64604da5af0d7739cfacf36f55712f0fc5cb
https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/client.py#L77-L82
train
jahuth/litus
spikes.py
SpikeContainerCollection.find
def find(self,cell_designation,cell_filter=lambda x,c: 'c' in x and x['c'] == c): """ finds spike containers in a multi spike containers collection """ res = [i for i,sc in enumerate(self.spike_containers) if cell_filter(sc.meta,cell_designation)] if len(res) > 0: return res[0]
python
def find(self,cell_designation,cell_filter=lambda x,c: 'c' in x and x['c'] == c): """ finds spike containers in a multi spike containers collection """ res = [i for i,sc in enumerate(self.spike_containers) if cell_filter(sc.meta,cell_designation)] if len(res) > 0: return res[0]
[ "def", "find", "(", "self", ",", "cell_designation", ",", "cell_filter", "=", "lambda", "x", ",", "c", ":", "'c'", "in", "x", "and", "x", "[", "'c'", "]", "==", "c", ")", ":", "res", "=", "[", "i", "for", "i", ",", "sc", "in", "enumerate", "(", "self", ".", "spike_containers", ")", "if", "cell_filter", "(", "sc", ".", "meta", ",", "cell_designation", ")", "]", "if", "len", "(", "res", ")", ">", "0", ":", "return", "res", "[", "0", "]" ]
finds spike containers in a multi spike containers collection
[ "finds", "spike", "containers", "in", "a", "multi", "spike", "containers", "collection" ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L145-L151
train
jahuth/litus
spikes.py
LabelDimension.len
def len(self,resolution=1.0,units=None,conversion_function=convert_time, end_at_end=True): """ Calculates the length of the Label Dimension from its minimum, maximum and wether it is discrete. `resolution`: `units`: output units `conversion_function`: `end_at_end`: additional switch for continuous behaviour """ if units is not None: resolution = conversion_function(resolution,from_units=units,to_units=self.units) else: units = self.units if self.min is None: return int(self.max / resolution) if self.max is None: return 0 if units != '1' and end_at_end: return int(np.ceil((self.max - self.min) / resolution)) return int(np.ceil((self.max - self.min) / resolution) + 1)
python
def len(self,resolution=1.0,units=None,conversion_function=convert_time, end_at_end=True): """ Calculates the length of the Label Dimension from its minimum, maximum and wether it is discrete. `resolution`: `units`: output units `conversion_function`: `end_at_end`: additional switch for continuous behaviour """ if units is not None: resolution = conversion_function(resolution,from_units=units,to_units=self.units) else: units = self.units if self.min is None: return int(self.max / resolution) if self.max is None: return 0 if units != '1' and end_at_end: return int(np.ceil((self.max - self.min) / resolution)) return int(np.ceil((self.max - self.min) / resolution) + 1)
[ "def", "len", "(", "self", ",", "resolution", "=", "1.0", ",", "units", "=", "None", ",", "conversion_function", "=", "convert_time", ",", "end_at_end", "=", "True", ")", ":", "if", "units", "is", "not", "None", ":", "resolution", "=", "conversion_function", "(", "resolution", ",", "from_units", "=", "units", ",", "to_units", "=", "self", ".", "units", ")", "else", ":", "units", "=", "self", ".", "units", "if", "self", ".", "min", "is", "None", ":", "return", "int", "(", "self", ".", "max", "/", "resolution", ")", "if", "self", ".", "max", "is", "None", ":", "return", "0", "if", "units", "!=", "'1'", "and", "end_at_end", ":", "return", "int", "(", "np", ".", "ceil", "(", "(", "self", ".", "max", "-", "self", ".", "min", ")", "/", "resolution", ")", ")", "return", "int", "(", "np", ".", "ceil", "(", "(", "self", ".", "max", "-", "self", ".", "min", ")", "/", "resolution", ")", "+", "1", ")" ]
Calculates the length of the Label Dimension from its minimum, maximum and wether it is discrete. `resolution`: `units`: output units `conversion_function`: `end_at_end`: additional switch for continuous behaviour
[ "Calculates", "the", "length", "of", "the", "Label", "Dimension", "from", "its", "minimum", "maximum", "and", "wether", "it", "is", "discrete", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L282-L301
train
jahuth/litus
spikes.py
LabelDimension.logspace
def logspace(self,bins=None,units=None,conversion_function=convert_time,resolution=None,end_at_end=True): """ bins overwrites resolution """ if type(bins) in [list, np.ndarray]: return bins min = conversion_function(self.min,from_units=self.units,to_units=units) max = conversion_function(self.max,from_units=self.units,to_units=units) if units is None: units = self.units if resolution is None: resolution = 1.0 if bins is None: bins = self.len(resolution=resolution,units=units,conversion_function=conversion_function)# + 1 if units != '1' and end_at_end: # continuous variable behaviour: # we end with the last valid value at the outer edge return np.logspace(np.log10(min),np.log10(max),bins+1)[:-1] # discrete variable behaviour: # we end with the last valid value as its own bin return np.logspace(np.log10(min),np.log10(max),bins)
python
def logspace(self,bins=None,units=None,conversion_function=convert_time,resolution=None,end_at_end=True): """ bins overwrites resolution """ if type(bins) in [list, np.ndarray]: return bins min = conversion_function(self.min,from_units=self.units,to_units=units) max = conversion_function(self.max,from_units=self.units,to_units=units) if units is None: units = self.units if resolution is None: resolution = 1.0 if bins is None: bins = self.len(resolution=resolution,units=units,conversion_function=conversion_function)# + 1 if units != '1' and end_at_end: # continuous variable behaviour: # we end with the last valid value at the outer edge return np.logspace(np.log10(min),np.log10(max),bins+1)[:-1] # discrete variable behaviour: # we end with the last valid value as its own bin return np.logspace(np.log10(min),np.log10(max),bins)
[ "def", "logspace", "(", "self", ",", "bins", "=", "None", ",", "units", "=", "None", ",", "conversion_function", "=", "convert_time", ",", "resolution", "=", "None", ",", "end_at_end", "=", "True", ")", ":", "if", "type", "(", "bins", ")", "in", "[", "list", ",", "np", ".", "ndarray", "]", ":", "return", "bins", "min", "=", "conversion_function", "(", "self", ".", "min", ",", "from_units", "=", "self", ".", "units", ",", "to_units", "=", "units", ")", "max", "=", "conversion_function", "(", "self", ".", "max", ",", "from_units", "=", "self", ".", "units", ",", "to_units", "=", "units", ")", "if", "units", "is", "None", ":", "units", "=", "self", ".", "units", "if", "resolution", "is", "None", ":", "resolution", "=", "1.0", "if", "bins", "is", "None", ":", "bins", "=", "self", ".", "len", "(", "resolution", "=", "resolution", ",", "units", "=", "units", ",", "conversion_function", "=", "conversion_function", ")", "# + 1", "if", "units", "!=", "'1'", "and", "end_at_end", ":", "# continuous variable behaviour:", "# we end with the last valid value at the outer edge", "return", "np", ".", "logspace", "(", "np", ".", "log10", "(", "min", ")", ",", "np", ".", "log10", "(", "max", ")", ",", "bins", "+", "1", ")", "[", ":", "-", "1", "]", "# discrete variable behaviour:", "# we end with the last valid value as its own bin", "return", "np", ".", "logspace", "(", "np", ".", "log10", "(", "min", ")", ",", "np", ".", "log10", "(", "max", ")", ",", "bins", ")" ]
bins overwrites resolution
[ "bins", "overwrites", "resolution" ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L363-L381
train
jahuth/litus
spikes.py
LabelDimension.constraint_range_dict
def constraint_range_dict(self,*args,**kwargs): """ Creates a list of dictionaries which each give a constraint for a certain section of the dimension. bins arguments overwrites resolution """ bins = self.bins(*args,**kwargs) return [{self.name+'__gte': a,self.name+'__lt': b} for a,b in zip(bins[:-1],bins[1:])] space = self.space(*args,**kwargs) resolution = space[1] - space[0] return [{self.name+'__gte': s,self.name+'__lt': s+resolution} for s in space]
python
def constraint_range_dict(self,*args,**kwargs): """ Creates a list of dictionaries which each give a constraint for a certain section of the dimension. bins arguments overwrites resolution """ bins = self.bins(*args,**kwargs) return [{self.name+'__gte': a,self.name+'__lt': b} for a,b in zip(bins[:-1],bins[1:])] space = self.space(*args,**kwargs) resolution = space[1] - space[0] return [{self.name+'__gte': s,self.name+'__lt': s+resolution} for s in space]
[ "def", "constraint_range_dict", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "bins", "=", "self", ".", "bins", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "[", "{", "self", ".", "name", "+", "'__gte'", ":", "a", ",", "self", ".", "name", "+", "'__lt'", ":", "b", "}", "for", "a", ",", "b", "in", "zip", "(", "bins", "[", ":", "-", "1", "]", ",", "bins", "[", "1", ":", "]", ")", "]", "space", "=", "self", ".", "space", "(", "*", "args", ",", "*", "*", "kwargs", ")", "resolution", "=", "space", "[", "1", "]", "-", "space", "[", "0", "]", "return", "[", "{", "self", ".", "name", "+", "'__gte'", ":", "s", ",", "self", ".", "name", "+", "'__lt'", ":", "s", "+", "resolution", "}", "for", "s", "in", "space", "]" ]
Creates a list of dictionaries which each give a constraint for a certain section of the dimension. bins arguments overwrites resolution
[ "Creates", "a", "list", "of", "dictionaries", "which", "each", "give", "a", "constraint", "for", "a", "certain", "section", "of", "the", "dimension", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L392-L403
train
jahuth/litus
spikes.py
LabeledMatrix.find_labels
def find_labels(self,key,find_in_name=True,find_in_units=False): """ Takes a string or a function to find a set of label indizes that match. If the string starts with a '~', the label only has to contain the string. """ if type(key) is str: found_keys = [] if key.startswith('~'): for label_no,label in enumerate(self.labels): if find_in_name and key[1:] in label.name: found_keys.append(label_no) if find_in_units and key[1:] in label.units: found_keys.append(label_no) else: for label_no,label in enumerate(self.labels): if find_in_name and key == label.name: return [label_no] if find_in_units and key == label.units: return [label_no] return found_keys if hasattr(key, '__call__'): found_keys = [] for label_no,label in enumerate(self.labels): if key(label): found_keys.append(label_no) return found_keys if type(key) is int: return [key] if key < self.matrix.shape[1] else [] return [key]
python
def find_labels(self,key,find_in_name=True,find_in_units=False): """ Takes a string or a function to find a set of label indizes that match. If the string starts with a '~', the label only has to contain the string. """ if type(key) is str: found_keys = [] if key.startswith('~'): for label_no,label in enumerate(self.labels): if find_in_name and key[1:] in label.name: found_keys.append(label_no) if find_in_units and key[1:] in label.units: found_keys.append(label_no) else: for label_no,label in enumerate(self.labels): if find_in_name and key == label.name: return [label_no] if find_in_units and key == label.units: return [label_no] return found_keys if hasattr(key, '__call__'): found_keys = [] for label_no,label in enumerate(self.labels): if key(label): found_keys.append(label_no) return found_keys if type(key) is int: return [key] if key < self.matrix.shape[1] else [] return [key]
[ "def", "find_labels", "(", "self", ",", "key", ",", "find_in_name", "=", "True", ",", "find_in_units", "=", "False", ")", ":", "if", "type", "(", "key", ")", "is", "str", ":", "found_keys", "=", "[", "]", "if", "key", ".", "startswith", "(", "'~'", ")", ":", "for", "label_no", ",", "label", "in", "enumerate", "(", "self", ".", "labels", ")", ":", "if", "find_in_name", "and", "key", "[", "1", ":", "]", "in", "label", ".", "name", ":", "found_keys", ".", "append", "(", "label_no", ")", "if", "find_in_units", "and", "key", "[", "1", ":", "]", "in", "label", ".", "units", ":", "found_keys", ".", "append", "(", "label_no", ")", "else", ":", "for", "label_no", ",", "label", "in", "enumerate", "(", "self", ".", "labels", ")", ":", "if", "find_in_name", "and", "key", "==", "label", ".", "name", ":", "return", "[", "label_no", "]", "if", "find_in_units", "and", "key", "==", "label", ".", "units", ":", "return", "[", "label_no", "]", "return", "found_keys", "if", "hasattr", "(", "key", ",", "'__call__'", ")", ":", "found_keys", "=", "[", "]", "for", "label_no", ",", "label", "in", "enumerate", "(", "self", ".", "labels", ")", ":", "if", "key", "(", "label", ")", ":", "found_keys", ".", "append", "(", "label_no", ")", "return", "found_keys", "if", "type", "(", "key", ")", "is", "int", ":", "return", "[", "key", "]", "if", "key", "<", "self", ".", "matrix", ".", "shape", "[", "1", "]", "else", "[", "]", "return", "[", "key", "]" ]
Takes a string or a function to find a set of label indizes that match. If the string starts with a '~', the label only has to contain the string.
[ "Takes", "a", "string", "or", "a", "function", "to", "find", "a", "set", "of", "label", "indizes", "that", "match", ".", "If", "the", "string", "starts", "with", "a", "~", "the", "label", "only", "has", "to", "contain", "the", "string", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L462-L491
train
jahuth/litus
spikes.py
LabeledMatrix.convert
def convert(self,label,units=None,conversion_function=convert_time): """ converts a dimension in place """ label_no = self.get_label_no(label) new_label, new_column = self.get_converted(label_no,units,conversion_function) labels = [LabelDimension(l) for l in self.labels] labels[label_no] = new_label matrix = self.matrix.copy() matrix[:,label_no] = new_column return LabeledMatrix(matrix,labels)
python
def convert(self,label,units=None,conversion_function=convert_time): """ converts a dimension in place """ label_no = self.get_label_no(label) new_label, new_column = self.get_converted(label_no,units,conversion_function) labels = [LabelDimension(l) for l in self.labels] labels[label_no] = new_label matrix = self.matrix.copy() matrix[:,label_no] = new_column return LabeledMatrix(matrix,labels)
[ "def", "convert", "(", "self", ",", "label", ",", "units", "=", "None", ",", "conversion_function", "=", "convert_time", ")", ":", "label_no", "=", "self", ".", "get_label_no", "(", "label", ")", "new_label", ",", "new_column", "=", "self", ".", "get_converted", "(", "label_no", ",", "units", ",", "conversion_function", ")", "labels", "=", "[", "LabelDimension", "(", "l", ")", "for", "l", "in", "self", ".", "labels", "]", "labels", "[", "label_no", "]", "=", "new_label", "matrix", "=", "self", ".", "matrix", ".", "copy", "(", ")", "matrix", "[", ":", ",", "label_no", "]", "=", "new_column", "return", "LabeledMatrix", "(", "matrix", ",", "labels", ")" ]
converts a dimension in place
[ "converts", "a", "dimension", "in", "place" ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L597-L605
train
jahuth/litus
spikes.py
LabeledMatrix._get_constrained_labels
def _get_constrained_labels(self,remove_dimensions=False,**kwargs): """ returns labels which have updated minima and maxima, depending on the kwargs supplied to this """ new_labels = [] for label_no,label in enumerate(self.labels): new_label = LabelDimension(label) remove = False for k in kwargs: if k == label.name: new_label.max = kwargs[k] new_label.min = kwargs[k] remove = True if k == label.name+'__lt': if new_label.units == '1': new_label.max = np.min([new_label.max,kwargs[k]-1]) # is this right? else: new_label.max = np.min([new_label.max,kwargs[k]]) #remove = True if k == label.name+'__lte': new_label.max = np.min([new_label.max,kwargs[k]]) #remove = True if k == label.name+'__gt': if new_label.units == '1': new_label.min = np.max([new_label.min,kwargs[k]+1]) else: new_label.min = np.max([new_label.min,kwargs[k]]) #remove = True if k == label.name+'__gte': new_label.min = np.max([new_label.min,kwargs[k]]) #remove = True if k == label.name+'__evals': remove = True if remove_dimensions: if remove: # skipping removed labels continue new_labels.append(new_label) return new_labels
python
def _get_constrained_labels(self,remove_dimensions=False,**kwargs): """ returns labels which have updated minima and maxima, depending on the kwargs supplied to this """ new_labels = [] for label_no,label in enumerate(self.labels): new_label = LabelDimension(label) remove = False for k in kwargs: if k == label.name: new_label.max = kwargs[k] new_label.min = kwargs[k] remove = True if k == label.name+'__lt': if new_label.units == '1': new_label.max = np.min([new_label.max,kwargs[k]-1]) # is this right? else: new_label.max = np.min([new_label.max,kwargs[k]]) #remove = True if k == label.name+'__lte': new_label.max = np.min([new_label.max,kwargs[k]]) #remove = True if k == label.name+'__gt': if new_label.units == '1': new_label.min = np.max([new_label.min,kwargs[k]+1]) else: new_label.min = np.max([new_label.min,kwargs[k]]) #remove = True if k == label.name+'__gte': new_label.min = np.max([new_label.min,kwargs[k]]) #remove = True if k == label.name+'__evals': remove = True if remove_dimensions: if remove: # skipping removed labels continue new_labels.append(new_label) return new_labels
[ "def", "_get_constrained_labels", "(", "self", ",", "remove_dimensions", "=", "False", ",", "*", "*", "kwargs", ")", ":", "new_labels", "=", "[", "]", "for", "label_no", ",", "label", "in", "enumerate", "(", "self", ".", "labels", ")", ":", "new_label", "=", "LabelDimension", "(", "label", ")", "remove", "=", "False", "for", "k", "in", "kwargs", ":", "if", "k", "==", "label", ".", "name", ":", "new_label", ".", "max", "=", "kwargs", "[", "k", "]", "new_label", ".", "min", "=", "kwargs", "[", "k", "]", "remove", "=", "True", "if", "k", "==", "label", ".", "name", "+", "'__lt'", ":", "if", "new_label", ".", "units", "==", "'1'", ":", "new_label", ".", "max", "=", "np", ".", "min", "(", "[", "new_label", ".", "max", ",", "kwargs", "[", "k", "]", "-", "1", "]", ")", "# is this right?", "else", ":", "new_label", ".", "max", "=", "np", ".", "min", "(", "[", "new_label", ".", "max", ",", "kwargs", "[", "k", "]", "]", ")", "#remove = True", "if", "k", "==", "label", ".", "name", "+", "'__lte'", ":", "new_label", ".", "max", "=", "np", ".", "min", "(", "[", "new_label", ".", "max", ",", "kwargs", "[", "k", "]", "]", ")", "#remove = True", "if", "k", "==", "label", ".", "name", "+", "'__gt'", ":", "if", "new_label", ".", "units", "==", "'1'", ":", "new_label", ".", "min", "=", "np", ".", "max", "(", "[", "new_label", ".", "min", ",", "kwargs", "[", "k", "]", "+", "1", "]", ")", "else", ":", "new_label", ".", "min", "=", "np", ".", "max", "(", "[", "new_label", ".", "min", ",", "kwargs", "[", "k", "]", "]", ")", "#remove = True", "if", "k", "==", "label", ".", "name", "+", "'__gte'", ":", "new_label", ".", "min", "=", "np", ".", "max", "(", "[", "new_label", ".", "min", ",", "kwargs", "[", "k", "]", "]", ")", "#remove = True", "if", "k", "==", "label", ".", "name", "+", "'__evals'", ":", "remove", "=", "True", "if", "remove_dimensions", ":", "if", "remove", ":", "# skipping removed labels", "continue", "new_labels", ".", "append", "(", "new_label", ")", "return", "new_labels" ]
returns labels which have updated minima and maxima, depending on the kwargs supplied to this
[ "returns", "labels", "which", "have", "updated", "minima", "and", "maxima", "depending", "on", "the", "kwargs", "supplied", "to", "this" ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L606-L645
train
jahuth/litus
spikes.py
SpikeContainer.store_meta
def store_meta(self,meta): "Inplace method that adds meta information to the meta dictionary" if self.meta is None: self.meta = {} self.meta.update(meta) return self
python
def store_meta(self,meta): "Inplace method that adds meta information to the meta dictionary" if self.meta is None: self.meta = {} self.meta.update(meta) return self
[ "def", "store_meta", "(", "self", ",", "meta", ")", ":", "if", "self", ".", "meta", "is", "None", ":", "self", ".", "meta", "=", "{", "}", "self", ".", "meta", ".", "update", "(", "meta", ")", "return", "self" ]
Inplace method that adds meta information to the meta dictionary
[ "Inplace", "method", "that", "adds", "meta", "information", "to", "the", "meta", "dictionary" ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L879-L884
train
jahuth/litus
spikes.py
SpikeContainer.find
def find(self,cell_designation,cell_filter=lambda x,c: 'c' in x and x['c'] == c): """ finds spike containers in multi spike containers collection offspring """ if 'parent' in self.meta: return (self.meta['parent'],self.meta['parent'].find(cell_designation,cell_filter=cell_filter))
python
def find(self,cell_designation,cell_filter=lambda x,c: 'c' in x and x['c'] == c): """ finds spike containers in multi spike containers collection offspring """ if 'parent' in self.meta: return (self.meta['parent'],self.meta['parent'].find(cell_designation,cell_filter=cell_filter))
[ "def", "find", "(", "self", ",", "cell_designation", ",", "cell_filter", "=", "lambda", "x", ",", "c", ":", "'c'", "in", "x", "and", "x", "[", "'c'", "]", "==", "c", ")", ":", "if", "'parent'", "in", "self", ".", "meta", ":", "return", "(", "self", ".", "meta", "[", "'parent'", "]", ",", "self", ".", "meta", "[", "'parent'", "]", ".", "find", "(", "cell_designation", ",", "cell_filter", "=", "cell_filter", ")", ")" ]
finds spike containers in multi spike containers collection offspring
[ "finds", "spike", "containers", "in", "multi", "spike", "containers", "collection", "offspring" ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L885-L890
train
jahuth/litus
spikes.py
SpikeContainer.ISIs
def ISIs(self,time_dimension=0,units=None,min_t=None,max_t=None): """ returns the Inter Spike Intervals `time_dimension`: which dimension contains the spike times (by default the first) `units`,`min_t`,`max_t`: define the units of the output and the range of spikes that should be considered """ units = self._default_units(units) converted_dimension,st = self.spike_times.get_converted(time_dimension,units) if min_t is None: min_t = converted_dimension.min if max_t is None: max_t = converted_dimension.max return np.diff(sorted(st[(st>min_t) * (st <max_t)]))
python
def ISIs(self,time_dimension=0,units=None,min_t=None,max_t=None): """ returns the Inter Spike Intervals `time_dimension`: which dimension contains the spike times (by default the first) `units`,`min_t`,`max_t`: define the units of the output and the range of spikes that should be considered """ units = self._default_units(units) converted_dimension,st = self.spike_times.get_converted(time_dimension,units) if min_t is None: min_t = converted_dimension.min if max_t is None: max_t = converted_dimension.max return np.diff(sorted(st[(st>min_t) * (st <max_t)]))
[ "def", "ISIs", "(", "self", ",", "time_dimension", "=", "0", ",", "units", "=", "None", ",", "min_t", "=", "None", ",", "max_t", "=", "None", ")", ":", "units", "=", "self", ".", "_default_units", "(", "units", ")", "converted_dimension", ",", "st", "=", "self", ".", "spike_times", ".", "get_converted", "(", "time_dimension", ",", "units", ")", "if", "min_t", "is", "None", ":", "min_t", "=", "converted_dimension", ".", "min", "if", "max_t", "is", "None", ":", "max_t", "=", "converted_dimension", ".", "max", "return", "np", ".", "diff", "(", "sorted", "(", "st", "[", "(", "st", ">", "min_t", ")", "*", "(", "st", "<", "max_t", ")", "]", ")", ")" ]
returns the Inter Spike Intervals `time_dimension`: which dimension contains the spike times (by default the first) `units`,`min_t`,`max_t`: define the units of the output and the range of spikes that should be considered
[ "returns", "the", "Inter", "Spike", "Intervals" ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L1076-L1090
train
jahuth/litus
spikes.py
SpikeContainer.temporal_firing_rate
def temporal_firing_rate(self,time_dimension=0,resolution=1.0,units=None, min_t=None,max_t=None,weight_function=None,normalize_time=False, normalize_n=False,start_units_with_0=True,cell_dimension='N'): """ Outputs a time histogram of spikes. `bins`: number of bins (default is 1ms bins from 0 to t_max) `weight_function`: if set, computes a weighted histogram, dependent on the (index, time) tuples of each spike weight_function = lambda x: weight_map.flatten()[array(x[:,0],dtype=int)] `normalize_time` `normalize_n`: normalize by the length of time (such that normal output is Hz) and/or number of units (such that output is Hz/unit, determined with unique values in cell_dimension) Generally does not make sense when using a weight_function other than 'count'. `start_units_with_0`: starts indizes from 0 instead from the actual index """ units = self._default_units(units) if self.data_format == 'spike_times': converted_dimension,st = self.spike_times.get_converted(0,units) if min_t is None: min_t = converted_dimension.min if max_t is None: max_t = converted_dimension.max st = st[(st>=min_t)*(st<max_t)] bins = converted_dimension.linspace_by_resolution(resolution,end_at_end=True,extra_bins=0) H,edg = np.histogram(st,bins=bins) if normalize_time: H = H/(convert_time(resolution,from_units=units,to_units='s')) # make it Hertz if normalize_n: H = H/(len(np.unique(self.spike_times[cell_dimension]))) return H,edg
python
def temporal_firing_rate(self,time_dimension=0,resolution=1.0,units=None, min_t=None,max_t=None,weight_function=None,normalize_time=False, normalize_n=False,start_units_with_0=True,cell_dimension='N'): """ Outputs a time histogram of spikes. `bins`: number of bins (default is 1ms bins from 0 to t_max) `weight_function`: if set, computes a weighted histogram, dependent on the (index, time) tuples of each spike weight_function = lambda x: weight_map.flatten()[array(x[:,0],dtype=int)] `normalize_time` `normalize_n`: normalize by the length of time (such that normal output is Hz) and/or number of units (such that output is Hz/unit, determined with unique values in cell_dimension) Generally does not make sense when using a weight_function other than 'count'. `start_units_with_0`: starts indizes from 0 instead from the actual index """ units = self._default_units(units) if self.data_format == 'spike_times': converted_dimension,st = self.spike_times.get_converted(0,units) if min_t is None: min_t = converted_dimension.min if max_t is None: max_t = converted_dimension.max st = st[(st>=min_t)*(st<max_t)] bins = converted_dimension.linspace_by_resolution(resolution,end_at_end=True,extra_bins=0) H,edg = np.histogram(st,bins=bins) if normalize_time: H = H/(convert_time(resolution,from_units=units,to_units='s')) # make it Hertz if normalize_n: H = H/(len(np.unique(self.spike_times[cell_dimension]))) return H,edg
[ "def", "temporal_firing_rate", "(", "self", ",", "time_dimension", "=", "0", ",", "resolution", "=", "1.0", ",", "units", "=", "None", ",", "min_t", "=", "None", ",", "max_t", "=", "None", ",", "weight_function", "=", "None", ",", "normalize_time", "=", "False", ",", "normalize_n", "=", "False", ",", "start_units_with_0", "=", "True", ",", "cell_dimension", "=", "'N'", ")", ":", "units", "=", "self", ".", "_default_units", "(", "units", ")", "if", "self", ".", "data_format", "==", "'spike_times'", ":", "converted_dimension", ",", "st", "=", "self", ".", "spike_times", ".", "get_converted", "(", "0", ",", "units", ")", "if", "min_t", "is", "None", ":", "min_t", "=", "converted_dimension", ".", "min", "if", "max_t", "is", "None", ":", "max_t", "=", "converted_dimension", ".", "max", "st", "=", "st", "[", "(", "st", ">=", "min_t", ")", "*", "(", "st", "<", "max_t", ")", "]", "bins", "=", "converted_dimension", ".", "linspace_by_resolution", "(", "resolution", ",", "end_at_end", "=", "True", ",", "extra_bins", "=", "0", ")", "H", ",", "edg", "=", "np", ".", "histogram", "(", "st", ",", "bins", "=", "bins", ")", "if", "normalize_time", ":", "H", "=", "H", "/", "(", "convert_time", "(", "resolution", ",", "from_units", "=", "units", ",", "to_units", "=", "'s'", ")", ")", "# make it Hertz", "if", "normalize_n", ":", "H", "=", "H", "/", "(", "len", "(", "np", ".", "unique", "(", "self", ".", "spike_times", "[", "cell_dimension", "]", ")", ")", ")", "return", "H", ",", "edg" ]
Outputs a time histogram of spikes. `bins`: number of bins (default is 1ms bins from 0 to t_max) `weight_function`: if set, computes a weighted histogram, dependent on the (index, time) tuples of each spike weight_function = lambda x: weight_map.flatten()[array(x[:,0],dtype=int)] `normalize_time` `normalize_n`: normalize by the length of time (such that normal output is Hz) and/or number of units (such that output is Hz/unit, determined with unique values in cell_dimension) Generally does not make sense when using a weight_function other than 'count'. `start_units_with_0`: starts indizes from 0 instead from the actual index
[ "Outputs", "a", "time", "histogram", "of", "spikes", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L1201-L1232
train
jahuth/litus
spikes.py
SpikeContainer.plot_temporal_firing_rate
def plot_temporal_firing_rate(self,time_dimension=0,resolution=1.0,units=None,min_t=None,max_t=None,weight_function=None,normalize_time=False,normalize_n=False,start_units_with_0=True,cell_dimension='N',**kwargs): """ Plots a firing rate plot. Accepts the same keyword arguments as :func:`matplotlib.pylab.plot()` for lines (:class:`~matplotlib.lines.Line2D`), eg `color`, `linewidth` (or `lw`), `linestyle` (or `ls`). See help for :func:`matplotlib.pylab.plot()`. """ if bool(self): import matplotlib.pylab as plt H,ed = self.temporal_firing_rate(time_dimension=time_dimension,resolution=resolution,units=units,min_t=min_t,max_t=max_t,weight_function=weight_function,normalize_time=normalize_time,normalize_n=normalize_n,start_units_with_0=start_units_with_0,cell_dimension=cell_dimension) plt.plot(ed[1:],H,**kwargs)
python
def plot_temporal_firing_rate(self,time_dimension=0,resolution=1.0,units=None,min_t=None,max_t=None,weight_function=None,normalize_time=False,normalize_n=False,start_units_with_0=True,cell_dimension='N',**kwargs): """ Plots a firing rate plot. Accepts the same keyword arguments as :func:`matplotlib.pylab.plot()` for lines (:class:`~matplotlib.lines.Line2D`), eg `color`, `linewidth` (or `lw`), `linestyle` (or `ls`). See help for :func:`matplotlib.pylab.plot()`. """ if bool(self): import matplotlib.pylab as plt H,ed = self.temporal_firing_rate(time_dimension=time_dimension,resolution=resolution,units=units,min_t=min_t,max_t=max_t,weight_function=weight_function,normalize_time=normalize_time,normalize_n=normalize_n,start_units_with_0=start_units_with_0,cell_dimension=cell_dimension) plt.plot(ed[1:],H,**kwargs)
[ "def", "plot_temporal_firing_rate", "(", "self", ",", "time_dimension", "=", "0", ",", "resolution", "=", "1.0", ",", "units", "=", "None", ",", "min_t", "=", "None", ",", "max_t", "=", "None", ",", "weight_function", "=", "None", ",", "normalize_time", "=", "False", ",", "normalize_n", "=", "False", ",", "start_units_with_0", "=", "True", ",", "cell_dimension", "=", "'N'", ",", "*", "*", "kwargs", ")", ":", "if", "bool", "(", "self", ")", ":", "import", "matplotlib", ".", "pylab", "as", "plt", "H", ",", "ed", "=", "self", ".", "temporal_firing_rate", "(", "time_dimension", "=", "time_dimension", ",", "resolution", "=", "resolution", ",", "units", "=", "units", ",", "min_t", "=", "min_t", ",", "max_t", "=", "max_t", ",", "weight_function", "=", "weight_function", ",", "normalize_time", "=", "normalize_time", ",", "normalize_n", "=", "normalize_n", ",", "start_units_with_0", "=", "start_units_with_0", ",", "cell_dimension", "=", "cell_dimension", ")", "plt", ".", "plot", "(", "ed", "[", "1", ":", "]", ",", "H", ",", "*", "*", "kwargs", ")" ]
Plots a firing rate plot. Accepts the same keyword arguments as :func:`matplotlib.pylab.plot()` for lines (:class:`~matplotlib.lines.Line2D`), eg `color`, `linewidth` (or `lw`), `linestyle` (or `ls`). See help for :func:`matplotlib.pylab.plot()`.
[ "Plots", "a", "firing", "rate", "plot", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L1235-L1245
train
jahuth/litus
spikes.py
SpikeContainer.get_units
def get_units(self,*args,**kwargs): """ Returns the units of a Dimension """ if len(args) == 1: return self.spike_times.get_label(args[0]).units return [self.spike_times.get_label(a).units for a in args]
python
def get_units(self,*args,**kwargs): """ Returns the units of a Dimension """ if len(args) == 1: return self.spike_times.get_label(args[0]).units return [self.spike_times.get_label(a).units for a in args]
[ "def", "get_units", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "return", "self", ".", "spike_times", ".", "get_label", "(", "args", "[", "0", "]", ")", ".", "units", "return", "[", "self", ".", "spike_times", ".", "get_label", "(", "a", ")", ".", "units", "for", "a", "in", "args", "]" ]
Returns the units of a Dimension
[ "Returns", "the", "units", "of", "a", "Dimension" ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L1381-L1387
train
jahuth/litus
spikes.py
SpikeContainer.get_min
def get_min(self,*args,**kwargs): """ Returns the minimum of a Dimension TODO: conversion is not implemented yet but should be """ if len(args) == 1: return self.spike_times.get_label(args[0]).min return [self.spike_times.get_label(a).max for a in args]
python
def get_min(self,*args,**kwargs): """ Returns the minimum of a Dimension TODO: conversion is not implemented yet but should be """ if len(args) == 1: return self.spike_times.get_label(args[0]).min return [self.spike_times.get_label(a).max for a in args]
[ "def", "get_min", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "return", "self", ".", "spike_times", ".", "get_label", "(", "args", "[", "0", "]", ")", ".", "min", "return", "[", "self", ".", "spike_times", ".", "get_label", "(", "a", ")", ".", "max", "for", "a", "in", "args", "]" ]
Returns the minimum of a Dimension TODO: conversion is not implemented yet but should be
[ "Returns", "the", "minimum", "of", "a", "Dimension" ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L1388-L1396
train
jahuth/litus
spikes.py
SpikeContainer.get_max
def get_max(self,*args,**kwargs): """ Returns the maximum of a Dimension TODO: conversion is not implemented yet but should be """ if len(args) == 1: return self.spike_times.get_label(args[0]).max return [self.spike_times.get_label(a).max for a in args]
python
def get_max(self,*args,**kwargs): """ Returns the maximum of a Dimension TODO: conversion is not implemented yet but should be """ if len(args) == 1: return self.spike_times.get_label(args[0]).max return [self.spike_times.get_label(a).max for a in args]
[ "def", "get_max", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "return", "self", ".", "spike_times", ".", "get_label", "(", "args", "[", "0", "]", ")", ".", "max", "return", "[", "self", ".", "spike_times", ".", "get_label", "(", "a", ")", ".", "max", "for", "a", "in", "args", "]" ]
Returns the maximum of a Dimension TODO: conversion is not implemented yet but should be
[ "Returns", "the", "maximum", "of", "a", "Dimension" ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L1397-L1405
train
jahuth/litus
spikes.py
SpikeContainer.linspace_bins
def linspace_bins(self,dim,*args,**kwargs): """ Like linspace, but shifts the space to create edges for histograms. """ return self.spike_times.get_label(dim).linspace_bins(*args,**kwargs)
python
def linspace_bins(self,dim,*args,**kwargs): """ Like linspace, but shifts the space to create edges for histograms. """ return self.spike_times.get_label(dim).linspace_bins(*args,**kwargs)
[ "def", "linspace_bins", "(", "self", ",", "dim", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "spike_times", ".", "get_label", "(", "dim", ")", ".", "linspace_bins", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Like linspace, but shifts the space to create edges for histograms.
[ "Like", "linspace", "but", "shifts", "the", "space", "to", "create", "edges", "for", "histograms", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L1432-L1436
train
jahuth/litus
spikes.py
SpikeContainer.create_SpikeGeneratorGroup
def create_SpikeGeneratorGroup(self,time_label=0,index_label=1,reorder_indices=False,index_offset=True): """ Creates a brian 2 create_SpikeGeneratorGroup object that contains the spikes in this container. time_label: Name or number of the label that contains the spike times (default: 0 / first column) index_label: Name or number of the label that contains the cell indices (default: 1 / the second column) reorder_indices: If the cell indices do not matter, the SpikeGeneratorGroup can be created with only as many unique neurons as necessary (default: False / The indices are preserved) index_offset: If set to a number, this will be subtracted from every index (default: True) If set to True, the `.min` of the label dimension will be subtracted. If set to False, nothing will be subtracted. """ import brian2 spike_times = self.spike_times.convert(time_label,'s')[time_label]*brian2.second indices = [0] * len(spike_times) if len(self.spike_times.find_labels(index_label)): indices = self.spike_times[index_label] if index_offset is not False: if index_offset is True: indices = indices - self.spike_times.get_label(index_label).min else: indices = indices - index_offset N = np.max(indices) else: N = self.spike_times.get_label(index_label).max if reorder_indices: indices_levels = np.sort(np.unique(indices)).tolist() indices = np.array([indices_levels.index(i) for i in indices]) N = len(indices_levels) return brian2.SpikeGeneratorGroup(N+1,indices = indices, times = spike_times)
python
def create_SpikeGeneratorGroup(self,time_label=0,index_label=1,reorder_indices=False,index_offset=True): """ Creates a brian 2 create_SpikeGeneratorGroup object that contains the spikes in this container. time_label: Name or number of the label that contains the spike times (default: 0 / first column) index_label: Name or number of the label that contains the cell indices (default: 1 / the second column) reorder_indices: If the cell indices do not matter, the SpikeGeneratorGroup can be created with only as many unique neurons as necessary (default: False / The indices are preserved) index_offset: If set to a number, this will be subtracted from every index (default: True) If set to True, the `.min` of the label dimension will be subtracted. If set to False, nothing will be subtracted. """ import brian2 spike_times = self.spike_times.convert(time_label,'s')[time_label]*brian2.second indices = [0] * len(spike_times) if len(self.spike_times.find_labels(index_label)): indices = self.spike_times[index_label] if index_offset is not False: if index_offset is True: indices = indices - self.spike_times.get_label(index_label).min else: indices = indices - index_offset N = np.max(indices) else: N = self.spike_times.get_label(index_label).max if reorder_indices: indices_levels = np.sort(np.unique(indices)).tolist() indices = np.array([indices_levels.index(i) for i in indices]) N = len(indices_levels) return brian2.SpikeGeneratorGroup(N+1,indices = indices, times = spike_times)
[ "def", "create_SpikeGeneratorGroup", "(", "self", ",", "time_label", "=", "0", ",", "index_label", "=", "1", ",", "reorder_indices", "=", "False", ",", "index_offset", "=", "True", ")", ":", "import", "brian2", "spike_times", "=", "self", ".", "spike_times", ".", "convert", "(", "time_label", ",", "'s'", ")", "[", "time_label", "]", "*", "brian2", ".", "second", "indices", "=", "[", "0", "]", "*", "len", "(", "spike_times", ")", "if", "len", "(", "self", ".", "spike_times", ".", "find_labels", "(", "index_label", ")", ")", ":", "indices", "=", "self", ".", "spike_times", "[", "index_label", "]", "if", "index_offset", "is", "not", "False", ":", "if", "index_offset", "is", "True", ":", "indices", "=", "indices", "-", "self", ".", "spike_times", ".", "get_label", "(", "index_label", ")", ".", "min", "else", ":", "indices", "=", "indices", "-", "index_offset", "N", "=", "np", ".", "max", "(", "indices", ")", "else", ":", "N", "=", "self", ".", "spike_times", ".", "get_label", "(", "index_label", ")", ".", "max", "if", "reorder_indices", ":", "indices_levels", "=", "np", ".", "sort", "(", "np", ".", "unique", "(", "indices", ")", ")", ".", "tolist", "(", ")", "indices", "=", "np", ".", "array", "(", "[", "indices_levels", ".", "index", "(", "i", ")", "for", "i", "in", "indices", "]", ")", "N", "=", "len", "(", "indices_levels", ")", "return", "brian2", ".", "SpikeGeneratorGroup", "(", "N", "+", "1", ",", "indices", "=", "indices", ",", "times", "=", "spike_times", ")" ]
Creates a brian 2 create_SpikeGeneratorGroup object that contains the spikes in this container. time_label: Name or number of the label that contains the spike times (default: 0 / first column) index_label: Name or number of the label that contains the cell indices (default: 1 / the second column) reorder_indices: If the cell indices do not matter, the SpikeGeneratorGroup can be created with only as many unique neurons as necessary (default: False / The indices are preserved) index_offset: If set to a number, this will be subtracted from every index (default: True) If set to True, the `.min` of the label dimension will be subtracted. If set to False, nothing will be subtracted.
[ "Creates", "a", "brian", "2", "create_SpikeGeneratorGroup", "object", "that", "contains", "the", "spikes", "in", "this", "container", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L1495-L1524
train
jahuth/litus
spikes.py
SpikeContainer.to_neo
def to_neo(self,index_label='N',time_label=0,name='segment of exported spikes',index=0): """ Returns a `neo` Segment containing the spike trains. Example usage:: import quantities as pq seg = sp.to_neo() fig = pyplot.figure() trains = [st.rescale('s').magnitude for st in seg.spiketrains] colors = pyplot.cm.jet(np.linspace(0, 1, len(seg.spiketrains))) gca().eventplot(trains, colors=colors) gca().set_title(seg.file_origin) f = neo.io.AsciiSpikeTrainIO('a_spike_file.txt') f.write_segment(seg) """ import neo from quantities import s seq = neo.Segment(name=name,index=index) t_start = None t_stop = None if self.min_t is not None: t_start = convert_time(self.min_t,from_units=self.units,to_units='s')*s if self.max_t is not None: t_stop = convert_time(self.max_t,from_units=self.units,to_units='s')*s for train in self.generate(index_label): seq.spiketrains.append(neo.SpikeTrain(train.spike_times.get_converted(time_label,'s')[1]*s,t_start=t_start,t_stop=t_stop)) return seq
python
def to_neo(self,index_label='N',time_label=0,name='segment of exported spikes',index=0): """ Returns a `neo` Segment containing the spike trains. Example usage:: import quantities as pq seg = sp.to_neo() fig = pyplot.figure() trains = [st.rescale('s').magnitude for st in seg.spiketrains] colors = pyplot.cm.jet(np.linspace(0, 1, len(seg.spiketrains))) gca().eventplot(trains, colors=colors) gca().set_title(seg.file_origin) f = neo.io.AsciiSpikeTrainIO('a_spike_file.txt') f.write_segment(seg) """ import neo from quantities import s seq = neo.Segment(name=name,index=index) t_start = None t_stop = None if self.min_t is not None: t_start = convert_time(self.min_t,from_units=self.units,to_units='s')*s if self.max_t is not None: t_stop = convert_time(self.max_t,from_units=self.units,to_units='s')*s for train in self.generate(index_label): seq.spiketrains.append(neo.SpikeTrain(train.spike_times.get_converted(time_label,'s')[1]*s,t_start=t_start,t_stop=t_stop)) return seq
[ "def", "to_neo", "(", "self", ",", "index_label", "=", "'N'", ",", "time_label", "=", "0", ",", "name", "=", "'segment of exported spikes'", ",", "index", "=", "0", ")", ":", "import", "neo", "from", "quantities", "import", "s", "seq", "=", "neo", ".", "Segment", "(", "name", "=", "name", ",", "index", "=", "index", ")", "t_start", "=", "None", "t_stop", "=", "None", "if", "self", ".", "min_t", "is", "not", "None", ":", "t_start", "=", "convert_time", "(", "self", ".", "min_t", ",", "from_units", "=", "self", ".", "units", ",", "to_units", "=", "'s'", ")", "*", "s", "if", "self", ".", "max_t", "is", "not", "None", ":", "t_stop", "=", "convert_time", "(", "self", ".", "max_t", ",", "from_units", "=", "self", ".", "units", ",", "to_units", "=", "'s'", ")", "*", "s", "for", "train", "in", "self", ".", "generate", "(", "index_label", ")", ":", "seq", ".", "spiketrains", ".", "append", "(", "neo", ".", "SpikeTrain", "(", "train", ".", "spike_times", ".", "get_converted", "(", "time_label", ",", "'s'", ")", "[", "1", "]", "*", "s", ",", "t_start", "=", "t_start", ",", "t_stop", "=", "t_stop", ")", ")", "return", "seq" ]
Returns a `neo` Segment containing the spike trains. Example usage:: import quantities as pq seg = sp.to_neo() fig = pyplot.figure() trains = [st.rescale('s').magnitude for st in seg.spiketrains] colors = pyplot.cm.jet(np.linspace(0, 1, len(seg.spiketrains))) gca().eventplot(trains, colors=colors) gca().set_title(seg.file_origin) f = neo.io.AsciiSpikeTrainIO('a_spike_file.txt') f.write_segment(seg)
[ "Returns", "a", "neo", "Segment", "containing", "the", "spike", "trains", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/spikes.py#L1525-L1556
train
olitheolix/qtmacs
qtmacs/applets/scieditor.py
SciEditor.qteModificationChanged
def qteModificationChanged(self, mod): """ Update the modification status in the mode bar. This slot is Connected to the ``modificationChanged`` signal from the ``QtmacsScintilla`` widget. """ if mod: s = '*' else: s = '-' self._qteModeBar.qteChangeModeValue('MODIFIED', s)
python
def qteModificationChanged(self, mod): """ Update the modification status in the mode bar. This slot is Connected to the ``modificationChanged`` signal from the ``QtmacsScintilla`` widget. """ if mod: s = '*' else: s = '-' self._qteModeBar.qteChangeModeValue('MODIFIED', s)
[ "def", "qteModificationChanged", "(", "self", ",", "mod", ")", ":", "if", "mod", ":", "s", "=", "'*'", "else", ":", "s", "=", "'-'", "self", ".", "_qteModeBar", ".", "qteChangeModeValue", "(", "'MODIFIED'", ",", "s", ")" ]
Update the modification status in the mode bar. This slot is Connected to the ``modificationChanged`` signal from the ``QtmacsScintilla`` widget.
[ "Update", "the", "modification", "status", "in", "the", "mode", "bar", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/applets/scieditor.py#L214-L225
train
olitheolix/qtmacs
qtmacs/applets/scieditor.py
SciEditor.loadFile
def loadFile(self, fileName): """ Display the file ``fileName``. """ self.fileName = fileName # Assign QFile object with the current name. self.file = QtCore.QFile(fileName) if self.file.exists(): # Load the file into the widget and reset the undo stack # to delete the undo object create by the setText method. # Without it, an undo operation would delete the content # of the widget which is intuitive. self.qteScintilla.setText(open(fileName).read()) self.qteScintilla.qteUndoStack.reset() else: msg = "File <b>{}</b> does not exist".format(self.qteAppletID()) self.qteLogger.info(msg)
python
def loadFile(self, fileName): """ Display the file ``fileName``. """ self.fileName = fileName # Assign QFile object with the current name. self.file = QtCore.QFile(fileName) if self.file.exists(): # Load the file into the widget and reset the undo stack # to delete the undo object create by the setText method. # Without it, an undo operation would delete the content # of the widget which is intuitive. self.qteScintilla.setText(open(fileName).read()) self.qteScintilla.qteUndoStack.reset() else: msg = "File <b>{}</b> does not exist".format(self.qteAppletID()) self.qteLogger.info(msg)
[ "def", "loadFile", "(", "self", ",", "fileName", ")", ":", "self", ".", "fileName", "=", "fileName", "# Assign QFile object with the current name.", "self", ".", "file", "=", "QtCore", ".", "QFile", "(", "fileName", ")", "if", "self", ".", "file", ".", "exists", "(", ")", ":", "# Load the file into the widget and reset the undo stack", "# to delete the undo object create by the setText method.", "# Without it, an undo operation would delete the content", "# of the widget which is intuitive.", "self", ".", "qteScintilla", ".", "setText", "(", "open", "(", "fileName", ")", ".", "read", "(", ")", ")", "self", ".", "qteScintilla", ".", "qteUndoStack", ".", "reset", "(", ")", "else", ":", "msg", "=", "\"File <b>{}</b> does not exist\"", ".", "format", "(", "self", ".", "qteAppletID", "(", ")", ")", "self", ".", "qteLogger", ".", "info", "(", "msg", ")" ]
Display the file ``fileName``.
[ "Display", "the", "file", "fileName", "." ]
36253b082b82590f183fe154b053eb3a1e741be2
https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/applets/scieditor.py#L239-L256
train
noobermin/pys
pys/__init__.py
conv
def conv(arg,default=None,func=None): ''' essentially, the generalization of arg if arg else default or func(arg) if arg else default ''' if func: return func(arg) if arg else default; else: return arg if arg else default;
python
def conv(arg,default=None,func=None): ''' essentially, the generalization of arg if arg else default or func(arg) if arg else default ''' if func: return func(arg) if arg else default; else: return arg if arg else default;
[ "def", "conv", "(", "arg", ",", "default", "=", "None", ",", "func", "=", "None", ")", ":", "if", "func", ":", "return", "func", "(", "arg", ")", "if", "arg", "else", "default", "else", ":", "return", "arg", "if", "arg", "else", "default" ]
essentially, the generalization of arg if arg else default or func(arg) if arg else default
[ "essentially", "the", "generalization", "of", "arg", "if", "arg", "else", "default" ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L10-L23
train
noobermin/pys
pys/__init__.py
dump_pickle
def dump_pickle(name, obj): '''quick pickle dump similar to np.save''' with open(name,"wb") as f: pickle.dump(obj,f,2); pass;
python
def dump_pickle(name, obj): '''quick pickle dump similar to np.save''' with open(name,"wb") as f: pickle.dump(obj,f,2); pass;
[ "def", "dump_pickle", "(", "name", ",", "obj", ")", ":", "with", "open", "(", "name", ",", "\"wb\"", ")", "as", "f", ":", "pickle", ".", "dump", "(", "obj", ",", "f", ",", "2", ")", "pass" ]
quick pickle dump similar to np.save
[ "quick", "pickle", "dump", "similar", "to", "np", ".", "save" ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L36-L40
train
noobermin/pys
pys/__init__.py
chunks
def chunks(l,n): '''chunk l in n sized bits''' #http://stackoverflow.com/a/3226719 #...not that this is hard to understand. return [l[x:x+n] for x in range(0, len(l), n)];
python
def chunks(l,n): '''chunk l in n sized bits''' #http://stackoverflow.com/a/3226719 #...not that this is hard to understand. return [l[x:x+n] for x in range(0, len(l), n)];
[ "def", "chunks", "(", "l", ",", "n", ")", ":", "#http://stackoverflow.com/a/3226719", "#...not that this is hard to understand.", "return", "[", "l", "[", "x", ":", "x", "+", "n", "]", "for", "x", "in", "range", "(", "0", ",", "len", "(", "l", ")", ",", "n", ")", "]" ]
chunk l in n sized bits
[ "chunk", "l", "in", "n", "sized", "bits" ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L48-L52
train
noobermin/pys
pys/__init__.py
check_vprint
def check_vprint(s, vprinter): '''checked verbose printing''' if vprinter is True: print(s); elif callable(vprinter): vprinter(s);
python
def check_vprint(s, vprinter): '''checked verbose printing''' if vprinter is True: print(s); elif callable(vprinter): vprinter(s);
[ "def", "check_vprint", "(", "s", ",", "vprinter", ")", ":", "if", "vprinter", "is", "True", ":", "print", "(", "s", ")", "elif", "callable", "(", "vprinter", ")", ":", "vprinter", "(", "s", ")" ]
checked verbose printing
[ "checked", "verbose", "printing" ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L54-L59
train
noobermin/pys
pys/__init__.py
filelines
def filelines(fname,strip=False): '''read lines from a file into lines...optional strip''' with open(fname,'r') as f: lines = f.readlines(); if strip: lines[:] = [line.strip() for line in lines] return lines;
python
def filelines(fname,strip=False): '''read lines from a file into lines...optional strip''' with open(fname,'r') as f: lines = f.readlines(); if strip: lines[:] = [line.strip() for line in lines] return lines;
[ "def", "filelines", "(", "fname", ",", "strip", "=", "False", ")", ":", "with", "open", "(", "fname", ",", "'r'", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "if", "strip", ":", "lines", "[", ":", "]", "=", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "lines", "]", "return", "lines" ]
read lines from a file into lines...optional strip
[ "read", "lines", "from", "a", "file", "into", "lines", "...", "optional", "strip" ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L69-L75
train
noobermin/pys
pys/__init__.py
parse_utuple
def parse_utuple(s,urx,length=2): '''parse a string into a list of a uniform type''' if type(urx) != str: urx=urx.pattern; if length is not None and length < 1: raise ValueError("invalid length: {}".format(length)); if length == 1: rx = r"^ *\( *{urx} *,? *\) *$".format(urx=urx); elif length is None: rx = r"^ *\( *(?:{urx} *, *)*{urx} *,? *\) *$".format(urx=urx); else: rx = r"^ *\( *(?:{urx} *, *){{{rep1}}}{urx} *,? *\) *$".format( rep1=length-1, urx=urx); return re.match(rx,s);
python
def parse_utuple(s,urx,length=2): '''parse a string into a list of a uniform type''' if type(urx) != str: urx=urx.pattern; if length is not None and length < 1: raise ValueError("invalid length: {}".format(length)); if length == 1: rx = r"^ *\( *{urx} *,? *\) *$".format(urx=urx); elif length is None: rx = r"^ *\( *(?:{urx} *, *)*{urx} *,? *\) *$".format(urx=urx); else: rx = r"^ *\( *(?:{urx} *, *){{{rep1}}}{urx} *,? *\) *$".format( rep1=length-1, urx=urx); return re.match(rx,s);
[ "def", "parse_utuple", "(", "s", ",", "urx", ",", "length", "=", "2", ")", ":", "if", "type", "(", "urx", ")", "!=", "str", ":", "urx", "=", "urx", ".", "pattern", "if", "length", "is", "not", "None", "and", "length", "<", "1", ":", "raise", "ValueError", "(", "\"invalid length: {}\"", ".", "format", "(", "length", ")", ")", "if", "length", "==", "1", ":", "rx", "=", "r\"^ *\\( *{urx} *,? *\\) *$\"", ".", "format", "(", "urx", "=", "urx", ")", "elif", "length", "is", "None", ":", "rx", "=", "r\"^ *\\( *(?:{urx} *, *)*{urx} *,? *\\) *$\"", ".", "format", "(", "urx", "=", "urx", ")", "else", ":", "rx", "=", "r\"^ *\\( *(?:{urx} *, *){{{rep1}}}{urx} *,? *\\) *$\"", ".", "format", "(", "rep1", "=", "length", "-", "1", ",", "urx", "=", "urx", ")", "return", "re", ".", "match", "(", "rx", ",", "s", ")" ]
parse a string into a list of a uniform type
[ "parse", "a", "string", "into", "a", "list", "of", "a", "uniform", "type" ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L90-L104
train
noobermin/pys
pys/__init__.py
parse_numtuple
def parse_numtuple(s,intype,length=2,scale=1): '''parse a string into a list of numbers of a type''' if intype == int: numrx = intrx_s; elif intype == float: numrx = fltrx_s; else: raise NotImplementedError("Not implemented for type: {}".format( intype)); if parse_utuple(s, numrx, length=length) is None: raise ValueError("{} is not a valid number tuple.".format(s)); return [x*scale for x in evalt(s)];
python
def parse_numtuple(s,intype,length=2,scale=1): '''parse a string into a list of numbers of a type''' if intype == int: numrx = intrx_s; elif intype == float: numrx = fltrx_s; else: raise NotImplementedError("Not implemented for type: {}".format( intype)); if parse_utuple(s, numrx, length=length) is None: raise ValueError("{} is not a valid number tuple.".format(s)); return [x*scale for x in evalt(s)];
[ "def", "parse_numtuple", "(", "s", ",", "intype", ",", "length", "=", "2", ",", "scale", "=", "1", ")", ":", "if", "intype", "==", "int", ":", "numrx", "=", "intrx_s", "elif", "intype", "==", "float", ":", "numrx", "=", "fltrx_s", "else", ":", "raise", "NotImplementedError", "(", "\"Not implemented for type: {}\"", ".", "format", "(", "intype", ")", ")", "if", "parse_utuple", "(", "s", ",", "numrx", ",", "length", "=", "length", ")", "is", "None", ":", "raise", "ValueError", "(", "\"{} is not a valid number tuple.\"", ".", "format", "(", "s", ")", ")", "return", "[", "x", "*", "scale", "for", "x", "in", "evalt", "(", "s", ")", "]" ]
parse a string into a list of numbers of a type
[ "parse", "a", "string", "into", "a", "list", "of", "numbers", "of", "a", "type" ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L110-L121
train
noobermin/pys
pys/__init__.py
parse_ctuple
def parse_ctuple(s,length=2): '''parse a string of acceptable colors into matplotlib, that is, either strings, or three tuples of rgb. Don't quote strings. ''' if parse_utuple(s, colrx_s, length=length) is None: raise ValueError("{} is not a valid color tuple.".format(s)); #quote strings s=quote_subs(s,colorfix=True); return evalt(s);
python
def parse_ctuple(s,length=2): '''parse a string of acceptable colors into matplotlib, that is, either strings, or three tuples of rgb. Don't quote strings. ''' if parse_utuple(s, colrx_s, length=length) is None: raise ValueError("{} is not a valid color tuple.".format(s)); #quote strings s=quote_subs(s,colorfix=True); return evalt(s);
[ "def", "parse_ctuple", "(", "s", ",", "length", "=", "2", ")", ":", "if", "parse_utuple", "(", "s", ",", "colrx_s", ",", "length", "=", "length", ")", "is", "None", ":", "raise", "ValueError", "(", "\"{} is not a valid color tuple.\"", ".", "format", "(", "s", ")", ")", "#quote strings", "s", "=", "quote_subs", "(", "s", ",", "colorfix", "=", "True", ")", "return", "evalt", "(", "s", ")" ]
parse a string of acceptable colors into matplotlib, that is, either strings, or three tuples of rgb. Don't quote strings.
[ "parse", "a", "string", "of", "acceptable", "colors", "into", "matplotlib", "that", "is", "either", "strings", "or", "three", "tuples", "of", "rgb", ".", "Don", "t", "quote", "strings", "." ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L130-L138
train
noobermin/pys
pys/__init__.py
parse_stuple
def parse_stuple(s,length=2): '''parse a string of strings. Don't quote strings''' if parse_utuple(s, isrx_s, length=length) is None: raise ValueError("{} is not a valid string tuple.".format(s)); s = quote_subs(s); return evalt(s);
python
def parse_stuple(s,length=2): '''parse a string of strings. Don't quote strings''' if parse_utuple(s, isrx_s, length=length) is None: raise ValueError("{} is not a valid string tuple.".format(s)); s = quote_subs(s); return evalt(s);
[ "def", "parse_stuple", "(", "s", ",", "length", "=", "2", ")", ":", "if", "parse_utuple", "(", "s", ",", "isrx_s", ",", "length", "=", "length", ")", "is", "None", ":", "raise", "ValueError", "(", "\"{} is not a valid string tuple.\"", ".", "format", "(", "s", ")", ")", "s", "=", "quote_subs", "(", "s", ")", "return", "evalt", "(", "s", ")" ]
parse a string of strings. Don't quote strings
[ "parse", "a", "string", "of", "strings", ".", "Don", "t", "quote", "strings" ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L140-L145
train
noobermin/pys
pys/__init__.py
parse_colors
def parse_colors(s, length=1): '''helper for parsing a string that can be either a matplotlib color or be a tuple of colors. Returns a tuple of them either way. ''' if length and length > 1: return parse_ctuple(s,length=length); if re.match('^ *{} *$'.format(isrx_s), s): #it's just a string. return [s]; elif re.match('^ *{} *$'.format(rgbrx_s), s): return [eval(s)]; else: return parse_ctuple(s,length=length);
python
def parse_colors(s, length=1): '''helper for parsing a string that can be either a matplotlib color or be a tuple of colors. Returns a tuple of them either way. ''' if length and length > 1: return parse_ctuple(s,length=length); if re.match('^ *{} *$'.format(isrx_s), s): #it's just a string. return [s]; elif re.match('^ *{} *$'.format(rgbrx_s), s): return [eval(s)]; else: return parse_ctuple(s,length=length);
[ "def", "parse_colors", "(", "s", ",", "length", "=", "1", ")", ":", "if", "length", "and", "length", ">", "1", ":", "return", "parse_ctuple", "(", "s", ",", "length", "=", "length", ")", "if", "re", ".", "match", "(", "'^ *{} *$'", ".", "format", "(", "isrx_s", ")", ",", "s", ")", ":", "#it's just a string.", "return", "[", "s", "]", "elif", "re", ".", "match", "(", "'^ *{} *$'", ".", "format", "(", "rgbrx_s", ")", ",", "s", ")", ":", "return", "[", "eval", "(", "s", ")", "]", "else", ":", "return", "parse_ctuple", "(", "s", ",", "length", "=", "length", ")" ]
helper for parsing a string that can be either a matplotlib color or be a tuple of colors. Returns a tuple of them either way.
[ "helper", "for", "parsing", "a", "string", "that", "can", "be", "either", "a", "matplotlib", "color", "or", "be", "a", "tuple", "of", "colors", ".", "Returns", "a", "tuple", "of", "them", "either", "way", "." ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L155-L168
train
noobermin/pys
pys/__init__.py
parse_qs
def parse_qs(s, rx, parsef=None, length=2, quote=False): '''helper for parsing a string that can both rx or parsef which is obstensibly the parsef for rx. Use parse colors for color tuples. This won't work with those. ''' if type(rx) != str: rx = rx.pattern; if re.match(" *\(.*\)", s): if not parsef: if parse_utuple(s,rx,length=length): if quote: s=quote_subs(s); return evalt(s); else: raise ValueError("{} did is not a valid tuple of {}".format( s, rx)); else: return parsef(s,length=length); elif re.match('^ *{} *$'.format(rx), s): if quote: return eval('["{}"]'.format(s)); return eval('[{}]'.format(s)); else: raise ValueError("{} does not match '{}' or the passed parsef".format( s,rx));
python
def parse_qs(s, rx, parsef=None, length=2, quote=False): '''helper for parsing a string that can both rx or parsef which is obstensibly the parsef for rx. Use parse colors for color tuples. This won't work with those. ''' if type(rx) != str: rx = rx.pattern; if re.match(" *\(.*\)", s): if not parsef: if parse_utuple(s,rx,length=length): if quote: s=quote_subs(s); return evalt(s); else: raise ValueError("{} did is not a valid tuple of {}".format( s, rx)); else: return parsef(s,length=length); elif re.match('^ *{} *$'.format(rx), s): if quote: return eval('["{}"]'.format(s)); return eval('[{}]'.format(s)); else: raise ValueError("{} does not match '{}' or the passed parsef".format( s,rx));
[ "def", "parse_qs", "(", "s", ",", "rx", ",", "parsef", "=", "None", ",", "length", "=", "2", ",", "quote", "=", "False", ")", ":", "if", "type", "(", "rx", ")", "!=", "str", ":", "rx", "=", "rx", ".", "pattern", "if", "re", ".", "match", "(", "\" *\\(.*\\)\"", ",", "s", ")", ":", "if", "not", "parsef", ":", "if", "parse_utuple", "(", "s", ",", "rx", ",", "length", "=", "length", ")", ":", "if", "quote", ":", "s", "=", "quote_subs", "(", "s", ")", "return", "evalt", "(", "s", ")", "else", ":", "raise", "ValueError", "(", "\"{} did is not a valid tuple of {}\"", ".", "format", "(", "s", ",", "rx", ")", ")", "else", ":", "return", "parsef", "(", "s", ",", "length", "=", "length", ")", "elif", "re", ".", "match", "(", "'^ *{} *$'", ".", "format", "(", "rx", ")", ",", "s", ")", ":", "if", "quote", ":", "return", "eval", "(", "'[\"{}\"]'", ".", "format", "(", "s", ")", ")", "return", "eval", "(", "'[{}]'", ".", "format", "(", "s", ")", ")", "else", ":", "raise", "ValueError", "(", "\"{} does not match '{}' or the passed parsef\"", ".", "format", "(", "s", ",", "rx", ")", ")" ]
helper for parsing a string that can both rx or parsef which is obstensibly the parsef for rx. Use parse colors for color tuples. This won't work with those.
[ "helper", "for", "parsing", "a", "string", "that", "can", "both", "rx", "or", "parsef", "which", "is", "obstensibly", "the", "parsef", "for", "rx", "." ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L170-L196
train
noobermin/pys
pys/__init__.py
sd
def sd(d,**kw): ''' A hack to return a modified dict dynamically. Basically, Does "classless OOP" as in js but with dicts, although not really for the "verb" parts of OOP but more of the "subject" stuff. Confused? Here's how it works: `d` is a dict. We have that sd(d, perfect=42, gf='qt3.14') returns a dict like d but with d['perfect']==42 and d['gf']=='qt3.14'. 'sd' stands for "setdefault" which is, you know, what we do when we set elements of a dict. I plan to use this heavily. ''' #HURR SO COMPLICATED r={}; #copy. if you want to modify, r.update(d); #use {}.update r.update(kw); return r;
python
def sd(d,**kw): ''' A hack to return a modified dict dynamically. Basically, Does "classless OOP" as in js but with dicts, although not really for the "verb" parts of OOP but more of the "subject" stuff. Confused? Here's how it works: `d` is a dict. We have that sd(d, perfect=42, gf='qt3.14') returns a dict like d but with d['perfect']==42 and d['gf']=='qt3.14'. 'sd' stands for "setdefault" which is, you know, what we do when we set elements of a dict. I plan to use this heavily. ''' #HURR SO COMPLICATED r={}; #copy. if you want to modify, r.update(d); #use {}.update r.update(kw); return r;
[ "def", "sd", "(", "d", ",", "*", "*", "kw", ")", ":", "#HURR SO COMPLICATED", "r", "=", "{", "}", "#copy. if you want to modify,", "r", ".", "update", "(", "d", ")", "#use {}.update", "r", ".", "update", "(", "kw", ")", "return", "r" ]
A hack to return a modified dict dynamically. Basically, Does "classless OOP" as in js but with dicts, although not really for the "verb" parts of OOP but more of the "subject" stuff. Confused? Here's how it works: `d` is a dict. We have that sd(d, perfect=42, gf='qt3.14') returns a dict like d but with d['perfect']==42 and d['gf']=='qt3.14'. 'sd' stands for "setdefault" which is, you know, what we do when we set elements of a dict. I plan to use this heavily.
[ "A", "hack", "to", "return", "a", "modified", "dict", "dynamically", ".", "Basically", "Does", "classless", "OOP", "as", "in", "js", "but", "with", "dicts", "although", "not", "really", "for", "the", "verb", "parts", "of", "OOP", "but", "more", "of", "the", "subject", "stuff", "." ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L199-L222
train
noobermin/pys
pys/__init__.py
mk_getkw
def mk_getkw(kw, defaults,prefer_passed=False): ''' a helper for generating a function for reading keywords in interface functions with a dictionary with defaults expects the defaults dictionary to have keywords you request. example: defaults = dict(a='a',b=3); def bigfunc(**kw): getkw=mk_getkw(kw,defaults); # I want the callers' `a', or the default if s/he doesn't # supply it a=getkw('a'); c = [a]*getkw('b'); return c,c[0]; Option: prefer_passed -- use "l in kw" only, not test. ''' def getkw(*ls): r = [ kw[l] if test(kw,l) else defaults[l] for l in ls ]; if len(r) == 1: return r[0]; return r; def getkw_prefer_passed(*ls): r = [ kw[l] if l in kw else defaults[l] for l in ls ]; if len(r) == 1: return r[0]; return r; return getkw if not prefer_passed else getkw_prefer_passed;
python
def mk_getkw(kw, defaults,prefer_passed=False): ''' a helper for generating a function for reading keywords in interface functions with a dictionary with defaults expects the defaults dictionary to have keywords you request. example: defaults = dict(a='a',b=3); def bigfunc(**kw): getkw=mk_getkw(kw,defaults); # I want the callers' `a', or the default if s/he doesn't # supply it a=getkw('a'); c = [a]*getkw('b'); return c,c[0]; Option: prefer_passed -- use "l in kw" only, not test. ''' def getkw(*ls): r = [ kw[l] if test(kw,l) else defaults[l] for l in ls ]; if len(r) == 1: return r[0]; return r; def getkw_prefer_passed(*ls): r = [ kw[l] if l in kw else defaults[l] for l in ls ]; if len(r) == 1: return r[0]; return r; return getkw if not prefer_passed else getkw_prefer_passed;
[ "def", "mk_getkw", "(", "kw", ",", "defaults", ",", "prefer_passed", "=", "False", ")", ":", "def", "getkw", "(", "*", "ls", ")", ":", "r", "=", "[", "kw", "[", "l", "]", "if", "test", "(", "kw", ",", "l", ")", "else", "defaults", "[", "l", "]", "for", "l", "in", "ls", "]", "if", "len", "(", "r", ")", "==", "1", ":", "return", "r", "[", "0", "]", "return", "r", "def", "getkw_prefer_passed", "(", "*", "ls", ")", ":", "r", "=", "[", "kw", "[", "l", "]", "if", "l", "in", "kw", "else", "defaults", "[", "l", "]", "for", "l", "in", "ls", "]", "if", "len", "(", "r", ")", "==", "1", ":", "return", "r", "[", "0", "]", "return", "r", "return", "getkw", "if", "not", "prefer_passed", "else", "getkw_prefer_passed" ]
a helper for generating a function for reading keywords in interface functions with a dictionary with defaults expects the defaults dictionary to have keywords you request. example: defaults = dict(a='a',b=3); def bigfunc(**kw): getkw=mk_getkw(kw,defaults); # I want the callers' `a', or the default if s/he doesn't # supply it a=getkw('a'); c = [a]*getkw('b'); return c,c[0]; Option: prefer_passed -- use "l in kw" only, not test.
[ "a", "helper", "for", "generating", "a", "function", "for", "reading", "keywords", "in", "interface", "functions", "with", "a", "dictionary", "with", "defaults" ]
e01b74210c65eb96d019bb42e0a3c9e6676da943
https://github.com/noobermin/pys/blob/e01b74210c65eb96d019bb42e0a3c9e6676da943/pys/__init__.py#L250-L281
train
consbio/restle
restle/resources.py
Resource._load_resource
def _load_resource(self): """Load resource data from server""" url = self._url if self._params: url += '?{0}'.format(six.moves.urllib_parse.urlencode(self._params)) r = getattr(self._session, self._meta.get_method.lower())(url) if r.status_code == 404: raise NotFoundException('Server returned 404 Not Found for the URL {0}'.format(self._url)) elif not 200 <= r.status_code < 400: raise HTTPException('Server returned {0} ({1})'.format(r.status_code, r.reason), r) data = self._meta.deserializer.to_dict(r.text) self.populate_field_values(data)
python
def _load_resource(self): """Load resource data from server""" url = self._url if self._params: url += '?{0}'.format(six.moves.urllib_parse.urlencode(self._params)) r = getattr(self._session, self._meta.get_method.lower())(url) if r.status_code == 404: raise NotFoundException('Server returned 404 Not Found for the URL {0}'.format(self._url)) elif not 200 <= r.status_code < 400: raise HTTPException('Server returned {0} ({1})'.format(r.status_code, r.reason), r) data = self._meta.deserializer.to_dict(r.text) self.populate_field_values(data)
[ "def", "_load_resource", "(", "self", ")", ":", "url", "=", "self", ".", "_url", "if", "self", ".", "_params", ":", "url", "+=", "'?{0}'", ".", "format", "(", "six", ".", "moves", ".", "urllib_parse", ".", "urlencode", "(", "self", ".", "_params", ")", ")", "r", "=", "getattr", "(", "self", ".", "_session", ",", "self", ".", "_meta", ".", "get_method", ".", "lower", "(", ")", ")", "(", "url", ")", "if", "r", ".", "status_code", "==", "404", ":", "raise", "NotFoundException", "(", "'Server returned 404 Not Found for the URL {0}'", ".", "format", "(", "self", ".", "_url", ")", ")", "elif", "not", "200", "<=", "r", ".", "status_code", "<", "400", ":", "raise", "HTTPException", "(", "'Server returned {0} ({1})'", ".", "format", "(", "r", ".", "status_code", ",", "r", ".", "reason", ")", ",", "r", ")", "data", "=", "self", ".", "_meta", ".", "deserializer", ".", "to_dict", "(", "r", ".", "text", ")", "self", ".", "populate_field_values", "(", "data", ")" ]
Load resource data from server
[ "Load", "resource", "data", "from", "server" ]
60d100da034c612d4910f4f79eaa57a76eb3dcc6
https://github.com/consbio/restle/blob/60d100da034c612d4910f4f79eaa57a76eb3dcc6/restle/resources.py#L69-L84
train
consbio/restle
restle/resources.py
Resource.populate_field_values
def populate_field_values(self, data): """Load resource data and populate field values""" if not self._meta.case_sensitive_fields: data = {k.lower(): v for k, v in six.iteritems(data)} if self._meta.match_fuzzy_keys: # String any non-alphanumeric chars from each key data = {''.join(x for x in k if x in ALPHANUMERIC).lower(): v for k, v in six.iteritems(data)} for field in self._meta.fields: name = field.name if self._meta.case_sensitive_fields else field.name.lower() value = None if self._meta.match_fuzzy_keys: name = ''.join(x for x in name if x in ALPHANUMERIC).lower() if name in data: value = field.to_python(data[name], self) elif field.required and field.default is None: message = "Response from {0} is missing required field '{1}'".format(self._url, field.name) if self._strict: raise MissingFieldException(message) else: logger.warn(message) elif field.default is not None: value = copy.copy(field.default) setattr(self, field._attr_name, value) self._populated_field_values = True
python
def populate_field_values(self, data): """Load resource data and populate field values""" if not self._meta.case_sensitive_fields: data = {k.lower(): v for k, v in six.iteritems(data)} if self._meta.match_fuzzy_keys: # String any non-alphanumeric chars from each key data = {''.join(x for x in k if x in ALPHANUMERIC).lower(): v for k, v in six.iteritems(data)} for field in self._meta.fields: name = field.name if self._meta.case_sensitive_fields else field.name.lower() value = None if self._meta.match_fuzzy_keys: name = ''.join(x for x in name if x in ALPHANUMERIC).lower() if name in data: value = field.to_python(data[name], self) elif field.required and field.default is None: message = "Response from {0} is missing required field '{1}'".format(self._url, field.name) if self._strict: raise MissingFieldException(message) else: logger.warn(message) elif field.default is not None: value = copy.copy(field.default) setattr(self, field._attr_name, value) self._populated_field_values = True
[ "def", "populate_field_values", "(", "self", ",", "data", ")", ":", "if", "not", "self", ".", "_meta", ".", "case_sensitive_fields", ":", "data", "=", "{", "k", ".", "lower", "(", ")", ":", "v", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "data", ")", "}", "if", "self", ".", "_meta", ".", "match_fuzzy_keys", ":", "# String any non-alphanumeric chars from each key", "data", "=", "{", "''", ".", "join", "(", "x", "for", "x", "in", "k", "if", "x", "in", "ALPHANUMERIC", ")", ".", "lower", "(", ")", ":", "v", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "data", ")", "}", "for", "field", "in", "self", ".", "_meta", ".", "fields", ":", "name", "=", "field", ".", "name", "if", "self", ".", "_meta", ".", "case_sensitive_fields", "else", "field", ".", "name", ".", "lower", "(", ")", "value", "=", "None", "if", "self", ".", "_meta", ".", "match_fuzzy_keys", ":", "name", "=", "''", ".", "join", "(", "x", "for", "x", "in", "name", "if", "x", "in", "ALPHANUMERIC", ")", ".", "lower", "(", ")", "if", "name", "in", "data", ":", "value", "=", "field", ".", "to_python", "(", "data", "[", "name", "]", ",", "self", ")", "elif", "field", ".", "required", "and", "field", ".", "default", "is", "None", ":", "message", "=", "\"Response from {0} is missing required field '{1}'\"", ".", "format", "(", "self", ".", "_url", ",", "field", ".", "name", ")", "if", "self", ".", "_strict", ":", "raise", "MissingFieldException", "(", "message", ")", "else", ":", "logger", ".", "warn", "(", "message", ")", "elif", "field", ".", "default", "is", "not", "None", ":", "value", "=", "copy", ".", "copy", "(", "field", ".", "default", ")", "setattr", "(", "self", ",", "field", ".", "_attr_name", ",", "value", ")", "self", ".", "_populated_field_values", "=", "True" ]
Load resource data and populate field values
[ "Load", "resource", "data", "and", "populate", "field", "values" ]
60d100da034c612d4910f4f79eaa57a76eb3dcc6
https://github.com/consbio/restle/blob/60d100da034c612d4910f4f79eaa57a76eb3dcc6/restle/resources.py#L86-L116
train
a1ezzz/wasp-general
wasp_general/task/thread.py
WThreadTask.close_thread
def close_thread(self): """ Clear all object descriptors for stopped task. Task must be joined prior to calling this method. :return: None """ if self.__thread is not None and self.__thread.is_alive() is True: raise WThreadJoiningTimeoutError('Thread is still alive. Thread name: %s' % self.__thread.name) self.start_event().clear() self.__thread = None
python
def close_thread(self): """ Clear all object descriptors for stopped task. Task must be joined prior to calling this method. :return: None """ if self.__thread is not None and self.__thread.is_alive() is True: raise WThreadJoiningTimeoutError('Thread is still alive. Thread name: %s' % self.__thread.name) self.start_event().clear() self.__thread = None
[ "def", "close_thread", "(", "self", ")", ":", "if", "self", ".", "__thread", "is", "not", "None", "and", "self", ".", "__thread", ".", "is_alive", "(", ")", "is", "True", ":", "raise", "WThreadJoiningTimeoutError", "(", "'Thread is still alive. Thread name: %s'", "%", "self", ".", "__thread", ".", "name", ")", "self", ".", "start_event", "(", ")", ".", "clear", "(", ")", "self", ".", "__thread", "=", "None" ]
Clear all object descriptors for stopped task. Task must be joined prior to calling this method. :return: None
[ "Clear", "all", "object", "descriptors", "for", "stopped", "task", ".", "Task", "must", "be", "joined", "prior", "to", "calling", "this", "method", "." ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/thread.py#L166-L174
train
pmacosta/pexdoc
docs/support/trace_my_module_1.py
trace_module
def trace_module(no_print=True): """Trace my_module exceptions.""" pwd = os.path.dirname(__file__) script_name = os.path.join(pwd, "test_my_module.py") with pexdoc.ExDocCxt() as exdoc_obj: if pytest.main(["-s", "-vv", "-x", "{0}".format(script_name)]): raise RuntimeError("Tracing did not complete successfully") if not no_print: module_prefix = "docs.support.my_module." callable_names = ["func", "MyClass.value"] for callable_name in callable_names: callable_name = module_prefix + callable_name print("\nCallable: {0}".format(callable_name)) print(exdoc_obj.get_sphinx_doc(callable_name, width=70)) print("\n") return copy.copy(exdoc_obj)
python
def trace_module(no_print=True): """Trace my_module exceptions.""" pwd = os.path.dirname(__file__) script_name = os.path.join(pwd, "test_my_module.py") with pexdoc.ExDocCxt() as exdoc_obj: if pytest.main(["-s", "-vv", "-x", "{0}".format(script_name)]): raise RuntimeError("Tracing did not complete successfully") if not no_print: module_prefix = "docs.support.my_module." callable_names = ["func", "MyClass.value"] for callable_name in callable_names: callable_name = module_prefix + callable_name print("\nCallable: {0}".format(callable_name)) print(exdoc_obj.get_sphinx_doc(callable_name, width=70)) print("\n") return copy.copy(exdoc_obj)
[ "def", "trace_module", "(", "no_print", "=", "True", ")", ":", "pwd", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "script_name", "=", "os", ".", "path", ".", "join", "(", "pwd", ",", "\"test_my_module.py\"", ")", "with", "pexdoc", ".", "ExDocCxt", "(", ")", "as", "exdoc_obj", ":", "if", "pytest", ".", "main", "(", "[", "\"-s\"", ",", "\"-vv\"", ",", "\"-x\"", ",", "\"{0}\"", ".", "format", "(", "script_name", ")", "]", ")", ":", "raise", "RuntimeError", "(", "\"Tracing did not complete successfully\"", ")", "if", "not", "no_print", ":", "module_prefix", "=", "\"docs.support.my_module.\"", "callable_names", "=", "[", "\"func\"", ",", "\"MyClass.value\"", "]", "for", "callable_name", "in", "callable_names", ":", "callable_name", "=", "module_prefix", "+", "callable_name", "print", "(", "\"\\nCallable: {0}\"", ".", "format", "(", "callable_name", ")", ")", "print", "(", "exdoc_obj", ".", "get_sphinx_doc", "(", "callable_name", ",", "width", "=", "70", ")", ")", "print", "(", "\"\\n\"", ")", "return", "copy", ".", "copy", "(", "exdoc_obj", ")" ]
Trace my_module exceptions.
[ "Trace", "my_module", "exceptions", "." ]
201ac243e5781347feb75896a4231429fe6da4b1
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/docs/support/trace_my_module_1.py#L14-L29
train
a1ezzz/wasp-general
wasp_general/network/web/headers.py
WHTTPHeaders.header_name_check
def header_name_check(header_name): """ Check header name for validity. Return True if name is valid :param header_name: name to check :return: bool """ header_match = WHTTPHeaders.header_name_re.match(header_name.encode('us-ascii')) return len(header_name) > 0 and header_match is not None
python
def header_name_check(header_name): """ Check header name for validity. Return True if name is valid :param header_name: name to check :return: bool """ header_match = WHTTPHeaders.header_name_re.match(header_name.encode('us-ascii')) return len(header_name) > 0 and header_match is not None
[ "def", "header_name_check", "(", "header_name", ")", ":", "header_match", "=", "WHTTPHeaders", ".", "header_name_re", ".", "match", "(", "header_name", ".", "encode", "(", "'us-ascii'", ")", ")", "return", "len", "(", "header_name", ")", ">", "0", "and", "header_match", "is", "not", "None" ]
Check header name for validity. Return True if name is valid :param header_name: name to check :return: bool
[ "Check", "header", "name", "for", "validity", ".", "Return", "True", "if", "name", "is", "valid" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/headers.py#L53-L60
train
a1ezzz/wasp-general
wasp_general/network/web/headers.py
WHTTPHeaders.remove_headers
def remove_headers(self, header_name): """ Remove header by its name :param header_name: name of header to remove :return: None """ if self.__ro_flag: raise RuntimeError('ro') header_name = self.normalize_name(header_name) if header_name in self.__headers.keys(): self.__headers.pop(header_name)
python
def remove_headers(self, header_name): """ Remove header by its name :param header_name: name of header to remove :return: None """ if self.__ro_flag: raise RuntimeError('ro') header_name = self.normalize_name(header_name) if header_name in self.__headers.keys(): self.__headers.pop(header_name)
[ "def", "remove_headers", "(", "self", ",", "header_name", ")", ":", "if", "self", ".", "__ro_flag", ":", "raise", "RuntimeError", "(", "'ro'", ")", "header_name", "=", "self", ".", "normalize_name", "(", "header_name", ")", "if", "header_name", "in", "self", ".", "__headers", ".", "keys", "(", ")", ":", "self", ".", "__headers", ".", "pop", "(", "header_name", ")" ]
Remove header by its name :param header_name: name of header to remove :return: None
[ "Remove", "header", "by", "its", "name" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/headers.py#L83-L93
train
a1ezzz/wasp-general
wasp_general/network/web/headers.py
WHTTPHeaders.add_headers
def add_headers(self, header_name, value, *values): """ Add new header :param header_name: name of the header to add :param value: header value :param values: additional header values (in a result request/response must be concatenated by the coma \ or by the separate header string) :return: None """ if self.__ro_flag: raise RuntimeError('ro') header_name = self.normalize_name(header_name) if header_name not in self.__headers.keys(): self.__headers[header_name] = [value] else: self.__headers[header_name].append(value) for single_value in values: self.__headers[header_name].append(single_value)
python
def add_headers(self, header_name, value, *values): """ Add new header :param header_name: name of the header to add :param value: header value :param values: additional header values (in a result request/response must be concatenated by the coma \ or by the separate header string) :return: None """ if self.__ro_flag: raise RuntimeError('ro') header_name = self.normalize_name(header_name) if header_name not in self.__headers.keys(): self.__headers[header_name] = [value] else: self.__headers[header_name].append(value) for single_value in values: self.__headers[header_name].append(single_value)
[ "def", "add_headers", "(", "self", ",", "header_name", ",", "value", ",", "*", "values", ")", ":", "if", "self", ".", "__ro_flag", ":", "raise", "RuntimeError", "(", "'ro'", ")", "header_name", "=", "self", ".", "normalize_name", "(", "header_name", ")", "if", "header_name", "not", "in", "self", ".", "__headers", ".", "keys", "(", ")", ":", "self", ".", "__headers", "[", "header_name", "]", "=", "[", "value", "]", "else", ":", "self", ".", "__headers", "[", "header_name", "]", ".", "append", "(", "value", ")", "for", "single_value", "in", "values", ":", "self", ".", "__headers", "[", "header_name", "]", ".", "append", "(", "single_value", ")" ]
Add new header :param header_name: name of the header to add :param value: header value :param values: additional header values (in a result request/response must be concatenated by the coma \ or by the separate header string) :return: None
[ "Add", "new", "header" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/headers.py#L98-L116
train
a1ezzz/wasp-general
wasp_general/network/web/headers.py
WHTTPHeaders.get_headers
def get_headers(self, header_name): """ Return header value by its name :param header_name: header name :return: tuple of str """ header_name = self.normalize_name(header_name) if header_name in self.__headers.keys(): return tuple(self.__headers[header_name])
python
def get_headers(self, header_name): """ Return header value by its name :param header_name: header name :return: tuple of str """ header_name = self.normalize_name(header_name) if header_name in self.__headers.keys(): return tuple(self.__headers[header_name])
[ "def", "get_headers", "(", "self", ",", "header_name", ")", ":", "header_name", "=", "self", ".", "normalize_name", "(", "header_name", ")", "if", "header_name", "in", "self", ".", "__headers", ".", "keys", "(", ")", ":", "return", "tuple", "(", "self", ".", "__headers", "[", "header_name", "]", ")" ]
Return header value by its name :param header_name: header name :return: tuple of str
[ "Return", "header", "value", "by", "its", "name" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/headers.py#L137-L145
train
a1ezzz/wasp-general
wasp_general/network/web/headers.py
WHTTPHeaders.switch_name_style
def switch_name_style(self, http_protocol_version): """ Return object copy with header names saved as it is described in the given protocol version see :meth:`.WHTTPHeaders.normalize_name` :param http_protocol_version: target HTTP protocol version :return: WHTTPHeaders """ new_headers = WHTTPHeaders() new_headers.__normalization_mode = http_protocol_version names = self.headers() for name in names: new_headers.add_headers(name, *self.get_headers(name)) for cookie_name in self.__set_cookies.cookies(): new_headers.__set_cookies.add_cookie(self.__set_cookies[cookie_name].copy()) return new_headers
python
def switch_name_style(self, http_protocol_version): """ Return object copy with header names saved as it is described in the given protocol version see :meth:`.WHTTPHeaders.normalize_name` :param http_protocol_version: target HTTP protocol version :return: WHTTPHeaders """ new_headers = WHTTPHeaders() new_headers.__normalization_mode = http_protocol_version names = self.headers() for name in names: new_headers.add_headers(name, *self.get_headers(name)) for cookie_name in self.__set_cookies.cookies(): new_headers.__set_cookies.add_cookie(self.__set_cookies[cookie_name].copy()) return new_headers
[ "def", "switch_name_style", "(", "self", ",", "http_protocol_version", ")", ":", "new_headers", "=", "WHTTPHeaders", "(", ")", "new_headers", ".", "__normalization_mode", "=", "http_protocol_version", "names", "=", "self", ".", "headers", "(", ")", "for", "name", "in", "names", ":", "new_headers", ".", "add_headers", "(", "name", ",", "*", "self", ".", "get_headers", "(", "name", ")", ")", "for", "cookie_name", "in", "self", ".", "__set_cookies", ".", "cookies", "(", ")", ":", "new_headers", ".", "__set_cookies", ".", "add_cookie", "(", "self", ".", "__set_cookies", "[", "cookie_name", "]", ".", "copy", "(", ")", ")", "return", "new_headers" ]
Return object copy with header names saved as it is described in the given protocol version see :meth:`.WHTTPHeaders.normalize_name` :param http_protocol_version: target HTTP protocol version :return: WHTTPHeaders
[ "Return", "object", "copy", "with", "header", "names", "saved", "as", "it", "is", "described", "in", "the", "given", "protocol", "version" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/headers.py#L178-L193
train
a1ezzz/wasp-general
wasp_general/network/web/headers.py
WHTTPHeaders.ro
def ro(self): """ Return read-only copy of this object :return: WHTTPHeaders """ ro_headers = WHTTPHeaders() names = self.headers() for name in names: ro_headers.add_headers(name, *self.get_headers(name)) ro_headers.__cookies = self.__set_cookies.ro() ro_headers.__ro_flag = True return ro_headers
python
def ro(self): """ Return read-only copy of this object :return: WHTTPHeaders """ ro_headers = WHTTPHeaders() names = self.headers() for name in names: ro_headers.add_headers(name, *self.get_headers(name)) ro_headers.__cookies = self.__set_cookies.ro() ro_headers.__ro_flag = True return ro_headers
[ "def", "ro", "(", "self", ")", ":", "ro_headers", "=", "WHTTPHeaders", "(", ")", "names", "=", "self", ".", "headers", "(", ")", "for", "name", "in", "names", ":", "ro_headers", ".", "add_headers", "(", "name", ",", "*", "self", ".", "get_headers", "(", "name", ")", ")", "ro_headers", ".", "__cookies", "=", "self", ".", "__set_cookies", ".", "ro", "(", ")", "ro_headers", ".", "__ro_flag", "=", "True", "return", "ro_headers" ]
Return read-only copy of this object :return: WHTTPHeaders
[ "Return", "read", "-", "only", "copy", "of", "this", "object" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/headers.py#L195-L206
train
a1ezzz/wasp-general
wasp_general/network/web/headers.py
WHTTPHeaders.client_cookie_jar
def client_cookie_jar(self): """ Return internal cookie jar that must be used as HTTP-request cookies see :class:`.WHTTPCookieJar` :return: WHTTPCookieJar """ cookie_jar = WHTTPCookieJar() cookie_header = self.get_headers('Cookie') for cookie_string in (cookie_header if cookie_header is not None else tuple()): for single_cookie in WHTTPCookieJar.import_header_text(cookie_string): cookie_jar.add_cookie(single_cookie) return cookie_jar.ro()
python
def client_cookie_jar(self): """ Return internal cookie jar that must be used as HTTP-request cookies see :class:`.WHTTPCookieJar` :return: WHTTPCookieJar """ cookie_jar = WHTTPCookieJar() cookie_header = self.get_headers('Cookie') for cookie_string in (cookie_header if cookie_header is not None else tuple()): for single_cookie in WHTTPCookieJar.import_header_text(cookie_string): cookie_jar.add_cookie(single_cookie) return cookie_jar.ro()
[ "def", "client_cookie_jar", "(", "self", ")", ":", "cookie_jar", "=", "WHTTPCookieJar", "(", ")", "cookie_header", "=", "self", ".", "get_headers", "(", "'Cookie'", ")", "for", "cookie_string", "in", "(", "cookie_header", "if", "cookie_header", "is", "not", "None", "else", "tuple", "(", ")", ")", ":", "for", "single_cookie", "in", "WHTTPCookieJar", ".", "import_header_text", "(", "cookie_string", ")", ":", "cookie_jar", ".", "add_cookie", "(", "single_cookie", ")", "return", "cookie_jar", ".", "ro", "(", ")" ]
Return internal cookie jar that must be used as HTTP-request cookies see :class:`.WHTTPCookieJar` :return: WHTTPCookieJar
[ "Return", "internal", "cookie", "jar", "that", "must", "be", "used", "as", "HTTP", "-", "request", "cookies" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/headers.py#L230-L243
train
a1ezzz/wasp-general
wasp_general/network/web/headers.py
WHTTPHeaders.import_headers
def import_headers(cls, http_code): """ Create WHTTPHeaders by the given code. If code has 'Set-Cookie' headers, that headers are parsed, data are stored in internal cookie jar. At the end of parsing 'Set-Cookie' headers are removed from the result :param http_code: HTTP code to parse :return: WHTTPHeaders """ headers = WHTTPHeaders() message = email.message_from_file(StringIO(http_code)) for header_name, header_value in message.items(): headers.add_headers(header_name, header_value) cookie_header = headers.get_headers('Set-Cookie') if cookie_header is not None: for cookie_string in cookie_header: for single_cookie in WHTTPCookieJar.import_header_text(cookie_string): headers.set_cookie_jar().add_cookie(single_cookie) headers.remove_headers('Set-Cookie') return headers
python
def import_headers(cls, http_code): """ Create WHTTPHeaders by the given code. If code has 'Set-Cookie' headers, that headers are parsed, data are stored in internal cookie jar. At the end of parsing 'Set-Cookie' headers are removed from the result :param http_code: HTTP code to parse :return: WHTTPHeaders """ headers = WHTTPHeaders() message = email.message_from_file(StringIO(http_code)) for header_name, header_value in message.items(): headers.add_headers(header_name, header_value) cookie_header = headers.get_headers('Set-Cookie') if cookie_header is not None: for cookie_string in cookie_header: for single_cookie in WHTTPCookieJar.import_header_text(cookie_string): headers.set_cookie_jar().add_cookie(single_cookie) headers.remove_headers('Set-Cookie') return headers
[ "def", "import_headers", "(", "cls", ",", "http_code", ")", ":", "headers", "=", "WHTTPHeaders", "(", ")", "message", "=", "email", ".", "message_from_file", "(", "StringIO", "(", "http_code", ")", ")", "for", "header_name", ",", "header_value", "in", "message", ".", "items", "(", ")", ":", "headers", ".", "add_headers", "(", "header_name", ",", "header_value", ")", "cookie_header", "=", "headers", ".", "get_headers", "(", "'Set-Cookie'", ")", "if", "cookie_header", "is", "not", "None", ":", "for", "cookie_string", "in", "cookie_header", ":", "for", "single_cookie", "in", "WHTTPCookieJar", ".", "import_header_text", "(", "cookie_string", ")", ":", "headers", ".", "set_cookie_jar", "(", ")", ".", "add_cookie", "(", "single_cookie", ")", "headers", ".", "remove_headers", "(", "'Set-Cookie'", ")", "return", "headers" ]
Create WHTTPHeaders by the given code. If code has 'Set-Cookie' headers, that headers are parsed, data are stored in internal cookie jar. At the end of parsing 'Set-Cookie' headers are removed from the result :param http_code: HTTP code to parse :return: WHTTPHeaders
[ "Create", "WHTTPHeaders", "by", "the", "given", "code", ".", "If", "code", "has", "Set", "-", "Cookie", "headers", "that", "headers", "are", "parsed", "data", "are", "stored", "in", "internal", "cookie", "jar", ".", "At", "the", "end", "of", "parsing", "Set", "-", "Cookie", "headers", "are", "removed", "from", "the", "result" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/headers.py#L247-L267
train
pmacosta/pexdoc
docs/support/trace_my_module_2.py
trace_module
def trace_module(no_print=True): """Trace my_module_original exceptions.""" with pexdoc.ExDocCxt() as exdoc_obj: try: docs.support.my_module.func("John") obj = docs.support.my_module.MyClass() obj.value = 5 obj.value except: raise RuntimeError("Tracing did not complete successfully") if not no_print: module_prefix = "docs.support.my_module." callable_names = ["func", "MyClass.value"] for callable_name in callable_names: callable_name = module_prefix + callable_name print("\nCallable: {0}".format(callable_name)) print(exdoc_obj.get_sphinx_doc(callable_name, width=70)) print("\n") return copy.copy(exdoc_obj)
python
def trace_module(no_print=True): """Trace my_module_original exceptions.""" with pexdoc.ExDocCxt() as exdoc_obj: try: docs.support.my_module.func("John") obj = docs.support.my_module.MyClass() obj.value = 5 obj.value except: raise RuntimeError("Tracing did not complete successfully") if not no_print: module_prefix = "docs.support.my_module." callable_names = ["func", "MyClass.value"] for callable_name in callable_names: callable_name = module_prefix + callable_name print("\nCallable: {0}".format(callable_name)) print(exdoc_obj.get_sphinx_doc(callable_name, width=70)) print("\n") return copy.copy(exdoc_obj)
[ "def", "trace_module", "(", "no_print", "=", "True", ")", ":", "with", "pexdoc", ".", "ExDocCxt", "(", ")", "as", "exdoc_obj", ":", "try", ":", "docs", ".", "support", ".", "my_module", ".", "func", "(", "\"John\"", ")", "obj", "=", "docs", ".", "support", ".", "my_module", ".", "MyClass", "(", ")", "obj", ".", "value", "=", "5", "obj", ".", "value", "except", ":", "raise", "RuntimeError", "(", "\"Tracing did not complete successfully\"", ")", "if", "not", "no_print", ":", "module_prefix", "=", "\"docs.support.my_module.\"", "callable_names", "=", "[", "\"func\"", ",", "\"MyClass.value\"", "]", "for", "callable_name", "in", "callable_names", ":", "callable_name", "=", "module_prefix", "+", "callable_name", "print", "(", "\"\\nCallable: {0}\"", ".", "format", "(", "callable_name", ")", ")", "print", "(", "exdoc_obj", ".", "get_sphinx_doc", "(", "callable_name", ",", "width", "=", "70", ")", ")", "print", "(", "\"\\n\"", ")", "return", "copy", ".", "copy", "(", "exdoc_obj", ")" ]
Trace my_module_original exceptions.
[ "Trace", "my_module_original", "exceptions", "." ]
201ac243e5781347feb75896a4231429fe6da4b1
https://github.com/pmacosta/pexdoc/blob/201ac243e5781347feb75896a4231429fe6da4b1/docs/support/trace_my_module_2.py#L14-L32
train
a1ezzz/wasp-general
wasp_general/network/web/request.py
WWebRequest.ro
def ro(self): """ Create read-only copy :return: WWebRequest """ request = WWebRequest( self.session(), self.method(), self.path(), headers=self.headers().ro(), request_data=self.request_data() ) request.__ro_flag = True return request
python
def ro(self): """ Create read-only copy :return: WWebRequest """ request = WWebRequest( self.session(), self.method(), self.path(), headers=self.headers().ro(), request_data=self.request_data() ) request.__ro_flag = True return request
[ "def", "ro", "(", "self", ")", ":", "request", "=", "WWebRequest", "(", "self", ".", "session", "(", ")", ",", "self", ".", "method", "(", ")", ",", "self", ".", "path", "(", ")", ",", "headers", "=", "self", ".", "headers", "(", ")", ".", "ro", "(", ")", ",", "request_data", "=", "self", ".", "request_data", "(", ")", ")", "request", ".", "__ro_flag", "=", "True", "return", "request" ]
Create read-only copy :return: WWebRequest
[ "Create", "read", "-", "only", "copy" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/request.py#L154-L164
train
tBaxter/tango-contact-manager
build/lib/contact_manager/views.py
simple_contact
def simple_contact(request, username=""): """ Defines simple contact form that can be used to contact a site member passed by username in the URL or to all superusers or to a list defined in settings.DEFAULT_CONTACTS. """ site = Site.objects.get_current() form = ContactForm(request.POST or None) UserModel = get_user_model() recipients = [] site_form = False logger.debug('Recipients should be empty: %s' % recipients) # if we know, fill in the user name and email if request.user.is_authenticated: # first, resolve username for tango and non-tango sites try: name = request.user.display_name except AttributeError: name = request.user.username form.fields['sender_name'].widget.attrs['readonly'] = 'true' form.fields['sender_name'].initial = name form.fields['sender_email'].widget.attrs['readonly'] = 'true' form.fields['sender_email'].initial = request.user.email if username: member = get_object_or_404(UserModel, username=username) recipients = [member.email, ] logger.debug('Recipients should be a single user: %s' % recipients) else: # site contact form. # Use first of settings.DEFAULT_CONTACTS or all superusers site_form = True member = None recipients = getattr(settings, "DEFAULT_CONTACTS", None) logger.debug('Recipients should be match DEFAULT_CONTACTS: %s' % recipients) if not recipients: recipients = UserModel.objects.filter(is_superuser=True).values_list('email', flat=True) warnings.warn( "settings.DEFAULT_CONTACTS does not exist. You may want to create it.", RuntimeWarning ) logger.debug('Recipients should be superusers: %s' % recipients) if form.is_valid(): if site_form: subject = "A {} contact form submission from {}".format( site.name, form.cleaned_data['sender_name'] ) else: subject = "A message from {} on {}".format(form.cleaned_data['sender_name'], site.name) body = form.cleaned_data['body'] sender_email = form.cleaned_data['sender_email'] if 'send_a_copy' in request.POST: recipients.append(sender_email) logger.debug('Recipients should be match prior + sender email: %s' % recipients) mail = EmailMessage( subject=subject, body=body, from_email=sender_email, to=recipients ) mail.send() return HttpResponseRedirect(success_url) return render(request, 'contact/simple_form.html', { 'form': form, 'site': site, 'member': member })
python
def simple_contact(request, username=""): """ Defines simple contact form that can be used to contact a site member passed by username in the URL or to all superusers or to a list defined in settings.DEFAULT_CONTACTS. """ site = Site.objects.get_current() form = ContactForm(request.POST or None) UserModel = get_user_model() recipients = [] site_form = False logger.debug('Recipients should be empty: %s' % recipients) # if we know, fill in the user name and email if request.user.is_authenticated: # first, resolve username for tango and non-tango sites try: name = request.user.display_name except AttributeError: name = request.user.username form.fields['sender_name'].widget.attrs['readonly'] = 'true' form.fields['sender_name'].initial = name form.fields['sender_email'].widget.attrs['readonly'] = 'true' form.fields['sender_email'].initial = request.user.email if username: member = get_object_or_404(UserModel, username=username) recipients = [member.email, ] logger.debug('Recipients should be a single user: %s' % recipients) else: # site contact form. # Use first of settings.DEFAULT_CONTACTS or all superusers site_form = True member = None recipients = getattr(settings, "DEFAULT_CONTACTS", None) logger.debug('Recipients should be match DEFAULT_CONTACTS: %s' % recipients) if not recipients: recipients = UserModel.objects.filter(is_superuser=True).values_list('email', flat=True) warnings.warn( "settings.DEFAULT_CONTACTS does not exist. You may want to create it.", RuntimeWarning ) logger.debug('Recipients should be superusers: %s' % recipients) if form.is_valid(): if site_form: subject = "A {} contact form submission from {}".format( site.name, form.cleaned_data['sender_name'] ) else: subject = "A message from {} on {}".format(form.cleaned_data['sender_name'], site.name) body = form.cleaned_data['body'] sender_email = form.cleaned_data['sender_email'] if 'send_a_copy' in request.POST: recipients.append(sender_email) logger.debug('Recipients should be match prior + sender email: %s' % recipients) mail = EmailMessage( subject=subject, body=body, from_email=sender_email, to=recipients ) mail.send() return HttpResponseRedirect(success_url) return render(request, 'contact/simple_form.html', { 'form': form, 'site': site, 'member': member })
[ "def", "simple_contact", "(", "request", ",", "username", "=", "\"\"", ")", ":", "site", "=", "Site", ".", "objects", ".", "get_current", "(", ")", "form", "=", "ContactForm", "(", "request", ".", "POST", "or", "None", ")", "UserModel", "=", "get_user_model", "(", ")", "recipients", "=", "[", "]", "site_form", "=", "False", "logger", ".", "debug", "(", "'Recipients should be empty: %s'", "%", "recipients", ")", "# if we know, fill in the user name and email\r", "if", "request", ".", "user", ".", "is_authenticated", ":", "# first, resolve username for tango and non-tango sites\r", "try", ":", "name", "=", "request", ".", "user", ".", "display_name", "except", "AttributeError", ":", "name", "=", "request", ".", "user", ".", "username", "form", ".", "fields", "[", "'sender_name'", "]", ".", "widget", ".", "attrs", "[", "'readonly'", "]", "=", "'true'", "form", ".", "fields", "[", "'sender_name'", "]", ".", "initial", "=", "name", "form", ".", "fields", "[", "'sender_email'", "]", ".", "widget", ".", "attrs", "[", "'readonly'", "]", "=", "'true'", "form", ".", "fields", "[", "'sender_email'", "]", ".", "initial", "=", "request", ".", "user", ".", "email", "if", "username", ":", "member", "=", "get_object_or_404", "(", "UserModel", ",", "username", "=", "username", ")", "recipients", "=", "[", "member", ".", "email", ",", "]", "logger", ".", "debug", "(", "'Recipients should be a single user: %s'", "%", "recipients", ")", "else", ":", "# site contact form.\r", "# Use first of settings.DEFAULT_CONTACTS or all superusers\r", "site_form", "=", "True", "member", "=", "None", "recipients", "=", "getattr", "(", "settings", ",", "\"DEFAULT_CONTACTS\"", ",", "None", ")", "logger", ".", "debug", "(", "'Recipients should be match DEFAULT_CONTACTS: %s'", "%", "recipients", ")", "if", "not", "recipients", ":", "recipients", "=", "UserModel", ".", "objects", ".", "filter", "(", "is_superuser", "=", "True", ")", ".", "values_list", "(", "'email'", ",", "flat", "=", "True", ")", "warnings", ".", "warn", "(", "\"settings.DEFAULT_CONTACTS does not exist. You may want to create it.\"", ",", "RuntimeWarning", ")", "logger", ".", "debug", "(", "'Recipients should be superusers: %s'", "%", "recipients", ")", "if", "form", ".", "is_valid", "(", ")", ":", "if", "site_form", ":", "subject", "=", "\"A {} contact form submission from {}\"", ".", "format", "(", "site", ".", "name", ",", "form", ".", "cleaned_data", "[", "'sender_name'", "]", ")", "else", ":", "subject", "=", "\"A message from {} on {}\"", ".", "format", "(", "form", ".", "cleaned_data", "[", "'sender_name'", "]", ",", "site", ".", "name", ")", "body", "=", "form", ".", "cleaned_data", "[", "'body'", "]", "sender_email", "=", "form", ".", "cleaned_data", "[", "'sender_email'", "]", "if", "'send_a_copy'", "in", "request", ".", "POST", ":", "recipients", ".", "append", "(", "sender_email", ")", "logger", ".", "debug", "(", "'Recipients should be match prior + sender email: %s'", "%", "recipients", ")", "mail", "=", "EmailMessage", "(", "subject", "=", "subject", ",", "body", "=", "body", ",", "from_email", "=", "sender_email", ",", "to", "=", "recipients", ")", "mail", ".", "send", "(", ")", "return", "HttpResponseRedirect", "(", "success_url", ")", "return", "render", "(", "request", ",", "'contact/simple_form.html'", ",", "{", "'form'", ":", "form", ",", "'site'", ":", "site", ",", "'member'", ":", "member", "}", ")" ]
Defines simple contact form that can be used to contact a site member passed by username in the URL or to all superusers or to a list defined in settings.DEFAULT_CONTACTS.
[ "Defines", "simple", "contact", "form", "that", "can", "be", "used", "to", "contact", "a", "site", "member", "passed", "by", "username", "in", "the", "URL", "or", "to", "all", "superusers", "or", "to", "a", "list", "defined", "in", "settings", ".", "DEFAULT_CONTACTS", "." ]
7bd5be326a8db8f438cdefff0fbd14849d0474a5
https://github.com/tBaxter/tango-contact-manager/blob/7bd5be326a8db8f438cdefff0fbd14849d0474a5/build/lib/contact_manager/views.py#L61-L135
train
tBaxter/tango-contact-manager
build/lib/contact_manager/views.py
build_contact
def build_contact(request, slug=""): """ Builds appropriate contact form based on options set in the contact_form controller. """ controller = get_object_or_404(ContactFormController, slug=slug) site = Site.objects.get_current() UserModel = get_user_model() user = request.user form = ContactForm(request.POST or None, request.FILES or None, controller=controller) # if we know, fill in the user name and email if user.is_authenticated: # first, resolve username for tango and non-tango sites try: name = user.display_name except AttributeError: name = user.username form.fields['sender_name'].widget.attrs['readonly'] = 'true' form.fields['sender_name'].initial = name form.fields['sender_email'].widget.attrs['readonly'] = 'true' form.fields['sender_email'].initial = user.email if form.is_valid(): if controller.store_in_db: # To do: sanitize submission. new_msg = Contact(**form.cleaned_data) new_msg.controller = controller new_msg.site = site if controller.override_subject: # we're overriding the subject new_msg.subject = controller.override_subject new_msg.save() if controller.send_emails: form_data = form.cleaned_data if controller.override_subject: subject = controller.override_subject elif 'subject' in form_data: subject = form_data['subject'] else: subject = "{} message from {}".format(controller.name, form_data['sender_name']) body = "{} \n\n {}".format(form_data['body'], form_data['sender_name']) if controller.request_contact_info: body += "\nAddress: {} \nCity: {} \nState: {} \nPhone: {}".format( form_data['contact_address'], form_data['contact_city'], form_data['contact_state'], form_data['contact_phone'] ) if controller.email_options == '2': # Create selectable list from recipients try: to = [UserModel.objects.get(username=form.cleaned_data['to']).email] except Exception: to = [form.cleaned_data['to']] if controller.email_options == '1': to = [r.email for r in controller.recipients.all()] for r in controller.other_recipients.all(): to.append(r.email) if 'send_a_copy' in form.cleaned_data: to.append(form.cleaned_data['sender_email']) mail = EmailMessage( subject=subject, body=body, from_email=form.cleaned_data['sender_email'], to=to ) if 'photo' in request.FILES: photo = request.FILES['photo'] mail.attach(photo.name, photo.read(), photo.content_type) mail.send() return render(request, 'success_url', {'controller': controller}) return render(request, 'contact/form.html', { 'form': form, 'site': site, 'controller': controller })
python
def build_contact(request, slug=""): """ Builds appropriate contact form based on options set in the contact_form controller. """ controller = get_object_or_404(ContactFormController, slug=slug) site = Site.objects.get_current() UserModel = get_user_model() user = request.user form = ContactForm(request.POST or None, request.FILES or None, controller=controller) # if we know, fill in the user name and email if user.is_authenticated: # first, resolve username for tango and non-tango sites try: name = user.display_name except AttributeError: name = user.username form.fields['sender_name'].widget.attrs['readonly'] = 'true' form.fields['sender_name'].initial = name form.fields['sender_email'].widget.attrs['readonly'] = 'true' form.fields['sender_email'].initial = user.email if form.is_valid(): if controller.store_in_db: # To do: sanitize submission. new_msg = Contact(**form.cleaned_data) new_msg.controller = controller new_msg.site = site if controller.override_subject: # we're overriding the subject new_msg.subject = controller.override_subject new_msg.save() if controller.send_emails: form_data = form.cleaned_data if controller.override_subject: subject = controller.override_subject elif 'subject' in form_data: subject = form_data['subject'] else: subject = "{} message from {}".format(controller.name, form_data['sender_name']) body = "{} \n\n {}".format(form_data['body'], form_data['sender_name']) if controller.request_contact_info: body += "\nAddress: {} \nCity: {} \nState: {} \nPhone: {}".format( form_data['contact_address'], form_data['contact_city'], form_data['contact_state'], form_data['contact_phone'] ) if controller.email_options == '2': # Create selectable list from recipients try: to = [UserModel.objects.get(username=form.cleaned_data['to']).email] except Exception: to = [form.cleaned_data['to']] if controller.email_options == '1': to = [r.email for r in controller.recipients.all()] for r in controller.other_recipients.all(): to.append(r.email) if 'send_a_copy' in form.cleaned_data: to.append(form.cleaned_data['sender_email']) mail = EmailMessage( subject=subject, body=body, from_email=form.cleaned_data['sender_email'], to=to ) if 'photo' in request.FILES: photo = request.FILES['photo'] mail.attach(photo.name, photo.read(), photo.content_type) mail.send() return render(request, 'success_url', {'controller': controller}) return render(request, 'contact/form.html', { 'form': form, 'site': site, 'controller': controller })
[ "def", "build_contact", "(", "request", ",", "slug", "=", "\"\"", ")", ":", "controller", "=", "get_object_or_404", "(", "ContactFormController", ",", "slug", "=", "slug", ")", "site", "=", "Site", ".", "objects", ".", "get_current", "(", ")", "UserModel", "=", "get_user_model", "(", ")", "user", "=", "request", ".", "user", "form", "=", "ContactForm", "(", "request", ".", "POST", "or", "None", ",", "request", ".", "FILES", "or", "None", ",", "controller", "=", "controller", ")", "# if we know, fill in the user name and email\r", "if", "user", ".", "is_authenticated", ":", "# first, resolve username for tango and non-tango sites\r", "try", ":", "name", "=", "user", ".", "display_name", "except", "AttributeError", ":", "name", "=", "user", ".", "username", "form", ".", "fields", "[", "'sender_name'", "]", ".", "widget", ".", "attrs", "[", "'readonly'", "]", "=", "'true'", "form", ".", "fields", "[", "'sender_name'", "]", ".", "initial", "=", "name", "form", ".", "fields", "[", "'sender_email'", "]", ".", "widget", ".", "attrs", "[", "'readonly'", "]", "=", "'true'", "form", ".", "fields", "[", "'sender_email'", "]", ".", "initial", "=", "user", ".", "email", "if", "form", ".", "is_valid", "(", ")", ":", "if", "controller", ".", "store_in_db", ":", "# To do: sanitize submission.\r", "new_msg", "=", "Contact", "(", "*", "*", "form", ".", "cleaned_data", ")", "new_msg", ".", "controller", "=", "controller", "new_msg", ".", "site", "=", "site", "if", "controller", ".", "override_subject", ":", "# we're overriding the subject\r", "new_msg", ".", "subject", "=", "controller", ".", "override_subject", "new_msg", ".", "save", "(", ")", "if", "controller", ".", "send_emails", ":", "form_data", "=", "form", ".", "cleaned_data", "if", "controller", ".", "override_subject", ":", "subject", "=", "controller", ".", "override_subject", "elif", "'subject'", "in", "form_data", ":", "subject", "=", "form_data", "[", "'subject'", "]", "else", ":", "subject", "=", "\"{} message from {}\"", ".", "format", "(", "controller", ".", "name", ",", "form_data", "[", "'sender_name'", "]", ")", "body", "=", "\"{} \\n\\n {}\"", ".", "format", "(", "form_data", "[", "'body'", "]", ",", "form_data", "[", "'sender_name'", "]", ")", "if", "controller", ".", "request_contact_info", ":", "body", "+=", "\"\\nAddress: {} \\nCity: {} \\nState: {} \\nPhone: {}\"", ".", "format", "(", "form_data", "[", "'contact_address'", "]", ",", "form_data", "[", "'contact_city'", "]", ",", "form_data", "[", "'contact_state'", "]", ",", "form_data", "[", "'contact_phone'", "]", ")", "if", "controller", ".", "email_options", "==", "'2'", ":", "# Create selectable list from recipients\r", "try", ":", "to", "=", "[", "UserModel", ".", "objects", ".", "get", "(", "username", "=", "form", ".", "cleaned_data", "[", "'to'", "]", ")", ".", "email", "]", "except", "Exception", ":", "to", "=", "[", "form", ".", "cleaned_data", "[", "'to'", "]", "]", "if", "controller", ".", "email_options", "==", "'1'", ":", "to", "=", "[", "r", ".", "email", "for", "r", "in", "controller", ".", "recipients", ".", "all", "(", ")", "]", "for", "r", "in", "controller", ".", "other_recipients", ".", "all", "(", ")", ":", "to", ".", "append", "(", "r", ".", "email", ")", "if", "'send_a_copy'", "in", "form", ".", "cleaned_data", ":", "to", ".", "append", "(", "form", ".", "cleaned_data", "[", "'sender_email'", "]", ")", "mail", "=", "EmailMessage", "(", "subject", "=", "subject", ",", "body", "=", "body", ",", "from_email", "=", "form", ".", "cleaned_data", "[", "'sender_email'", "]", ",", "to", "=", "to", ")", "if", "'photo'", "in", "request", ".", "FILES", ":", "photo", "=", "request", ".", "FILES", "[", "'photo'", "]", "mail", ".", "attach", "(", "photo", ".", "name", ",", "photo", ".", "read", "(", ")", ",", "photo", ".", "content_type", ")", "mail", ".", "send", "(", ")", "return", "render", "(", "request", ",", "'success_url'", ",", "{", "'controller'", ":", "controller", "}", ")", "return", "render", "(", "request", ",", "'contact/form.html'", ",", "{", "'form'", ":", "form", ",", "'site'", ":", "site", ",", "'controller'", ":", "controller", "}", ")" ]
Builds appropriate contact form based on options set in the contact_form controller.
[ "Builds", "appropriate", "contact", "form", "based", "on", "options", "set", "in", "the", "contact_form", "controller", "." ]
7bd5be326a8db8f438cdefff0fbd14849d0474a5
https://github.com/tBaxter/tango-contact-manager/blob/7bd5be326a8db8f438cdefff0fbd14849d0474a5/build/lib/contact_manager/views.py#L138-L219
train
Loudr/pale
pale/adapters/webapp2.py
pale_webapp2_request_handler_generator
def pale_webapp2_request_handler_generator(pale_endpoint): """Generate a webapp2.RequestHandler class for the pale endpoint. webapp2 handles requests with subclasses of the RequestHandler class, instead of using functions like Flask, so we need to generate a new class for each pale endpoint. """ def pale_handler(self, *args, **kwargs): if self.request.method == "OPTIONS": origin = self.request.headers.get("Origin", None) self.response.headers['Access-Control-Allow-Origin'] = origin self.response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept' self.response.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE' self.response.headers['Access-Control-Allow-Credentials'] = 'true' return self.response try: return pale_endpoint._execute(self.request) finally: pale_endpoint._finally() cls = type(pale_endpoint._route_name, (webapp2.RequestHandler,), dict(pale_handler=pale_handler)) return cls
python
def pale_webapp2_request_handler_generator(pale_endpoint): """Generate a webapp2.RequestHandler class for the pale endpoint. webapp2 handles requests with subclasses of the RequestHandler class, instead of using functions like Flask, so we need to generate a new class for each pale endpoint. """ def pale_handler(self, *args, **kwargs): if self.request.method == "OPTIONS": origin = self.request.headers.get("Origin", None) self.response.headers['Access-Control-Allow-Origin'] = origin self.response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept' self.response.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE' self.response.headers['Access-Control-Allow-Credentials'] = 'true' return self.response try: return pale_endpoint._execute(self.request) finally: pale_endpoint._finally() cls = type(pale_endpoint._route_name, (webapp2.RequestHandler,), dict(pale_handler=pale_handler)) return cls
[ "def", "pale_webapp2_request_handler_generator", "(", "pale_endpoint", ")", ":", "def", "pale_handler", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "request", ".", "method", "==", "\"OPTIONS\"", ":", "origin", "=", "self", ".", "request", ".", "headers", ".", "get", "(", "\"Origin\"", ",", "None", ")", "self", ".", "response", ".", "headers", "[", "'Access-Control-Allow-Origin'", "]", "=", "origin", "self", ".", "response", ".", "headers", "[", "'Access-Control-Allow-Headers'", "]", "=", "'Origin, X-Requested-With, Content-Type, Accept'", "self", ".", "response", ".", "headers", "[", "'Access-Control-Allow-Methods'", "]", "=", "'POST, GET, PUT, DELETE'", "self", ".", "response", ".", "headers", "[", "'Access-Control-Allow-Credentials'", "]", "=", "'true'", "return", "self", ".", "response", "try", ":", "return", "pale_endpoint", ".", "_execute", "(", "self", ".", "request", ")", "finally", ":", "pale_endpoint", ".", "_finally", "(", ")", "cls", "=", "type", "(", "pale_endpoint", ".", "_route_name", ",", "(", "webapp2", ".", "RequestHandler", ",", ")", ",", "dict", "(", "pale_handler", "=", "pale_handler", ")", ")", "return", "cls" ]
Generate a webapp2.RequestHandler class for the pale endpoint. webapp2 handles requests with subclasses of the RequestHandler class, instead of using functions like Flask, so we need to generate a new class for each pale endpoint.
[ "Generate", "a", "webapp2", ".", "RequestHandler", "class", "for", "the", "pale", "endpoint", "." ]
dc002ee6032c856551143af222ff8f71ed9853fe
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/adapters/webapp2.py#L20-L44
train
Loudr/pale
pale/adapters/webapp2.py
bind_pale_to_webapp2
def bind_pale_to_webapp2(pale_app_module, webapp_wsgiapplication, route_prefix=None): """Binds a Pale API implementation to a webapp2 WSGIApplication""" if not isinstance(webapp_wsgiapplication, webapp2.WSGIApplication): raise TypeError("pale.adapters.webapp2.bind_pale_to_webapp2 expected " "the passed in webapp_wsgiapplication to be an instance of " "WSGIApplication, but it was an instance of %s instead." % (type(webapp_wsgiapplication), )) if not pale.is_pale_module(pale_app_module): raise TypeError("pale.adapters.webapp2.bind_pale_to_webapp2 expected " "the passed in pale_app_module to be a Python module with a " "`_module_type` value equal to `pale.ImplementationModule`, " "but it found an instance of %s instead." % (type(pale_app_module), )) endpoints = pale.extract_endpoints(pale_app_module) for endpoint in endpoints: endpoint._set_response_class(RESPONSE_CLASS) method = endpoint._http_method name = endpoint._route_name req_handler = pale_webapp2_request_handler_generator(endpoint) route_uri = endpoint._uri if route_prefix is not None: route_uri = "%s%s" % (route_prefix, route_uri) route = webapp2.Route( route_uri, handler=req_handler, name=name, handler_method='pale_handler', methods=[method, "OPTIONS"]) webapp_wsgiapplication.router.add(route)
python
def bind_pale_to_webapp2(pale_app_module, webapp_wsgiapplication, route_prefix=None): """Binds a Pale API implementation to a webapp2 WSGIApplication""" if not isinstance(webapp_wsgiapplication, webapp2.WSGIApplication): raise TypeError("pale.adapters.webapp2.bind_pale_to_webapp2 expected " "the passed in webapp_wsgiapplication to be an instance of " "WSGIApplication, but it was an instance of %s instead." % (type(webapp_wsgiapplication), )) if not pale.is_pale_module(pale_app_module): raise TypeError("pale.adapters.webapp2.bind_pale_to_webapp2 expected " "the passed in pale_app_module to be a Python module with a " "`_module_type` value equal to `pale.ImplementationModule`, " "but it found an instance of %s instead." % (type(pale_app_module), )) endpoints = pale.extract_endpoints(pale_app_module) for endpoint in endpoints: endpoint._set_response_class(RESPONSE_CLASS) method = endpoint._http_method name = endpoint._route_name req_handler = pale_webapp2_request_handler_generator(endpoint) route_uri = endpoint._uri if route_prefix is not None: route_uri = "%s%s" % (route_prefix, route_uri) route = webapp2.Route( route_uri, handler=req_handler, name=name, handler_method='pale_handler', methods=[method, "OPTIONS"]) webapp_wsgiapplication.router.add(route)
[ "def", "bind_pale_to_webapp2", "(", "pale_app_module", ",", "webapp_wsgiapplication", ",", "route_prefix", "=", "None", ")", ":", "if", "not", "isinstance", "(", "webapp_wsgiapplication", ",", "webapp2", ".", "WSGIApplication", ")", ":", "raise", "TypeError", "(", "\"pale.adapters.webapp2.bind_pale_to_webapp2 expected \"", "\"the passed in webapp_wsgiapplication to be an instance of \"", "\"WSGIApplication, but it was an instance of %s instead.\"", "%", "(", "type", "(", "webapp_wsgiapplication", ")", ",", ")", ")", "if", "not", "pale", ".", "is_pale_module", "(", "pale_app_module", ")", ":", "raise", "TypeError", "(", "\"pale.adapters.webapp2.bind_pale_to_webapp2 expected \"", "\"the passed in pale_app_module to be a Python module with a \"", "\"`_module_type` value equal to `pale.ImplementationModule`, \"", "\"but it found an instance of %s instead.\"", "%", "(", "type", "(", "pale_app_module", ")", ",", ")", ")", "endpoints", "=", "pale", ".", "extract_endpoints", "(", "pale_app_module", ")", "for", "endpoint", "in", "endpoints", ":", "endpoint", ".", "_set_response_class", "(", "RESPONSE_CLASS", ")", "method", "=", "endpoint", ".", "_http_method", "name", "=", "endpoint", ".", "_route_name", "req_handler", "=", "pale_webapp2_request_handler_generator", "(", "endpoint", ")", "route_uri", "=", "endpoint", ".", "_uri", "if", "route_prefix", "is", "not", "None", ":", "route_uri", "=", "\"%s%s\"", "%", "(", "route_prefix", ",", "route_uri", ")", "route", "=", "webapp2", ".", "Route", "(", "route_uri", ",", "handler", "=", "req_handler", ",", "name", "=", "name", ",", "handler_method", "=", "'pale_handler'", ",", "methods", "=", "[", "method", ",", "\"OPTIONS\"", "]", ")", "webapp_wsgiapplication", ".", "router", ".", "add", "(", "route", ")" ]
Binds a Pale API implementation to a webapp2 WSGIApplication
[ "Binds", "a", "Pale", "API", "implementation", "to", "a", "webapp2", "WSGIApplication" ]
dc002ee6032c856551143af222ff8f71ed9853fe
https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/adapters/webapp2.py#L47-L84
train
a1ezzz/wasp-general
wasp_general/network/messenger/coders.py
WMessengerFixedModificationLayer.encode
def encode(self, envelope, session, target=None, modification_code=None, **kwargs): """ Methods appends 'modification_code' to the specified envelope. :param envelope: original envelope :param session: original session :param target: flag, that specifies whether code must be appended to the start or to the end :param modification_code: code to append :param kwargs: additional arguments :return: WMessengerTextEnvelope or WMessengerBytesEnvelope (depends on the original envelope) """ self.__args_check(envelope, target, modification_code) if isinstance(envelope, WMessengerTextEnvelope): target_envelope_cls = WMessengerTextEnvelope else: # isinstance(envelope, WMessengerBytesEnvelope) target_envelope_cls = WMessengerBytesEnvelope if target == WMessengerFixedModificationLayer.Target.head: return target_envelope_cls(modification_code + envelope.message(), meta=envelope) else: # target == WMessengerFixedModificationLayer.Target.tail return target_envelope_cls(envelope.message() + modification_code, meta=envelope)
python
def encode(self, envelope, session, target=None, modification_code=None, **kwargs): """ Methods appends 'modification_code' to the specified envelope. :param envelope: original envelope :param session: original session :param target: flag, that specifies whether code must be appended to the start or to the end :param modification_code: code to append :param kwargs: additional arguments :return: WMessengerTextEnvelope or WMessengerBytesEnvelope (depends on the original envelope) """ self.__args_check(envelope, target, modification_code) if isinstance(envelope, WMessengerTextEnvelope): target_envelope_cls = WMessengerTextEnvelope else: # isinstance(envelope, WMessengerBytesEnvelope) target_envelope_cls = WMessengerBytesEnvelope if target == WMessengerFixedModificationLayer.Target.head: return target_envelope_cls(modification_code + envelope.message(), meta=envelope) else: # target == WMessengerFixedModificationLayer.Target.tail return target_envelope_cls(envelope.message() + modification_code, meta=envelope)
[ "def", "encode", "(", "self", ",", "envelope", ",", "session", ",", "target", "=", "None", ",", "modification_code", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__args_check", "(", "envelope", ",", "target", ",", "modification_code", ")", "if", "isinstance", "(", "envelope", ",", "WMessengerTextEnvelope", ")", ":", "target_envelope_cls", "=", "WMessengerTextEnvelope", "else", ":", "# isinstance(envelope, WMessengerBytesEnvelope)", "target_envelope_cls", "=", "WMessengerBytesEnvelope", "if", "target", "==", "WMessengerFixedModificationLayer", ".", "Target", ".", "head", ":", "return", "target_envelope_cls", "(", "modification_code", "+", "envelope", ".", "message", "(", ")", ",", "meta", "=", "envelope", ")", "else", ":", "# target == WMessengerFixedModificationLayer.Target.tail", "return", "target_envelope_cls", "(", "envelope", ".", "message", "(", ")", "+", "modification_code", ",", "meta", "=", "envelope", ")" ]
Methods appends 'modification_code' to the specified envelope. :param envelope: original envelope :param session: original session :param target: flag, that specifies whether code must be appended to the start or to the end :param modification_code: code to append :param kwargs: additional arguments :return: WMessengerTextEnvelope or WMessengerBytesEnvelope (depends on the original envelope)
[ "Methods", "appends", "modification_code", "to", "the", "specified", "envelope", "." ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/messenger/coders.py#L103-L124
train
a1ezzz/wasp-general
wasp_general/network/messenger/coders.py
WMessengerFixedModificationLayer.decode
def decode(self, envelope, session, target=None, modification_code=None, **kwargs): """ Methods checks envelope for 'modification_code' existence and removes it. :param envelope: original envelope :param session: original session :param target: flag, that specifies whether code must be searched and removed at the start or at the end :param modification_code: code to search/remove :param kwargs: additional arguments :return: WMessengerTextEnvelope or WMessengerBytesEnvelope (depends on the original envelope) """ self.__args_check(envelope, target, modification_code) message = envelope.message() if len(message) < len(modification_code): raise ValueError('Invalid message length') if isinstance(envelope, WMessengerTextEnvelope): target_envelope_cls = WMessengerTextEnvelope else: # isinstance(envelope, WMessengerBytesEnvelope) target_envelope_cls = WMessengerBytesEnvelope if target == WMessengerFixedModificationLayer.Target.head: if message[:len(modification_code)] != modification_code: raise ValueError('Invalid header in message') return target_envelope_cls(message[len(modification_code):], meta=envelope) else: # target == WMessengerFixedModificationLayer.Target.tail if message[-len(modification_code):] != modification_code: raise ValueError('Invalid tail in message') return target_envelope_cls(message[:-len(modification_code)], meta=envelope)
python
def decode(self, envelope, session, target=None, modification_code=None, **kwargs): """ Methods checks envelope for 'modification_code' existence and removes it. :param envelope: original envelope :param session: original session :param target: flag, that specifies whether code must be searched and removed at the start or at the end :param modification_code: code to search/remove :param kwargs: additional arguments :return: WMessengerTextEnvelope or WMessengerBytesEnvelope (depends on the original envelope) """ self.__args_check(envelope, target, modification_code) message = envelope.message() if len(message) < len(modification_code): raise ValueError('Invalid message length') if isinstance(envelope, WMessengerTextEnvelope): target_envelope_cls = WMessengerTextEnvelope else: # isinstance(envelope, WMessengerBytesEnvelope) target_envelope_cls = WMessengerBytesEnvelope if target == WMessengerFixedModificationLayer.Target.head: if message[:len(modification_code)] != modification_code: raise ValueError('Invalid header in message') return target_envelope_cls(message[len(modification_code):], meta=envelope) else: # target == WMessengerFixedModificationLayer.Target.tail if message[-len(modification_code):] != modification_code: raise ValueError('Invalid tail in message') return target_envelope_cls(message[:-len(modification_code)], meta=envelope)
[ "def", "decode", "(", "self", ",", "envelope", ",", "session", ",", "target", "=", "None", ",", "modification_code", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__args_check", "(", "envelope", ",", "target", ",", "modification_code", ")", "message", "=", "envelope", ".", "message", "(", ")", "if", "len", "(", "message", ")", "<", "len", "(", "modification_code", ")", ":", "raise", "ValueError", "(", "'Invalid message length'", ")", "if", "isinstance", "(", "envelope", ",", "WMessengerTextEnvelope", ")", ":", "target_envelope_cls", "=", "WMessengerTextEnvelope", "else", ":", "# isinstance(envelope, WMessengerBytesEnvelope)", "target_envelope_cls", "=", "WMessengerBytesEnvelope", "if", "target", "==", "WMessengerFixedModificationLayer", ".", "Target", ".", "head", ":", "if", "message", "[", ":", "len", "(", "modification_code", ")", "]", "!=", "modification_code", ":", "raise", "ValueError", "(", "'Invalid header in message'", ")", "return", "target_envelope_cls", "(", "message", "[", "len", "(", "modification_code", ")", ":", "]", ",", "meta", "=", "envelope", ")", "else", ":", "# target == WMessengerFixedModificationLayer.Target.tail", "if", "message", "[", "-", "len", "(", "modification_code", ")", ":", "]", "!=", "modification_code", ":", "raise", "ValueError", "(", "'Invalid tail in message'", ")", "return", "target_envelope_cls", "(", "message", "[", ":", "-", "len", "(", "modification_code", ")", "]", ",", "meta", "=", "envelope", ")" ]
Methods checks envelope for 'modification_code' existence and removes it. :param envelope: original envelope :param session: original session :param target: flag, that specifies whether code must be searched and removed at the start or at the end :param modification_code: code to search/remove :param kwargs: additional arguments :return: WMessengerTextEnvelope or WMessengerBytesEnvelope (depends on the original envelope)
[ "Methods", "checks", "envelope", "for", "modification_code", "existence", "and", "removes", "it", "." ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/messenger/coders.py#L128-L157
train
a1ezzz/wasp-general
wasp_general/task/dependency.py
WTaskDependencyRegistryStorage.started_tasks
def started_tasks(self, task_registry_id=None, task_cls=None): """ Return tasks that was started. Result way be filtered by the given arguments. :param task_registry_id: if it is specified, then try to return single task which id is the same as \ this value. :param task_cls: if it is specified then result will be consists of this subclass only :return: None or WTask or tuple of WTask """ if task_registry_id is not None: task = None for registered_task in self.__started: if registered_task.__registry_tag__ == task_registry_id: task = registered_task if task_cls is not None and task is not None: if isinstance(task, task_cls) is True: return task return None return task result = filter(lambda x: x is not None, self.__started) if task_cls is not None: result = filter(lambda x: isinstance(x, task_cls), result) return tuple(result)
python
def started_tasks(self, task_registry_id=None, task_cls=None): """ Return tasks that was started. Result way be filtered by the given arguments. :param task_registry_id: if it is specified, then try to return single task which id is the same as \ this value. :param task_cls: if it is specified then result will be consists of this subclass only :return: None or WTask or tuple of WTask """ if task_registry_id is not None: task = None for registered_task in self.__started: if registered_task.__registry_tag__ == task_registry_id: task = registered_task if task_cls is not None and task is not None: if isinstance(task, task_cls) is True: return task return None return task result = filter(lambda x: x is not None, self.__started) if task_cls is not None: result = filter(lambda x: isinstance(x, task_cls), result) return tuple(result)
[ "def", "started_tasks", "(", "self", ",", "task_registry_id", "=", "None", ",", "task_cls", "=", "None", ")", ":", "if", "task_registry_id", "is", "not", "None", ":", "task", "=", "None", "for", "registered_task", "in", "self", ".", "__started", ":", "if", "registered_task", ".", "__registry_tag__", "==", "task_registry_id", ":", "task", "=", "registered_task", "if", "task_cls", "is", "not", "None", "and", "task", "is", "not", "None", ":", "if", "isinstance", "(", "task", ",", "task_cls", ")", "is", "True", ":", "return", "task", "return", "None", "return", "task", "result", "=", "filter", "(", "lambda", "x", ":", "x", "is", "not", "None", ",", "self", ".", "__started", ")", "if", "task_cls", "is", "not", "None", ":", "result", "=", "filter", "(", "lambda", "x", ":", "isinstance", "(", "x", ",", "task_cls", ")", ",", "result", ")", "return", "tuple", "(", "result", ")" ]
Return tasks that was started. Result way be filtered by the given arguments. :param task_registry_id: if it is specified, then try to return single task which id is the same as \ this value. :param task_cls: if it is specified then result will be consists of this subclass only :return: None or WTask or tuple of WTask
[ "Return", "tasks", "that", "was", "started", ".", "Result", "way", "be", "filtered", "by", "the", "given", "arguments", "." ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/dependency.py#L153-L178
train
a1ezzz/wasp-general
wasp_general/task/dependency.py
WTaskDependencyRegistryStorage.stop_task
def stop_task(self, task_tag, stop_dependent=True, stop_requirements=False): """ Stop task with the given task tag. If task already stopped, then nothing happens. :param task_tag: task to stop :param stop_dependent: if True, then every task, that require the given task as dependency, will be \ stopped before. :param stop_requirements: if True, then every task, that is required as dependency for the given task, \ will be stopped after. :return: None """ # TODO: "coverage" requires more tests task = self.started_tasks(task_registry_id=task_tag) if task is None: return def stop(task_to_stop): if task_to_stop in self.__started: if isinstance(task_to_stop, WStoppableTask) is True: task_to_stop.stop() self.__started.remove(task_to_stop) def stop_dependency(task_to_stop): deeper_dependencies = [] for dependent_task in self.__started: if task_to_stop.__registry_tag__ in dependent_task.__class__.__dependency__: deeper_dependencies.append(dependent_task) for dependent_task in deeper_dependencies: stop_dependency(dependent_task) stop(task_to_stop) def calculate_requirements(task_to_stop, cross_requirements=False): requirements = set() for dependent_task in self.__started: if dependent_task.__class__.__registry_tag__ in task_to_stop.__class__.__dependency__: requirements.add(dependent_task) if cross_requirements is True: return requirements result = set() for task_a in requirements: requirement_match = False for task_b in requirements: if task_a.__class__.__registry_tag__ in task_b.__class__.__dependency__: requirement_match = True break if requirement_match is False: result.add(task_a) return result def calculate_priorities(task_to_stop, *extra_tasks, current_result=None, requirements_left=None): if current_result is None: current_result = [] tasks_to_stop = [task_to_stop] if len(extra_tasks) > 0: tasks_to_stop.extend(extra_tasks) current_result.append(list(tasks_to_stop)) all_requirements = calculate_requirements(tasks_to_stop[0], cross_requirements=True) nested_requirements = calculate_requirements(tasks_to_stop[0]) for dependent_task in tasks_to_stop[1:]: nested_requirements = nested_requirements.union(calculate_requirements(dependent_task)) all_requirements.update(calculate_requirements(dependent_task, cross_requirements=True)) all_requirements = all_requirements.difference(nested_requirements) if requirements_left is not None: requirements_left = requirements_left.difference(all_requirements) nested_requirements.update(requirements_left) if len(nested_requirements) == 0: return current_result return calculate_priorities( *list(nested_requirements), current_result=current_result, requirements_left=all_requirements ) if stop_dependent is True: stop_dependency(task) if stop_requirements is True: for task_list in calculate_priorities(task): for single_task in task_list: stop(single_task) if stop_dependent is not True: # check if we've already stopped this task stop(task)
python
def stop_task(self, task_tag, stop_dependent=True, stop_requirements=False): """ Stop task with the given task tag. If task already stopped, then nothing happens. :param task_tag: task to stop :param stop_dependent: if True, then every task, that require the given task as dependency, will be \ stopped before. :param stop_requirements: if True, then every task, that is required as dependency for the given task, \ will be stopped after. :return: None """ # TODO: "coverage" requires more tests task = self.started_tasks(task_registry_id=task_tag) if task is None: return def stop(task_to_stop): if task_to_stop in self.__started: if isinstance(task_to_stop, WStoppableTask) is True: task_to_stop.stop() self.__started.remove(task_to_stop) def stop_dependency(task_to_stop): deeper_dependencies = [] for dependent_task in self.__started: if task_to_stop.__registry_tag__ in dependent_task.__class__.__dependency__: deeper_dependencies.append(dependent_task) for dependent_task in deeper_dependencies: stop_dependency(dependent_task) stop(task_to_stop) def calculate_requirements(task_to_stop, cross_requirements=False): requirements = set() for dependent_task in self.__started: if dependent_task.__class__.__registry_tag__ in task_to_stop.__class__.__dependency__: requirements.add(dependent_task) if cross_requirements is True: return requirements result = set() for task_a in requirements: requirement_match = False for task_b in requirements: if task_a.__class__.__registry_tag__ in task_b.__class__.__dependency__: requirement_match = True break if requirement_match is False: result.add(task_a) return result def calculate_priorities(task_to_stop, *extra_tasks, current_result=None, requirements_left=None): if current_result is None: current_result = [] tasks_to_stop = [task_to_stop] if len(extra_tasks) > 0: tasks_to_stop.extend(extra_tasks) current_result.append(list(tasks_to_stop)) all_requirements = calculate_requirements(tasks_to_stop[0], cross_requirements=True) nested_requirements = calculate_requirements(tasks_to_stop[0]) for dependent_task in tasks_to_stop[1:]: nested_requirements = nested_requirements.union(calculate_requirements(dependent_task)) all_requirements.update(calculate_requirements(dependent_task, cross_requirements=True)) all_requirements = all_requirements.difference(nested_requirements) if requirements_left is not None: requirements_left = requirements_left.difference(all_requirements) nested_requirements.update(requirements_left) if len(nested_requirements) == 0: return current_result return calculate_priorities( *list(nested_requirements), current_result=current_result, requirements_left=all_requirements ) if stop_dependent is True: stop_dependency(task) if stop_requirements is True: for task_list in calculate_priorities(task): for single_task in task_list: stop(single_task) if stop_dependent is not True: # check if we've already stopped this task stop(task)
[ "def", "stop_task", "(", "self", ",", "task_tag", ",", "stop_dependent", "=", "True", ",", "stop_requirements", "=", "False", ")", ":", "# TODO: \"coverage\" requires more tests", "task", "=", "self", ".", "started_tasks", "(", "task_registry_id", "=", "task_tag", ")", "if", "task", "is", "None", ":", "return", "def", "stop", "(", "task_to_stop", ")", ":", "if", "task_to_stop", "in", "self", ".", "__started", ":", "if", "isinstance", "(", "task_to_stop", ",", "WStoppableTask", ")", "is", "True", ":", "task_to_stop", ".", "stop", "(", ")", "self", ".", "__started", ".", "remove", "(", "task_to_stop", ")", "def", "stop_dependency", "(", "task_to_stop", ")", ":", "deeper_dependencies", "=", "[", "]", "for", "dependent_task", "in", "self", ".", "__started", ":", "if", "task_to_stop", ".", "__registry_tag__", "in", "dependent_task", ".", "__class__", ".", "__dependency__", ":", "deeper_dependencies", ".", "append", "(", "dependent_task", ")", "for", "dependent_task", "in", "deeper_dependencies", ":", "stop_dependency", "(", "dependent_task", ")", "stop", "(", "task_to_stop", ")", "def", "calculate_requirements", "(", "task_to_stop", ",", "cross_requirements", "=", "False", ")", ":", "requirements", "=", "set", "(", ")", "for", "dependent_task", "in", "self", ".", "__started", ":", "if", "dependent_task", ".", "__class__", ".", "__registry_tag__", "in", "task_to_stop", ".", "__class__", ".", "__dependency__", ":", "requirements", ".", "add", "(", "dependent_task", ")", "if", "cross_requirements", "is", "True", ":", "return", "requirements", "result", "=", "set", "(", ")", "for", "task_a", "in", "requirements", ":", "requirement_match", "=", "False", "for", "task_b", "in", "requirements", ":", "if", "task_a", ".", "__class__", ".", "__registry_tag__", "in", "task_b", ".", "__class__", ".", "__dependency__", ":", "requirement_match", "=", "True", "break", "if", "requirement_match", "is", "False", ":", "result", ".", "add", "(", "task_a", ")", "return", "result", "def", "calculate_priorities", "(", "task_to_stop", ",", "*", "extra_tasks", ",", "current_result", "=", "None", ",", "requirements_left", "=", "None", ")", ":", "if", "current_result", "is", "None", ":", "current_result", "=", "[", "]", "tasks_to_stop", "=", "[", "task_to_stop", "]", "if", "len", "(", "extra_tasks", ")", ">", "0", ":", "tasks_to_stop", ".", "extend", "(", "extra_tasks", ")", "current_result", ".", "append", "(", "list", "(", "tasks_to_stop", ")", ")", "all_requirements", "=", "calculate_requirements", "(", "tasks_to_stop", "[", "0", "]", ",", "cross_requirements", "=", "True", ")", "nested_requirements", "=", "calculate_requirements", "(", "tasks_to_stop", "[", "0", "]", ")", "for", "dependent_task", "in", "tasks_to_stop", "[", "1", ":", "]", ":", "nested_requirements", "=", "nested_requirements", ".", "union", "(", "calculate_requirements", "(", "dependent_task", ")", ")", "all_requirements", ".", "update", "(", "calculate_requirements", "(", "dependent_task", ",", "cross_requirements", "=", "True", ")", ")", "all_requirements", "=", "all_requirements", ".", "difference", "(", "nested_requirements", ")", "if", "requirements_left", "is", "not", "None", ":", "requirements_left", "=", "requirements_left", ".", "difference", "(", "all_requirements", ")", "nested_requirements", ".", "update", "(", "requirements_left", ")", "if", "len", "(", "nested_requirements", ")", "==", "0", ":", "return", "current_result", "return", "calculate_priorities", "(", "*", "list", "(", "nested_requirements", ")", ",", "current_result", "=", "current_result", ",", "requirements_left", "=", "all_requirements", ")", "if", "stop_dependent", "is", "True", ":", "stop_dependency", "(", "task", ")", "if", "stop_requirements", "is", "True", ":", "for", "task_list", "in", "calculate_priorities", "(", "task", ")", ":", "for", "single_task", "in", "task_list", ":", "stop", "(", "single_task", ")", "if", "stop_dependent", "is", "not", "True", ":", "# check if we've already stopped this task", "stop", "(", "task", ")" ]
Stop task with the given task tag. If task already stopped, then nothing happens. :param task_tag: task to stop :param stop_dependent: if True, then every task, that require the given task as dependency, will be \ stopped before. :param stop_requirements: if True, then every task, that is required as dependency for the given task, \ will be stopped after. :return: None
[ "Stop", "task", "with", "the", "given", "task", "tag", ".", "If", "task", "already", "stopped", "then", "nothing", "happens", "." ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/dependency.py#L218-L312
train
a1ezzz/wasp-general
wasp_general/task/dependency.py
WTaskDependencyRegistry.start_task
def start_task(cls, task_tag, skip_unresolved=False): """ Start task from registry :param task_tag: same as in :meth:`.WTaskDependencyRegistryStorage.start_task` method :param skip_unresolved: same as in :meth:`.WTaskDependencyRegistryStorage.start_task` method :return: None """ registry = cls.registry_storage() registry.start_task(task_tag, skip_unresolved=skip_unresolved)
python
def start_task(cls, task_tag, skip_unresolved=False): """ Start task from registry :param task_tag: same as in :meth:`.WTaskDependencyRegistryStorage.start_task` method :param skip_unresolved: same as in :meth:`.WTaskDependencyRegistryStorage.start_task` method :return: None """ registry = cls.registry_storage() registry.start_task(task_tag, skip_unresolved=skip_unresolved)
[ "def", "start_task", "(", "cls", ",", "task_tag", ",", "skip_unresolved", "=", "False", ")", ":", "registry", "=", "cls", ".", "registry_storage", "(", ")", "registry", ".", "start_task", "(", "task_tag", ",", "skip_unresolved", "=", "skip_unresolved", ")" ]
Start task from registry :param task_tag: same as in :meth:`.WTaskDependencyRegistryStorage.start_task` method :param skip_unresolved: same as in :meth:`.WTaskDependencyRegistryStorage.start_task` method :return: None
[ "Start", "task", "from", "registry" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/dependency.py#L338-L346
train
a1ezzz/wasp-general
wasp_general/task/dependency.py
WTaskDependencyRegistry.stop_task
def stop_task(cls, task_tag, stop_dependent=True, stop_requirements=False): """ Stop started task from registry :param task_tag: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method :param stop_dependent: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method :param stop_requirements: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method :return: None """ registry = cls.registry_storage() registry.stop_task(task_tag, stop_dependent=stop_dependent, stop_requirements=stop_requirements)
python
def stop_task(cls, task_tag, stop_dependent=True, stop_requirements=False): """ Stop started task from registry :param task_tag: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method :param stop_dependent: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method :param stop_requirements: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method :return: None """ registry = cls.registry_storage() registry.stop_task(task_tag, stop_dependent=stop_dependent, stop_requirements=stop_requirements)
[ "def", "stop_task", "(", "cls", ",", "task_tag", ",", "stop_dependent", "=", "True", ",", "stop_requirements", "=", "False", ")", ":", "registry", "=", "cls", ".", "registry_storage", "(", ")", "registry", ".", "stop_task", "(", "task_tag", ",", "stop_dependent", "=", "stop_dependent", ",", "stop_requirements", "=", "stop_requirements", ")" ]
Stop started task from registry :param task_tag: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method :param stop_dependent: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method :param stop_requirements: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method :return: None
[ "Stop", "started", "task", "from", "registry" ]
1029839d33eb663f8dec76c1c46754d53c1de4a9
https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/dependency.py#L349-L358
train
jahuth/litus
__init__.py
snip_this
def snip_this(tag="",write_date=True): """ When this function is invoced in a notebook cell, the cell is snipped. """ snip(tag=tag,start=-1,write_date=write_date)
python
def snip_this(tag="",write_date=True): """ When this function is invoced in a notebook cell, the cell is snipped. """ snip(tag=tag,start=-1,write_date=write_date)
[ "def", "snip_this", "(", "tag", "=", "\"\"", ",", "write_date", "=", "True", ")", ":", "snip", "(", "tag", "=", "tag", ",", "start", "=", "-", "1", ",", "write_date", "=", "write_date", ")" ]
When this function is invoced in a notebook cell, the cell is snipped.
[ "When", "this", "function", "is", "invoced", "in", "a", "notebook", "cell", "the", "cell", "is", "snipped", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/__init__.py#L51-L53
train
jahuth/litus
__init__.py
unsnip
def unsnip(tag=None,start=-1): """ This function retrieves a tagged or untagged snippet. """ import IPython i = IPython.get_ipython() if tag in _tagged_inputs.keys(): if len(_tagged_inputs[tag]) > 0: i.set_next_input(_tagged_inputs[tag][start]) else: if len(_last_inputs) > 0: i.set_next_input(_last_inputs[start])
python
def unsnip(tag=None,start=-1): """ This function retrieves a tagged or untagged snippet. """ import IPython i = IPython.get_ipython() if tag in _tagged_inputs.keys(): if len(_tagged_inputs[tag]) > 0: i.set_next_input(_tagged_inputs[tag][start]) else: if len(_last_inputs) > 0: i.set_next_input(_last_inputs[start])
[ "def", "unsnip", "(", "tag", "=", "None", ",", "start", "=", "-", "1", ")", ":", "import", "IPython", "i", "=", "IPython", ".", "get_ipython", "(", ")", "if", "tag", "in", "_tagged_inputs", ".", "keys", "(", ")", ":", "if", "len", "(", "_tagged_inputs", "[", "tag", "]", ")", ">", "0", ":", "i", ".", "set_next_input", "(", "_tagged_inputs", "[", "tag", "]", "[", "start", "]", ")", "else", ":", "if", "len", "(", "_last_inputs", ")", ">", "0", ":", "i", ".", "set_next_input", "(", "_last_inputs", "[", "start", "]", ")" ]
This function retrieves a tagged or untagged snippet.
[ "This", "function", "retrieves", "a", "tagged", "or", "untagged", "snippet", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/__init__.py#L55-L64
train
jahuth/litus
__init__.py
alert
def alert(msg,body="",icon=None): """ alerts the user of something happening via `notify-send`. If it is not installed, the alert will be printed to the console. """ if type(body) == str: body = body[:200] if call(["which","notify-send"]) == 0: if icon is not None: call(["notify-send",msg,"-i",icon,body]) else: call(["notify-send",msg,body]) else: print(("ALERT: ", msg))
python
def alert(msg,body="",icon=None): """ alerts the user of something happening via `notify-send`. If it is not installed, the alert will be printed to the console. """ if type(body) == str: body = body[:200] if call(["which","notify-send"]) == 0: if icon is not None: call(["notify-send",msg,"-i",icon,body]) else: call(["notify-send",msg,body]) else: print(("ALERT: ", msg))
[ "def", "alert", "(", "msg", ",", "body", "=", "\"\"", ",", "icon", "=", "None", ")", ":", "if", "type", "(", "body", ")", "==", "str", ":", "body", "=", "body", "[", ":", "200", "]", "if", "call", "(", "[", "\"which\"", ",", "\"notify-send\"", "]", ")", "==", "0", ":", "if", "icon", "is", "not", "None", ":", "call", "(", "[", "\"notify-send\"", ",", "msg", ",", "\"-i\"", ",", "icon", ",", "body", "]", ")", "else", ":", "call", "(", "[", "\"notify-send\"", ",", "msg", ",", "body", "]", ")", "else", ":", "print", "(", "(", "\"ALERT: \"", ",", "msg", ")", ")" ]
alerts the user of something happening via `notify-send`. If it is not installed, the alert will be printed to the console.
[ "alerts", "the", "user", "of", "something", "happening", "via", "notify", "-", "send", ".", "If", "it", "is", "not", "installed", "the", "alert", "will", "be", "printed", "to", "the", "console", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/__init__.py#L271-L283
train
jahuth/litus
__init__.py
recgen
def recgen(gen, fix_type_errors=True): """ Iterates through generators recursively and flattens them. If `fix_type_errors` is True, `TypeError`s that are generated by iterating are ignored and the generator that raised the Exception is yielded instead. This is the case eg. for theano tensor variables. If you want `TypeError`s to be re-raised, set `fix_type_errors` to False. Aliases for this function: `generate_recursively` and `flatten_generator`. `recgen_enumerate` enumerates the result with tuples corresponding to each index used. """ if not hasattr(gen,'__iter__'): yield gen else: try: for i in gen: for ii in recgen(i): yield ii except TypeError: # oops, it seems it was not an iterable even if it had an __iter__ method... # this happens eg. with theano tensor variables as they try to trick you to sum them. if not fix_type_errors: raise # maybe you want this Exception? yield gen
python
def recgen(gen, fix_type_errors=True): """ Iterates through generators recursively and flattens them. If `fix_type_errors` is True, `TypeError`s that are generated by iterating are ignored and the generator that raised the Exception is yielded instead. This is the case eg. for theano tensor variables. If you want `TypeError`s to be re-raised, set `fix_type_errors` to False. Aliases for this function: `generate_recursively` and `flatten_generator`. `recgen_enumerate` enumerates the result with tuples corresponding to each index used. """ if not hasattr(gen,'__iter__'): yield gen else: try: for i in gen: for ii in recgen(i): yield ii except TypeError: # oops, it seems it was not an iterable even if it had an __iter__ method... # this happens eg. with theano tensor variables as they try to trick you to sum them. if not fix_type_errors: raise # maybe you want this Exception? yield gen
[ "def", "recgen", "(", "gen", ",", "fix_type_errors", "=", "True", ")", ":", "if", "not", "hasattr", "(", "gen", ",", "'__iter__'", ")", ":", "yield", "gen", "else", ":", "try", ":", "for", "i", "in", "gen", ":", "for", "ii", "in", "recgen", "(", "i", ")", ":", "yield", "ii", "except", "TypeError", ":", "# oops, it seems it was not an iterable even if it had an __iter__ method...", "# this happens eg. with theano tensor variables as they try to trick you to sum them.", "if", "not", "fix_type_errors", ":", "raise", "# maybe you want this Exception?", "yield", "gen" ]
Iterates through generators recursively and flattens them. If `fix_type_errors` is True, `TypeError`s that are generated by iterating are ignored and the generator that raised the Exception is yielded instead. This is the case eg. for theano tensor variables. If you want `TypeError`s to be re-raised, set `fix_type_errors` to False. Aliases for this function: `generate_recursively` and `flatten_generator`. `recgen_enumerate` enumerates the result with tuples corresponding to each index used.
[ "Iterates", "through", "generators", "recursively", "and", "flattens", "them", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/__init__.py#L510-L538
train
jahuth/litus
__init__.py
list_of_dicts_to_dict_of_lists
def list_of_dicts_to_dict_of_lists(list_of_dictionaries): """ Takes a list of dictionaries and creates a dictionary with the combined values for each key in each dicitonary. Missing values are set to `None` for each dicitonary that does not contain a key that is present in at least one other dicitonary. >>> litus.list_of_dicts_to_dict_of_lists([{'a':1,'b':2,'c':3},{'a':3,'b':4,'c':5},{'a':1,'b':2,'c':3}]) {'a': [1, 3, 1], 'b': [2, 4, 2], 'c': [3, 5, 3]} Shorthand: `litus.ld2dl(..)` """ result = {} all_keys = set([k for d in list_of_dictionaries for k in d.keys()]) for d in list_of_dictionaries: for k in all_keys: result.setdefault(k,[]).append(d.get(k,None)) return result
python
def list_of_dicts_to_dict_of_lists(list_of_dictionaries): """ Takes a list of dictionaries and creates a dictionary with the combined values for each key in each dicitonary. Missing values are set to `None` for each dicitonary that does not contain a key that is present in at least one other dicitonary. >>> litus.list_of_dicts_to_dict_of_lists([{'a':1,'b':2,'c':3},{'a':3,'b':4,'c':5},{'a':1,'b':2,'c':3}]) {'a': [1, 3, 1], 'b': [2, 4, 2], 'c': [3, 5, 3]} Shorthand: `litus.ld2dl(..)` """ result = {} all_keys = set([k for d in list_of_dictionaries for k in d.keys()]) for d in list_of_dictionaries: for k in all_keys: result.setdefault(k,[]).append(d.get(k,None)) return result
[ "def", "list_of_dicts_to_dict_of_lists", "(", "list_of_dictionaries", ")", ":", "result", "=", "{", "}", "all_keys", "=", "set", "(", "[", "k", "for", "d", "in", "list_of_dictionaries", "for", "k", "in", "d", ".", "keys", "(", ")", "]", ")", "for", "d", "in", "list_of_dictionaries", ":", "for", "k", "in", "all_keys", ":", "result", ".", "setdefault", "(", "k", ",", "[", "]", ")", ".", "append", "(", "d", ".", "get", "(", "k", ",", "None", ")", ")", "return", "result" ]
Takes a list of dictionaries and creates a dictionary with the combined values for each key in each dicitonary. Missing values are set to `None` for each dicitonary that does not contain a key that is present in at least one other dicitonary. >>> litus.list_of_dicts_to_dict_of_lists([{'a':1,'b':2,'c':3},{'a':3,'b':4,'c':5},{'a':1,'b':2,'c':3}]) {'a': [1, 3, 1], 'b': [2, 4, 2], 'c': [3, 5, 3]} Shorthand: `litus.ld2dl(..)`
[ "Takes", "a", "list", "of", "dictionaries", "and", "creates", "a", "dictionary", "with", "the", "combined", "values", "for", "each", "key", "in", "each", "dicitonary", ".", "Missing", "values", "are", "set", "to", "None", "for", "each", "dicitonary", "that", "does", "not", "contain", "a", "key", "that", "is", "present", "in", "at", "least", "one", "other", "dicitonary", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/__init__.py#L564-L582
train
jahuth/litus
__init__.py
dict_of_lists_to_list_of_dicts
def dict_of_lists_to_list_of_dicts(dictionary_of_lists): """ Takes a dictionary of lists and creates a list of dictionaries. If the lists are of unequal length, the remaining entries are set to `None`. Shorthand: `litus.dl2ld(..)`: >>> litus.dl2ld({'a': [1, 3, 1], 'b': [2, 4, 2], 'c': [3, 5, 3]}) [{'a': 1, 'b': 2, 'c': 3}, {'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}] """ return [{key: dictionary_of_lists[key][index] if len(dictionary_of_lists[key]) > index else None for key in dictionary_of_lists.keys()} for index in range(max(map(len,dictionary_of_lists.values())))]
python
def dict_of_lists_to_list_of_dicts(dictionary_of_lists): """ Takes a dictionary of lists and creates a list of dictionaries. If the lists are of unequal length, the remaining entries are set to `None`. Shorthand: `litus.dl2ld(..)`: >>> litus.dl2ld({'a': [1, 3, 1], 'b': [2, 4, 2], 'c': [3, 5, 3]}) [{'a': 1, 'b': 2, 'c': 3}, {'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}] """ return [{key: dictionary_of_lists[key][index] if len(dictionary_of_lists[key]) > index else None for key in dictionary_of_lists.keys()} for index in range(max(map(len,dictionary_of_lists.values())))]
[ "def", "dict_of_lists_to_list_of_dicts", "(", "dictionary_of_lists", ")", ":", "return", "[", "{", "key", ":", "dictionary_of_lists", "[", "key", "]", "[", "index", "]", "if", "len", "(", "dictionary_of_lists", "[", "key", "]", ")", ">", "index", "else", "None", "for", "key", "in", "dictionary_of_lists", ".", "keys", "(", ")", "}", "for", "index", "in", "range", "(", "max", "(", "map", "(", "len", ",", "dictionary_of_lists", ".", "values", "(", ")", ")", ")", ")", "]" ]
Takes a dictionary of lists and creates a list of dictionaries. If the lists are of unequal length, the remaining entries are set to `None`. Shorthand: `litus.dl2ld(..)`: >>> litus.dl2ld({'a': [1, 3, 1], 'b': [2, 4, 2], 'c': [3, 5, 3]}) [{'a': 1, 'b': 2, 'c': 3}, {'a': 3, 'b': 4, 'c': 5}, {'a': 1, 'b': 2, 'c': 3}]
[ "Takes", "a", "dictionary", "of", "lists", "and", "creates", "a", "list", "of", "dictionaries", ".", "If", "the", "lists", "are", "of", "unequal", "length", "the", "remaining", "entries", "are", "set", "to", "None", "." ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/__init__.py#L586-L599
train
jahuth/litus
__init__.py
colorate
def colorate(sequence, colormap="", start=0, length=None): """ like enumerate, but with colors """ n = start colors = color_space(colormap, sequence, start=0.1, stop=0.9, length=length) for elem in sequence: yield n, colors[n-start], elem n += 1
python
def colorate(sequence, colormap="", start=0, length=None): """ like enumerate, but with colors """ n = start colors = color_space(colormap, sequence, start=0.1, stop=0.9, length=length) for elem in sequence: yield n, colors[n-start], elem n += 1
[ "def", "colorate", "(", "sequence", ",", "colormap", "=", "\"\"", ",", "start", "=", "0", ",", "length", "=", "None", ")", ":", "n", "=", "start", "colors", "=", "color_space", "(", "colormap", ",", "sequence", ",", "start", "=", "0.1", ",", "stop", "=", "0.9", ",", "length", "=", "length", ")", "for", "elem", "in", "sequence", ":", "yield", "n", ",", "colors", "[", "n", "-", "start", "]", ",", "elem", "n", "+=", "1" ]
like enumerate, but with colors
[ "like", "enumerate", "but", "with", "colors" ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/__init__.py#L618-L624
train
jahuth/litus
__init__.py
PDContainerList.generate
def generate(self,**kwargs): """run once to create all children containers for each combination of the keywords""" import collections all_params = cartesian_dicts({k:kwargs[k] for k in kwargs.keys() if isinstance(kwargs[k], collections.Iterable)}) for pi,p in enumerate(all_params): if self.name_mode == 'int': n = str(len(self.containers)) else: n = None self.containers.append(PDContainer(name=n,params=p,parent=self)) self.parameters.update({ k: kwargs[k] for k in kwargs.keys() if not isinstance(kwargs[k], collections.Iterable) }) self.save()
python
def generate(self,**kwargs): """run once to create all children containers for each combination of the keywords""" import collections all_params = cartesian_dicts({k:kwargs[k] for k in kwargs.keys() if isinstance(kwargs[k], collections.Iterable)}) for pi,p in enumerate(all_params): if self.name_mode == 'int': n = str(len(self.containers)) else: n = None self.containers.append(PDContainer(name=n,params=p,parent=self)) self.parameters.update({ k: kwargs[k] for k in kwargs.keys() if not isinstance(kwargs[k], collections.Iterable) }) self.save()
[ "def", "generate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "import", "collections", "all_params", "=", "cartesian_dicts", "(", "{", "k", ":", "kwargs", "[", "k", "]", "for", "k", "in", "kwargs", ".", "keys", "(", ")", "if", "isinstance", "(", "kwargs", "[", "k", "]", ",", "collections", ".", "Iterable", ")", "}", ")", "for", "pi", ",", "p", "in", "enumerate", "(", "all_params", ")", ":", "if", "self", ".", "name_mode", "==", "'int'", ":", "n", "=", "str", "(", "len", "(", "self", ".", "containers", ")", ")", "else", ":", "n", "=", "None", "self", ".", "containers", ".", "append", "(", "PDContainer", "(", "name", "=", "n", ",", "params", "=", "p", ",", "parent", "=", "self", ")", ")", "self", ".", "parameters", ".", "update", "(", "{", "k", ":", "kwargs", "[", "k", "]", "for", "k", "in", "kwargs", ".", "keys", "(", ")", "if", "not", "isinstance", "(", "kwargs", "[", "k", "]", ",", "collections", ".", "Iterable", ")", "}", ")", "self", ".", "save", "(", ")" ]
run once to create all children containers for each combination of the keywords
[ "run", "once", "to", "create", "all", "children", "containers", "for", "each", "combination", "of", "the", "keywords" ]
712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e
https://github.com/jahuth/litus/blob/712b016ea2dbb1cf0a30bfdbb0a136945a7b7c5e/__init__.py#L764-L775
train