repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
3 values
summary
stringlengths
4
350
dsoprea/PySchedules
pyschedules/xml_callbacks.py
XmlCallbacks._startGenresNode
def _startGenresNode(self, name, attrs): """Process the start of a node under xtvd/genres""" if name == 'programGenre': self._programId = attrs.get('program') elif name == 'genre': self._genre = None self._relevance = None
python
def _startGenresNode(self, name, attrs): """Process the start of a node under xtvd/genres""" if name == 'programGenre': self._programId = attrs.get('program') elif name == 'genre': self._genre = None self._relevance = None
[ "def", "_startGenresNode", "(", "self", ",", "name", ",", "attrs", ")", ":", "if", "name", "==", "'programGenre'", ":", "self", ".", "_programId", "=", "attrs", ".", "get", "(", "'program'", ")", "elif", "name", "==", "'genre'", ":", "self", ".", "_gen...
Process the start of a node under xtvd/genres
[ "Process", "the", "start", "of", "a", "node", "under", "xtvd", "/", "genres" ]
e5aae988fad90217f72db45f93bf69839f4d75e7
https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/xml_callbacks.py#L268-L275
train
Process the start of a genres node under xtvd / genres
dsoprea/PySchedules
pyschedules/xml_callbacks.py
XmlCallbacks._endGenresNode
def _endGenresNode(self, name, content): """Process the end of a node under xtvd/genres""" if name == 'class': self._genre = content elif name == 'relevance': self._relevance = content elif name == 'genre': if not self._error: self._im...
python
def _endGenresNode(self, name, content): """Process the end of a node under xtvd/genres""" if name == 'class': self._genre = content elif name == 'relevance': self._relevance = content elif name == 'genre': if not self._error: self._im...
[ "def", "_endGenresNode", "(", "self", ",", "name", ",", "content", ")", ":", "if", "name", "==", "'class'", ":", "self", ".", "_genre", "=", "content", "elif", "name", "==", "'relevance'", ":", "self", ".", "_relevance", "=", "content", "elif", "name", ...
Process the end of a node under xtvd/genres
[ "Process", "the", "end", "of", "a", "node", "under", "xtvd", "/", "genres" ]
e5aae988fad90217f72db45f93bf69839f4d75e7
https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/xml_callbacks.py#L277-L287
train
Process the end of a genres node under xtvd / genres
dsoprea/PySchedules
pyschedules/xml_callbacks.py
XmlCallbacks.startElement
def startElement(self, name, attrs): """Callback run at the start of each XML element""" self._contextStack.append(self._context) self._contentList = [] if name in self._statusDict: self._itemTag, itemType = self._statusDict[name] self._progress.startItem(itemTy...
python
def startElement(self, name, attrs): """Callback run at the start of each XML element""" self._contextStack.append(self._context) self._contentList = [] if name in self._statusDict: self._itemTag, itemType = self._statusDict[name] self._progress.startItem(itemTy...
[ "def", "startElement", "(", "self", ",", "name", ",", "attrs", ")", ":", "self", ".", "_contextStack", ".", "append", "(", "self", ".", "_context", ")", "self", ".", "_contentList", "=", "[", "]", "if", "name", "in", "self", ".", "_statusDict", ":", ...
Callback run at the start of each XML element
[ "Callback", "run", "at", "the", "start", "of", "each", "XML", "element" ]
e5aae988fad90217f72db45f93bf69839f4d75e7
https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/xml_callbacks.py#L289-L323
train
Callback run at the beginning of each XML element
dsoprea/PySchedules
pyschedules/xml_callbacks.py
XmlCallbacks.endElement
def endElement(self, name): """Callback run at the end of each XML element""" content = ''.join(self._contentList) if name == 'xtvd': self._progress.endItems() else: try: if self._context == 'stations': self._endStationsNode(n...
python
def endElement(self, name): """Callback run at the end of each XML element""" content = ''.join(self._contentList) if name == 'xtvd': self._progress.endItems() else: try: if self._context == 'stations': self._endStationsNode(n...
[ "def", "endElement", "(", "self", ",", "name", ")", ":", "content", "=", "''", ".", "join", "(", "self", ".", "_contentList", ")", "if", "name", "==", "'xtvd'", ":", "self", ".", "_progress", ".", "endItems", "(", ")", "else", ":", "try", ":", "if"...
Callback run at the end of each XML element
[ "Callback", "run", "at", "the", "end", "of", "each", "XML", "element" ]
e5aae988fad90217f72db45f93bf69839f4d75e7
https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/xml_callbacks.py#L330-L355
train
Callback run at the end of each XML element
dsoprea/PySchedules
pyschedules/xml_callbacks.py
XmlCallbacks.error
def error(self, msg): """Callback run when a recoverable parsing error occurs""" self._error = True self._progress.printMsg('XML parse error: %s' % msg, error=True)
python
def error(self, msg): """Callback run when a recoverable parsing error occurs""" self._error = True self._progress.printMsg('XML parse error: %s' % msg, error=True)
[ "def", "error", "(", "self", ",", "msg", ")", ":", "self", ".", "_error", "=", "True", "self", ".", "_progress", ".", "printMsg", "(", "'XML parse error: %s'", "%", "msg", ",", "error", "=", "True", ")" ]
Callback run when a recoverable parsing error occurs
[ "Callback", "run", "when", "a", "recoverable", "parsing", "error", "occurs" ]
e5aae988fad90217f72db45f93bf69839f4d75e7
https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/xml_callbacks.py#L357-L361
train
Callback run when an XML parse error occurs
dsoprea/PySchedules
pyschedules/interfaces/ientity_trigger.py
IEntityTrigger.new_mapping
def new_mapping(self, lineup, station, channel, channelMinor, validFrom, validTo, onAirFrom, onAirTo): """Callback run for each new mapping within a lineup""" raise NotImplementedError()
python
def new_mapping(self, lineup, station, channel, channelMinor, validFrom, validTo, onAirFrom, onAirTo): """Callback run for each new mapping within a lineup""" raise NotImplementedError()
[ "def", "new_mapping", "(", "self", ",", "lineup", ",", "station", ",", "channel", ",", "channelMinor", ",", "validFrom", ",", "validTo", ",", "onAirFrom", ",", "onAirTo", ")", ":", "raise", "NotImplementedError", "(", ")" ]
Callback run for each new mapping within a lineup
[ "Callback", "run", "for", "each", "new", "mapping", "within", "a", "lineup" ]
e5aae988fad90217f72db45f93bf69839f4d75e7
https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/interfaces/ientity_trigger.py#L12-L16
train
Callback run for each new mapping within a lineup
dsoprea/PySchedules
pyschedules/interfaces/ientity_trigger.py
IEntityTrigger.new_schedule
def new_schedule(self, program, station, time, duration, new, stereo, subtitled, hdtv, closeCaptioned, ei, tvRating, dolby, partNumber, partTotal): """Callback run for each new schedule entry""" raise NotImplementedError()
python
def new_schedule(self, program, station, time, duration, new, stereo, subtitled, hdtv, closeCaptioned, ei, tvRating, dolby, partNumber, partTotal): """Callback run for each new schedule entry""" raise NotImplementedError()
[ "def", "new_schedule", "(", "self", ",", "program", ",", "station", ",", "time", ",", "duration", ",", "new", ",", "stereo", ",", "subtitled", ",", "hdtv", ",", "closeCaptioned", ",", "ei", ",", "tvRating", ",", "dolby", ",", "partNumber", ",", "partTota...
Callback run for each new schedule entry
[ "Callback", "run", "for", "each", "new", "schedule", "entry" ]
e5aae988fad90217f72db45f93bf69839f4d75e7
https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/interfaces/ientity_trigger.py#L18-L23
train
Callback run for each new schedule entry
dsoprea/PySchedules
pyschedules/interfaces/ientity_trigger.py
IEntityTrigger.new_program
def new_program(self, _id, series, title, subtitle, description, mpaaRating, starRating, runTime, year, showType, colorCode, originalAirDate, syndicatedEpisodeNumber, advisories): """Callback run for each new program entry""" raise NotImplementedError()
python
def new_program(self, _id, series, title, subtitle, description, mpaaRating, starRating, runTime, year, showType, colorCode, originalAirDate, syndicatedEpisodeNumber, advisories): """Callback run for each new program entry""" raise NotImplementedError()
[ "def", "new_program", "(", "self", ",", "_id", ",", "series", ",", "title", ",", "subtitle", ",", "description", ",", "mpaaRating", ",", "starRating", ",", "runTime", ",", "year", ",", "showType", ",", "colorCode", ",", "originalAirDate", ",", "syndicatedEpi...
Callback run for each new program entry
[ "Callback", "run", "for", "each", "new", "program", "entry" ]
e5aae988fad90217f72db45f93bf69839f4d75e7
https://github.com/dsoprea/PySchedules/blob/e5aae988fad90217f72db45f93bf69839f4d75e7/pyschedules/interfaces/ientity_trigger.py#L25-L30
train
Callback run for each new program entry
NaPs/Kolekto
kolekto/commands/link.py
format_all
def format_all(format_string, env): """ Format the input string using each possible combination of lists in the provided environment. Returns a list of formated strings. """ prepared_env = parse_pattern(format_string, env, lambda x, y: [FormatWrapper(x, z) for z in y]) # Generate each possible ...
python
def format_all(format_string, env): """ Format the input string using each possible combination of lists in the provided environment. Returns a list of formated strings. """ prepared_env = parse_pattern(format_string, env, lambda x, y: [FormatWrapper(x, z) for z in y]) # Generate each possible ...
[ "def", "format_all", "(", "format_string", ",", "env", ")", ":", "prepared_env", "=", "parse_pattern", "(", "format_string", ",", "env", ",", "lambda", "x", ",", "y", ":", "[", "FormatWrapper", "(", "x", ",", "z", ")", "for", "z", "in", "y", "]", ")"...
Format the input string using each possible combination of lists in the provided environment. Returns a list of formated strings.
[ "Format", "the", "input", "string", "using", "each", "possible", "combination", "of", "lists", "in", "the", "provided", "environment", ".", "Returns", "a", "list", "of", "formated", "strings", "." ]
29c5469da8782780a06bf9a76c59414bb6fd8fe3
https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/commands/link.py#L26-L36
train
Format the input string using each possible combination of lists in the provided environment. Returns a list of formated strings.
NaPs/Kolekto
kolekto/commands/link.py
walk_links
def walk_links(directory, prefix='', linkbase=None): """ Return all links contained in directory (or any sub directory). """ links = {} try: for child in os.listdir(directory): fullname = os.path.join(directory, child) if os.path.islink(fullname): link_pat...
python
def walk_links(directory, prefix='', linkbase=None): """ Return all links contained in directory (or any sub directory). """ links = {} try: for child in os.listdir(directory): fullname = os.path.join(directory, child) if os.path.islink(fullname): link_pat...
[ "def", "walk_links", "(", "directory", ",", "prefix", "=", "''", ",", "linkbase", "=", "None", ")", ":", "links", "=", "{", "}", "try", ":", "for", "child", "in", "os", ".", "listdir", "(", "directory", ")", ":", "fullname", "=", "os", ".", "path",...
Return all links contained in directory (or any sub directory).
[ "Return", "all", "links", "contained", "in", "directory", "(", "or", "any", "sub", "directory", ")", "." ]
29c5469da8782780a06bf9a76c59414bb6fd8fe3
https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/commands/link.py#L39-L58
train
Recursively walks a directory and returns all links contained in it.
tamasgal/km3pipe
km3pipe/utils/rba.py
RBAPrompt.preloop
def preloop(self): """Initialization before prompting user for commands. Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub """ Cmd.preloop(self) # sets up command completion self._hist = [] # No history yet self._locals = {} # Initialize ex...
python
def preloop(self): """Initialization before prompting user for commands. Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub """ Cmd.preloop(self) # sets up command completion self._hist = [] # No history yet self._locals = {} # Initialize ex...
[ "def", "preloop", "(", "self", ")", ":", "Cmd", ".", "preloop", "(", "self", ")", "# sets up command completion", "self", ".", "_hist", "=", "[", "]", "# No history yet", "self", ".", "_locals", "=", "{", "}", "# Initialize execution namespace for user", "self",...
Initialization before prompting user for commands. Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub
[ "Initialization", "before", "prompting", "user", "for", "commands", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/rba.py#L46-L54
train
Initialize before prompting user for commands.
IRC-SPHERE/HyperStream
hyperstream/channels/base_channel.py
BaseChannel.execute_tool
def execute_tool(self, stream, interval): """ Executes the stream's tool over the given time interval :param stream: the stream reference :param interval: the time interval :return: None """ if interval.end > self.up_to_timestamp: raise ValueError( ...
python
def execute_tool(self, stream, interval): """ Executes the stream's tool over the given time interval :param stream: the stream reference :param interval: the time interval :return: None """ if interval.end > self.up_to_timestamp: raise ValueError( ...
[ "def", "execute_tool", "(", "self", ",", "stream", ",", "interval", ")", ":", "if", "interval", ".", "end", ">", "self", ".", "up_to_timestamp", ":", "raise", "ValueError", "(", "'The stream is not available after '", "+", "str", "(", "self", ".", "up_to_times...
Executes the stream's tool over the given time interval :param stream: the stream reference :param interval: the time interval :return: None
[ "Executes", "the", "stream", "s", "tool", "over", "the", "given", "time", "interval" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/channels/base_channel.py#L46-L65
train
Executes the stream s tool over the given time interval.
IRC-SPHERE/HyperStream
hyperstream/channels/base_channel.py
BaseChannel.get_or_create_stream
def get_or_create_stream(self, stream_id, try_create=True): """ Helper function to get a stream or create one if it's not already defined :param stream_id: The stream id :param try_create: Whether to try to create the stream if not found :return: The stream object """ ...
python
def get_or_create_stream(self, stream_id, try_create=True): """ Helper function to get a stream or create one if it's not already defined :param stream_id: The stream id :param try_create: Whether to try to create the stream if not found :return: The stream object """ ...
[ "def", "get_or_create_stream", "(", "self", ",", "stream_id", ",", "try_create", "=", "True", ")", ":", "stream_id", "=", "get_stream_id", "(", "stream_id", ")", "if", "stream_id", "in", "self", ".", "streams", ":", "logging", ".", "debug", "(", "\"found {}\...
Helper function to get a stream or create one if it's not already defined :param stream_id: The stream id :param try_create: Whether to try to create the stream if not found :return: The stream object
[ "Helper", "function", "to", "get", "a", "stream", "or", "create", "one", "if", "it", "s", "not", "already", "defined" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/channels/base_channel.py#L76-L91
train
Helper function to get a stream or create one if it s not already defined.
IRC-SPHERE/HyperStream
hyperstream/channels/base_channel.py
BaseChannel.find_streams
def find_streams(self, **kwargs): """ Finds streams with the given meta data values. Useful for debugging purposes. :param kwargs: The meta data as keyword arguments :return: The streams found """ found = {} if 'name' in kwargs: name = kwargs.pop('na...
python
def find_streams(self, **kwargs): """ Finds streams with the given meta data values. Useful for debugging purposes. :param kwargs: The meta data as keyword arguments :return: The streams found """ found = {} if 'name' in kwargs: name = kwargs.pop('na...
[ "def", "find_streams", "(", "self", ",", "*", "*", "kwargs", ")", ":", "found", "=", "{", "}", "if", "'name'", "in", "kwargs", ":", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "else", ":", "name", "=", "None", "for", "stream_id", ",", ...
Finds streams with the given meta data values. Useful for debugging purposes. :param kwargs: The meta data as keyword arguments :return: The streams found
[ "Finds", "streams", "with", "the", "given", "meta", "data", "values", ".", "Useful", "for", "debugging", "purposes", "." ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/channels/base_channel.py#L100-L121
train
Finds streams with the given meta data values. Useful for debugging purposes.
IRC-SPHERE/HyperStream
hyperstream/channels/base_channel.py
BaseChannel.find_stream
def find_stream(self, **kwargs): """ Finds a single stream with the given meta data values. Useful for debugging purposes. :param kwargs: The meta data as keyword arguments :return: The stream found """ found = list(self.find_streams(**kwargs).values()) if not fo...
python
def find_stream(self, **kwargs): """ Finds a single stream with the given meta data values. Useful for debugging purposes. :param kwargs: The meta data as keyword arguments :return: The stream found """ found = list(self.find_streams(**kwargs).values()) if not fo...
[ "def", "find_stream", "(", "self", ",", "*", "*", "kwargs", ")", ":", "found", "=", "list", "(", "self", ".", "find_streams", "(", "*", "*", "kwargs", ")", ".", "values", "(", ")", ")", "if", "not", "found", ":", "raise", "StreamNotFoundError", "(", ...
Finds a single stream with the given meta data values. Useful for debugging purposes. :param kwargs: The meta data as keyword arguments :return: The stream found
[ "Finds", "a", "single", "stream", "with", "the", "given", "meta", "data", "values", ".", "Useful", "for", "debugging", "purposes", "." ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/channels/base_channel.py#L123-L135
train
Finds a single stream with the given meta data values. Useful for debugging purposes.
IRC-SPHERE/HyperStream
hyperstream/channels/base_channel.py
BaseChannel.purge_node
def purge_node(self, node_id, remove_definition=False, sandbox=None): """ Purges a node (collection of streams) :param node_id: The node identifier :param remove_definition: Whether to remove the stream definition as well :param sandbox: The sandbox :return: None ...
python
def purge_node(self, node_id, remove_definition=False, sandbox=None): """ Purges a node (collection of streams) :param node_id: The node identifier :param remove_definition: Whether to remove the stream definition as well :param sandbox: The sandbox :return: None ...
[ "def", "purge_node", "(", "self", ",", "node_id", ",", "remove_definition", "=", "False", ",", "sandbox", "=", "None", ")", ":", "for", "stream_id", "in", "list", "(", "self", ".", "streams", ")", ":", "stream", "=", "self", ".", "streams", "[", "strea...
Purges a node (collection of streams) :param node_id: The node identifier :param remove_definition: Whether to remove the stream definition as well :param sandbox: The sandbox :return: None
[ "Purges", "a", "node", "(", "collection", "of", "streams", ")" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/channels/base_channel.py#L137-L153
train
Purges a node from the local cache
htm-community/menorah
menorah/confluencefactory.py
create
def create(streamIds, **kwargs): """ Creates and loads data into a Confluence, which is a collection of River Streams. :param streamIds: (list) Each data id in this list is a list of strings: 1. river name 2. stream name 3. field name :param kwargs...
python
def create(streamIds, **kwargs): """ Creates and loads data into a Confluence, which is a collection of River Streams. :param streamIds: (list) Each data id in this list is a list of strings: 1. river name 2. stream name 3. field name :param kwargs...
[ "def", "create", "(", "streamIds", ",", "*", "*", "kwargs", ")", ":", "print", "\"Creating Confluence for the following RiverStreams:\"", "\"\\n\\t%s\"", "%", "\",\\n\\t\"", ".", "join", "(", "[", "\":\"", ".", "join", "(", "row", ")", "for", "row", "in", "str...
Creates and loads data into a Confluence, which is a collection of River Streams. :param streamIds: (list) Each data id in this list is a list of strings: 1. river name 2. stream name 3. field name :param kwargs: Passed into Confluence constructor :r...
[ "Creates", "and", "loads", "data", "into", "a", "Confluence", "which", "is", "a", "collection", "of", "River", "Streams", ".", ":", "param", "streamIds", ":", "(", "list", ")", "Each", "data", "id", "in", "this", "list", "is", "a", "list", "of", "strin...
1991b01eda3f6361b22ed165b4a688ae3fb2deaf
https://github.com/htm-community/menorah/blob/1991b01eda3f6361b22ed165b4a688ae3fb2deaf/menorah/confluencefactory.py#L25-L40
train
Creates and loads a Confluence object for the given list of RiverStreams.
tamasgal/km3pipe
km3pipe/io/daq.py
DAQPump.next_blob
def next_blob(self): """Get the next frame from file""" blob_file = self.blob_file try: preamble = DAQPreamble(file_obj=blob_file) except struct.error: raise StopIteration try: data_type = DATA_TYPES[preamble.data_type] except KeyError...
python
def next_blob(self): """Get the next frame from file""" blob_file = self.blob_file try: preamble = DAQPreamble(file_obj=blob_file) except struct.error: raise StopIteration try: data_type = DATA_TYPES[preamble.data_type] except KeyError...
[ "def", "next_blob", "(", "self", ")", ":", "blob_file", "=", "self", ".", "blob_file", "try", ":", "preamble", "=", "DAQPreamble", "(", "file_obj", "=", "blob_file", ")", "except", "struct", ".", "error", ":", "raise", "StopIteration", "try", ":", "data_ty...
Get the next frame from file
[ "Get", "the", "next", "frame", "from", "file" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/daq.py#L145-L179
train
Get the next DAQ frame from the file
tamasgal/km3pipe
km3pipe/io/daq.py
DAQPump.seek_to_frame
def seek_to_frame(self, index): """Move file pointer to the frame with given index.""" pointer_position = self.frame_positions[index] self.blob_file.seek(pointer_position, 0)
python
def seek_to_frame(self, index): """Move file pointer to the frame with given index.""" pointer_position = self.frame_positions[index] self.blob_file.seek(pointer_position, 0)
[ "def", "seek_to_frame", "(", "self", ",", "index", ")", ":", "pointer_position", "=", "self", ".", "frame_positions", "[", "index", "]", "self", ".", "blob_file", ".", "seek", "(", "pointer_position", ",", "0", ")" ]
Move file pointer to the frame with given index.
[ "Move", "file", "pointer", "to", "the", "frame", "with", "given", "index", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/daq.py#L181-L184
train
Move file pointer to the frame with given index.
tamasgal/km3pipe
km3pipe/io/daq.py
DAQPump.determine_frame_positions
def determine_frame_positions(self): """Record the file pointer position of each frame""" self.rewind_file() with ignored(struct.error): while True: pointer_position = self.blob_file.tell() length = struct.unpack('<i', self.blob_file.read(4))[0] ...
python
def determine_frame_positions(self): """Record the file pointer position of each frame""" self.rewind_file() with ignored(struct.error): while True: pointer_position = self.blob_file.tell() length = struct.unpack('<i', self.blob_file.read(4))[0] ...
[ "def", "determine_frame_positions", "(", "self", ")", ":", "self", ".", "rewind_file", "(", ")", "with", "ignored", "(", "struct", ".", "error", ")", ":", "while", "True", ":", "pointer_position", "=", "self", ".", "blob_file", ".", "tell", "(", ")", "le...
Record the file pointer position of each frame
[ "Record", "the", "file", "pointer", "position", "of", "each", "frame" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/daq.py#L191-L201
train
Determine the file pointer positions of each frame in the archive.
tamasgal/km3pipe
km3pipe/io/daq.py
DAQPreamble._parse_byte_data
def _parse_byte_data(self, byte_data): """Extract the values from byte string.""" self.length, self.data_type = unpack('<ii', byte_data[:self.size])
python
def _parse_byte_data(self, byte_data): """Extract the values from byte string.""" self.length, self.data_type = unpack('<ii', byte_data[:self.size])
[ "def", "_parse_byte_data", "(", "self", ",", "byte_data", ")", ":", "self", ".", "length", ",", "self", ".", "data_type", "=", "unpack", "(", "'<ii'", ",", "byte_data", "[", ":", "self", ".", "size", "]", ")" ]
Extract the values from byte string.
[ "Extract", "the", "values", "from", "byte", "string", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/daq.py#L405-L407
train
Extracts the values from the byte string.
tamasgal/km3pipe
km3pipe/io/daq.py
DAQPreamble._parse_file
def _parse_file(self, file_obj): """Directly read from file handler. Note that this will move the file pointer. """ byte_data = file_obj.read(self.size) self._parse_byte_data(byte_data)
python
def _parse_file(self, file_obj): """Directly read from file handler. Note that this will move the file pointer. """ byte_data = file_obj.read(self.size) self._parse_byte_data(byte_data)
[ "def", "_parse_file", "(", "self", ",", "file_obj", ")", ":", "byte_data", "=", "file_obj", ".", "read", "(", "self", ".", "size", ")", "self", ".", "_parse_byte_data", "(", "byte_data", ")" ]
Directly read from file handler. Note that this will move the file pointer.
[ "Directly", "read", "from", "file", "handler", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/daq.py#L409-L416
train
Directly read from file handler.
tamasgal/km3pipe
km3pipe/io/daq.py
DAQHeader._parse_byte_data
def _parse_byte_data(self, byte_data): """Extract the values from byte string.""" chunks = unpack('<iiiii', byte_data[:self.size]) det_id, run, time_slice, time_stamp, ticks = chunks self.det_id = det_id self.run = run self.time_slice = time_slice self.time_stamp ...
python
def _parse_byte_data(self, byte_data): """Extract the values from byte string.""" chunks = unpack('<iiiii', byte_data[:self.size]) det_id, run, time_slice, time_stamp, ticks = chunks self.det_id = det_id self.run = run self.time_slice = time_slice self.time_stamp ...
[ "def", "_parse_byte_data", "(", "self", ",", "byte_data", ")", ":", "chunks", "=", "unpack", "(", "'<iiiii'", ",", "byte_data", "[", ":", "self", ".", "size", "]", ")", "det_id", ",", "run", ",", "time_slice", ",", "time_stamp", ",", "ticks", "=", "chu...
Extract the values from byte string.
[ "Extract", "the", "values", "from", "byte", "string", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/daq.py#L446-L454
train
Extract the values from the byte string.
tamasgal/km3pipe
km3pipe/io/daq.py
DAQSummaryslice._parse_summary_frames
def _parse_summary_frames(self, file_obj): """Iterate through the byte data and fill the summary_frames""" for _ in range(self.n_summary_frames): dom_id = unpack('<i', file_obj.read(4))[0] dq_status = file_obj.read(4) # probably dom status? # noqa dom_status = unpa...
python
def _parse_summary_frames(self, file_obj): """Iterate through the byte data and fill the summary_frames""" for _ in range(self.n_summary_frames): dom_id = unpack('<i', file_obj.read(4))[0] dq_status = file_obj.read(4) # probably dom status? # noqa dom_status = unpa...
[ "def", "_parse_summary_frames", "(", "self", ",", "file_obj", ")", ":", "for", "_", "in", "range", "(", "self", ".", "n_summary_frames", ")", ":", "dom_id", "=", "unpack", "(", "'<i'", ",", "file_obj", ".", "read", "(", "4", ")", ")", "[", "0", "]", ...
Iterate through the byte data and fill the summary_frames
[ "Iterate", "through", "the", "byte", "data", "and", "fill", "the", "summary_frames" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/daq.py#L499-L510
train
Iterate through the byte data and fill the summary_frames with the sum of the pmt rates and dom status.
tamasgal/km3pipe
km3pipe/io/daq.py
DAQSummaryslice._get_rate
def _get_rate(self, value): """Return the rate in Hz from the short int value""" if value == 0: return 0 else: return MINIMAL_RATE_HZ * math.exp(value * self._get_factor())
python
def _get_rate(self, value): """Return the rate in Hz from the short int value""" if value == 0: return 0 else: return MINIMAL_RATE_HZ * math.exp(value * self._get_factor())
[ "def", "_get_rate", "(", "self", ",", "value", ")", ":", "if", "value", "==", "0", ":", "return", "0", "else", ":", "return", "MINIMAL_RATE_HZ", "*", "math", ".", "exp", "(", "value", "*", "self", ".", "_get_factor", "(", ")", ")" ]
Return the rate in Hz from the short int value
[ "Return", "the", "rate", "in", "Hz", "from", "the", "short", "int", "value" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/daq.py#L512-L517
train
Return the rate in Hz from the short int value
tamasgal/km3pipe
km3pipe/io/daq.py
DAQEvent._parse_triggered_hits
def _parse_triggered_hits(self, file_obj): """Parse and store triggered hits.""" for _ in range(self.n_triggered_hits): dom_id, pmt_id = unpack('<ib', file_obj.read(5)) tdc_time = unpack('>I', file_obj.read(4))[0] tot = unpack('<b', file_obj.read(1))[0] tr...
python
def _parse_triggered_hits(self, file_obj): """Parse and store triggered hits.""" for _ in range(self.n_triggered_hits): dom_id, pmt_id = unpack('<ib', file_obj.read(5)) tdc_time = unpack('>I', file_obj.read(4))[0] tot = unpack('<b', file_obj.read(1))[0] tr...
[ "def", "_parse_triggered_hits", "(", "self", ",", "file_obj", ")", ":", "for", "_", "in", "range", "(", "self", ".", "n_triggered_hits", ")", ":", "dom_id", ",", "pmt_id", "=", "unpack", "(", "'<ib'", ",", "file_obj", ".", "read", "(", "5", ")", ")", ...
Parse and store triggered hits.
[ "Parse", "and", "store", "triggered", "hits", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/daq.py#L556-L565
train
Parse and store triggered hits.
tamasgal/km3pipe
km3pipe/io/daq.py
DAQEvent._parse_snapshot_hits
def _parse_snapshot_hits(self, file_obj): """Parse and store snapshot hits.""" for _ in range(self.n_snapshot_hits): dom_id, pmt_id = unpack('<ib', file_obj.read(5)) tdc_time = unpack('>I', file_obj.read(4))[0] tot = unpack('<b', file_obj.read(1))[0] self....
python
def _parse_snapshot_hits(self, file_obj): """Parse and store snapshot hits.""" for _ in range(self.n_snapshot_hits): dom_id, pmt_id = unpack('<ib', file_obj.read(5)) tdc_time = unpack('>I', file_obj.read(4))[0] tot = unpack('<b', file_obj.read(1))[0] self....
[ "def", "_parse_snapshot_hits", "(", "self", ",", "file_obj", ")", ":", "for", "_", "in", "range", "(", "self", ".", "n_snapshot_hits", ")", ":", "dom_id", ",", "pmt_id", "=", "unpack", "(", "'<ib'", ",", "file_obj", ".", "read", "(", "5", ")", ")", "...
Parse and store snapshot hits.
[ "Parse", "and", "store", "snapshot", "hits", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/io/daq.py#L567-L573
train
Parse and store snapshot hits.
tamasgal/km3pipe
km3pipe/utils/runtable.py
runtable
def runtable(det_id, n=5, run_range=None, compact=False, sep='\t', regex=None): """Print the run table of the last `n` runs for given detector""" db = kp.db.DBManager() df = db.run_table(det_id) if run_range is not None: try: from_run, to_run = [int(r) for r in run_range.split('-')]...
python
def runtable(det_id, n=5, run_range=None, compact=False, sep='\t', regex=None): """Print the run table of the last `n` runs for given detector""" db = kp.db.DBManager() df = db.run_table(det_id) if run_range is not None: try: from_run, to_run = [int(r) for r in run_range.split('-')]...
[ "def", "runtable", "(", "det_id", ",", "n", "=", "5", ",", "run_range", "=", "None", ",", "compact", "=", "False", ",", "sep", "=", "'\\t'", ",", "regex", "=", "None", ")", ":", "db", "=", "kp", ".", "db", ".", "DBManager", "(", ")", "df", "=",...
Print the run table of the last `n` runs for given detector
[ "Print", "the", "run", "table", "of", "the", "last", "n", "runs", "for", "given", "detector" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/runtable.py#L35-L65
train
Print the run table of the last n runs for given detector
tamasgal/km3pipe
km3modules/ahrs.py
fit_ahrs
def fit_ahrs(A, H, Aoff, Arot, Hoff, Hrot): """Calculate yaw, pitch and roll for given A/H and calibration set. Author: Vladimir Kulikovsky Parameters ---------- A: list, tuple or numpy.array of shape (3,) H: list, tuple or numpy.array of shape (3,) Aoff: numpy.array of shape(3,) Arot:...
python
def fit_ahrs(A, H, Aoff, Arot, Hoff, Hrot): """Calculate yaw, pitch and roll for given A/H and calibration set. Author: Vladimir Kulikovsky Parameters ---------- A: list, tuple or numpy.array of shape (3,) H: list, tuple or numpy.array of shape (3,) Aoff: numpy.array of shape(3,) Arot:...
[ "def", "fit_ahrs", "(", "A", ",", "H", ",", "Aoff", ",", "Arot", ",", "Hoff", ",", "Hrot", ")", ":", "Acal", "=", "np", ".", "dot", "(", "A", "-", "Aoff", ",", "Arot", ")", "Hcal", "=", "np", ".", "dot", "(", "H", "-", "Hoff", ",", "Hrot", ...
Calculate yaw, pitch and roll for given A/H and calibration set. Author: Vladimir Kulikovsky Parameters ---------- A: list, tuple or numpy.array of shape (3,) H: list, tuple or numpy.array of shape (3,) Aoff: numpy.array of shape(3,) Arot: numpy.array of shape(3, 3) Hoff: numpy.array o...
[ "Calculate", "yaw", "pitch", "and", "roll", "for", "given", "A", "/", "H", "and", "calibration", "set", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/ahrs.py#L112-L155
train
Fit a single A and H calibration set to a single A and H.
tamasgal/km3pipe
km3modules/ahrs.py
_extract_calibration
def _extract_calibration(xroot): """Extract AHRS calibration information from XML root. Parameters ---------- xroot: XML root Returns ------- Aoff: numpy.array with shape(3,) Arot: numpy.array with shape(3,3) Hoff: numpy.array with shape(3,) Hrot: numpy.array with shape(3,3) ...
python
def _extract_calibration(xroot): """Extract AHRS calibration information from XML root. Parameters ---------- xroot: XML root Returns ------- Aoff: numpy.array with shape(3,) Arot: numpy.array with shape(3,3) Hoff: numpy.array with shape(3,) Hrot: numpy.array with shape(3,3) ...
[ "def", "_extract_calibration", "(", "xroot", ")", ":", "names", "=", "[", "c", ".", "text", "for", "c", "in", "xroot", ".", "findall", "(", "\".//Name\"", ")", "]", "val", "=", "[", "[", "i", ".", "text", "for", "i", "in", "c", "]", "for", "c", ...
Extract AHRS calibration information from XML root. Parameters ---------- xroot: XML root Returns ------- Aoff: numpy.array with shape(3,) Arot: numpy.array with shape(3,3) Hoff: numpy.array with shape(3,) Hrot: numpy.array with shape(3,3)
[ "Extract", "AHRS", "calibration", "information", "from", "XML", "root", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/ahrs.py#L207-L256
train
Extract AHRS calibration information from XML root.
tamasgal/km3pipe
km3modules/ahrs.py
AHRSCalibrator.calibrate
def calibrate(self): """Calculate yaw, pitch and roll from the median of A and H. After successful calibration, the `self.A` and `self.H` are reset. DOMs with missing AHRS pre-calibration data are skipped. Returns ------- dict: key=dom_id, value=tuple: (timestamp, du, f...
python
def calibrate(self): """Calculate yaw, pitch and roll from the median of A and H. After successful calibration, the `self.A` and `self.H` are reset. DOMs with missing AHRS pre-calibration data are skipped. Returns ------- dict: key=dom_id, value=tuple: (timestamp, du, f...
[ "def", "calibrate", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "dom_ids", "=", "self", ".", "A", ".", "keys", "(", ")", "print", "(", "\"Calibrating AHRS from median A and H for {} DOMs.\"", ".", "format", "(", "len", "(", "dom_ids",...
Calculate yaw, pitch and roll from the median of A and H. After successful calibration, the `self.A` and `self.H` are reset. DOMs with missing AHRS pre-calibration data are skipped. Returns ------- dict: key=dom_id, value=tuple: (timestamp, du, floor, yaw, pitch, roll)
[ "Calculate", "yaw", "pitch", "and", "roll", "from", "the", "median", "of", "A", "and", "H", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3modules/ahrs.py#L75-L109
train
Calculate yaw pitch and roll from the median of A and H.
NaPs/Kolekto
kolekto/commands/stats.py
humanize_filesize
def humanize_filesize(value): """ Return an humanized file size. """ value = float(value) if value == 1: return '1 Byte' elif value < 1024: return '%d Bytes' % value elif value < 1024: return '%dB' % value for i, s in enumerate(SUFFIXES): unit = 1024 ** (i ...
python
def humanize_filesize(value): """ Return an humanized file size. """ value = float(value) if value == 1: return '1 Byte' elif value < 1024: return '%d Bytes' % value elif value < 1024: return '%dB' % value for i, s in enumerate(SUFFIXES): unit = 1024 ** (i ...
[ "def", "humanize_filesize", "(", "value", ")", ":", "value", "=", "float", "(", "value", ")", "if", "value", "==", "1", ":", "return", "'1 Byte'", "elif", "value", "<", "1024", ":", "return", "'%d Bytes'", "%", "value", "elif", "value", "<", "1024", ":...
Return an humanized file size.
[ "Return", "an", "humanized", "file", "size", "." ]
29c5469da8782780a06bf9a76c59414bb6fd8fe3
https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/commands/stats.py#L14-L31
train
Return a humanized file size.
NaPs/Kolekto
kolekto/commands/stats.py
format_top
def format_top(counter, top=3): """ Format a top. """ items = islice(reversed(sorted(counter.iteritems(), key=lambda x: x[1])), 0, top) return u'; '.join(u'{g} ({nb})'.format(g=g, nb=nb) for g, nb in items)
python
def format_top(counter, top=3): """ Format a top. """ items = islice(reversed(sorted(counter.iteritems(), key=lambda x: x[1])), 0, top) return u'; '.join(u'{g} ({nb})'.format(g=g, nb=nb) for g, nb in items)
[ "def", "format_top", "(", "counter", ",", "top", "=", "3", ")", ":", "items", "=", "islice", "(", "reversed", "(", "sorted", "(", "counter", ".", "iteritems", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")", ")", ",", "0"...
Format a top.
[ "Format", "a", "top", "." ]
29c5469da8782780a06bf9a76c59414bb6fd8fe3
https://github.com/NaPs/Kolekto/blob/29c5469da8782780a06bf9a76c59414bb6fd8fe3/kolekto/commands/stats.py#L34-L38
train
Format a top.
IRC-SPHERE/HyperStream
hyperstream/utils/decorators.py
check_output_format
def check_output_format(expected_formats): """ Decorator for stream outputs that checks the format of the outputs after modifiers have been applied :param expected_formats: The expected output formats :type expected_formats: tuple, set :return: the decorator """ def output_format_decorator(f...
python
def check_output_format(expected_formats): """ Decorator for stream outputs that checks the format of the outputs after modifiers have been applied :param expected_formats: The expected output formats :type expected_formats: tuple, set :return: the decorator """ def output_format_decorator(f...
[ "def", "check_output_format", "(", "expected_formats", ")", ":", "def", "output_format_decorator", "(", "func", ")", ":", "def", "func_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "if", "self", ".", ...
Decorator for stream outputs that checks the format of the outputs after modifiers have been applied :param expected_formats: The expected output formats :type expected_formats: tuple, set :return: the decorator
[ "Decorator", "for", "stream", "outputs", "that", "checks", "the", "format", "of", "the", "outputs", "after", "modifiers", "have", "been", "applied", ":", "param", "expected_formats", ":", "The", "expected", "output", "formats", ":", "type", "expected_formats", "...
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/decorators.py#L37-L51
train
Decorator for stream outputs that checks the format of the outputs after modifiers have been applied.
IRC-SPHERE/HyperStream
hyperstream/utils/decorators.py
check_tool_defined
def check_tool_defined(func): """ Decorator to check whether a tool stream has been defined before execution :return: the decorator """ def func_wrapper(*args): self = args[0] # Deferred import to avoid circular dependency from ..channels import ToolChannel if isinsta...
python
def check_tool_defined(func): """ Decorator to check whether a tool stream has been defined before execution :return: the decorator """ def func_wrapper(*args): self = args[0] # Deferred import to avoid circular dependency from ..channels import ToolChannel if isinsta...
[ "def", "check_tool_defined", "(", "func", ")", ":", "def", "func_wrapper", "(", "*", "args", ")", ":", "self", "=", "args", "[", "0", "]", "# Deferred import to avoid circular dependency", "from", ".", ".", "channels", "import", "ToolChannel", "if", "isinstance"...
Decorator to check whether a tool stream has been defined before execution :return: the decorator
[ "Decorator", "to", "check", "whether", "a", "tool", "stream", "has", "been", "defined", "before", "execution", ":", "return", ":", "the", "decorator" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/decorators.py#L54-L66
train
Decorator to check whether a tool stream has been defined before execution
IRC-SPHERE/HyperStream
hyperstream/utils/decorators.py
check_input_stream_count
def check_input_stream_count(expected_number_of_streams): """ Decorator for Tool._execute that checks the number of input streams :param expected_number_of_streams: The expected number of streams :return: the decorator """ def stream_count_decorator(func): def func_wrapper(*args, **kwa...
python
def check_input_stream_count(expected_number_of_streams): """ Decorator for Tool._execute that checks the number of input streams :param expected_number_of_streams: The expected number of streams :return: the decorator """ def stream_count_decorator(func): def func_wrapper(*args, **kwa...
[ "def", "check_input_stream_count", "(", "expected_number_of_streams", ")", ":", "def", "stream_count_decorator", "(", "func", ")", ":", "def", "func_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", "=", "args", "[", "0", "]", "sources",...
Decorator for Tool._execute that checks the number of input streams :param expected_number_of_streams: The expected number of streams :return: the decorator
[ "Decorator", "for", "Tool", ".", "_execute", "that", "checks", "the", "number", "of", "input", "streams" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/decorators.py#L69-L93
train
Decorator for Tool. _execute that checks the number of input streams
tamasgal/km3pipe
km3pipe/utils/ligiermirror.py
main
def main(): """The main script""" from docopt import docopt args = docopt(__doc__, version=kp.version) kp.logger.set_level("km3pipe", args['-d']) pipe = kp.Pipeline() pipe.attach( kp.io.ch.CHPump, host=args['SOURCE_IP'], port=int(args['-p']), tags=args['-m'], ...
python
def main(): """The main script""" from docopt import docopt args = docopt(__doc__, version=kp.version) kp.logger.set_level("km3pipe", args['-d']) pipe = kp.Pipeline() pipe.attach( kp.io.ch.CHPump, host=args['SOURCE_IP'], port=int(args['-p']), tags=args['-m'], ...
[ "def", "main", "(", ")", ":", "from", "docopt", "import", "docopt", "args", "=", "docopt", "(", "__doc__", ",", "version", "=", "kp", ".", "version", ")", "kp", ".", "logger", ".", "set_level", "(", "\"km3pipe\"", ",", "args", "[", "'-d'", "]", ")", ...
The main script
[ "The", "main", "script" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/utils/ligiermirror.py#L44-L61
train
The main script
nsfmc/swatch
swatch/__init__.py
parse
def parse(filename): """parses a .ase file and returns a list of colors and color groups `swatch.parse` reads in an ase file and converts it to a list of colors and palettes. colors are simple dicts of the form ```json { 'name': u'color name', 'type': u'Process', 'data': { ...
python
def parse(filename): """parses a .ase file and returns a list of colors and color groups `swatch.parse` reads in an ase file and converts it to a list of colors and palettes. colors are simple dicts of the form ```json { 'name': u'color name', 'type': u'Process', 'data': { ...
[ "def", "parse", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "data", ":", "header", ",", "v_major", ",", "v_minor", ",", "chunk_count", "=", "struct", ".", "unpack", "(", "\"!4sHHI\"", ",", "data", ".", "read", ...
parses a .ase file and returns a list of colors and color groups `swatch.parse` reads in an ase file and converts it to a list of colors and palettes. colors are simple dicts of the form ```json { 'name': u'color name', 'type': u'Process', 'data': { 'mode': u'RGB', ...
[ "parses", "a", ".", "ase", "file", "and", "returns", "a", "list", "of", "colors", "and", "color", "groups" ]
8654edf4f1aeef37d42211ff3fe6a3e9e4325859
https://github.com/nsfmc/swatch/blob/8654edf4f1aeef37d42211ff3fe6a3e9e4325859/swatch/__init__.py#L27-L106
train
parses a. ase file and returns a list of colors and color groups and palettes
nsfmc/swatch
swatch/__init__.py
dumps
def dumps(obj): """converts a swatch to bytes suitable for writing""" header = b'ASEF' v_major, v_minor = 1, 0 chunk_count = writer.chunk_count(obj) head = struct.pack('!4sHHI', header, v_major, v_minor, chunk_count) body = b''.join([writer.chunk_for_object(c) for c in obj]) return head + b...
python
def dumps(obj): """converts a swatch to bytes suitable for writing""" header = b'ASEF' v_major, v_minor = 1, 0 chunk_count = writer.chunk_count(obj) head = struct.pack('!4sHHI', header, v_major, v_minor, chunk_count) body = b''.join([writer.chunk_for_object(c) for c in obj]) return head + b...
[ "def", "dumps", "(", "obj", ")", ":", "header", "=", "b'ASEF'", "v_major", ",", "v_minor", "=", "1", ",", "0", "chunk_count", "=", "writer", ".", "chunk_count", "(", "obj", ")", "head", "=", "struct", ".", "pack", "(", "'!4sHHI'", ",", "header", ",",...
converts a swatch to bytes suitable for writing
[ "converts", "a", "swatch", "to", "bytes", "suitable", "for", "writing" ]
8654edf4f1aeef37d42211ff3fe6a3e9e4325859
https://github.com/nsfmc/swatch/blob/8654edf4f1aeef37d42211ff3fe6a3e9e4325859/swatch/__init__.py#L108-L116
train
converts a swatch to bytes suitable for writing
PrefPy/prefpy
prefpy/preference.py
Preference.isFullPreferenceOrder
def isFullPreferenceOrder(self, candList): """ Returns True if the underlying weighted majority graph contains a comparision between every pair of candidate and returns False otherwise. :ivar list<int> candList: Contains integer representations of each candidate. """ # ...
python
def isFullPreferenceOrder(self, candList): """ Returns True if the underlying weighted majority graph contains a comparision between every pair of candidate and returns False otherwise. :ivar list<int> candList: Contains integer representations of each candidate. """ # ...
[ "def", "isFullPreferenceOrder", "(", "self", ",", "candList", ")", ":", "# If a candidate is missing from the wmgMap or if there is a pair of candidates for which ", "# there is no value in the wmgMap, then the wmgMap cannot be a full preference order.", "for", "cand1", "in", "candList", ...
Returns True if the underlying weighted majority graph contains a comparision between every pair of candidate and returns False otherwise. :ivar list<int> candList: Contains integer representations of each candidate.
[ "Returns", "True", "if", "the", "underlying", "weighted", "majority", "graph", "contains", "a", "comparision", "between", "every", "pair", "of", "candidate", "and", "returns", "False", "otherwise", "." ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/preference.py#L21-L39
train
Returns True if the underlying weighted majority graph contains a comparision between every pair of candidate and returns False otherwise.
PrefPy/prefpy
prefpy/preference.py
Preference.containsTie
def containsTie(self): """ Returns True if the underlying weighted majority graph contains a tie between any pair of candidates and returns False otherwise. """ # If a value of 0 is present in the wmgMap, we assume that it represents a tie. for cand in self.wmgMap.keys()...
python
def containsTie(self): """ Returns True if the underlying weighted majority graph contains a tie between any pair of candidates and returns False otherwise. """ # If a value of 0 is present in the wmgMap, we assume that it represents a tie. for cand in self.wmgMap.keys()...
[ "def", "containsTie", "(", "self", ")", ":", "# If a value of 0 is present in the wmgMap, we assume that it represents a tie.", "for", "cand", "in", "self", ".", "wmgMap", ".", "keys", "(", ")", ":", "if", "0", "in", "self", ".", "wmgMap", "[", "cand", "]", ".",...
Returns True if the underlying weighted majority graph contains a tie between any pair of candidates and returns False otherwise.
[ "Returns", "True", "if", "the", "underlying", "weighted", "majority", "graph", "contains", "a", "tie", "between", "any", "pair", "of", "candidates", "and", "returns", "False", "otherwise", "." ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/preference.py#L41-L51
train
Returns True if the underlying weighted majority graph contains a tie between any pair of candidates and returns False otherwise.
PrefPy/prefpy
prefpy/preference.py
Preference.getIncEdgesMap
def getIncEdgesMap(self): """ Returns a dictionary that associates numbers of incoming edges in the weighted majority graph with the candidates that have that number of incoming edges. """ # We calculate the number of incoming edges for each candidate and store it into a diction...
python
def getIncEdgesMap(self): """ Returns a dictionary that associates numbers of incoming edges in the weighted majority graph with the candidates that have that number of incoming edges. """ # We calculate the number of incoming edges for each candidate and store it into a diction...
[ "def", "getIncEdgesMap", "(", "self", ")", ":", "# We calculate the number of incoming edges for each candidate and store it into a dictionary ", "# that associates the number of incoming edges with the candidates with that number.", "incEdgesMap", "=", "dict", "(", ")", "for", "cand1", ...
Returns a dictionary that associates numbers of incoming edges in the weighted majority graph with the candidates that have that number of incoming edges.
[ "Returns", "a", "dictionary", "that", "associates", "numbers", "of", "incoming", "edges", "in", "the", "weighted", "majority", "graph", "with", "the", "candidates", "that", "have", "that", "number", "of", "incoming", "edges", "." ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/preference.py#L53-L74
train
Returns a dictionary that associates numbers of incoming edges with the number of incoming edges in the weighted majority graph with the candidates that have that number of incoming edges.
PrefPy/prefpy
prefpy/preference.py
Preference.getRankMap
def getRankMap(self): """ Returns a dictionary that associates the integer representation of each candidate with its position in the ranking, starting from 1. """ # We sort the candidates based on the number of incoming edges they have in the graph. If # two candidates ...
python
def getRankMap(self): """ Returns a dictionary that associates the integer representation of each candidate with its position in the ranking, starting from 1. """ # We sort the candidates based on the number of incoming edges they have in the graph. If # two candidates ...
[ "def", "getRankMap", "(", "self", ")", ":", "# We sort the candidates based on the number of incoming edges they have in the graph. If ", "# two candidates have the same number, we assume that they are tied.", "incEdgesMap", "=", "self", ".", "getIncEdgesMap", "(", ")", "sortedKeys", ...
Returns a dictionary that associates the integer representation of each candidate with its position in the ranking, starting from 1.
[ "Returns", "a", "dictionary", "that", "associates", "the", "integer", "representation", "of", "each", "candidate", "with", "its", "position", "in", "the", "ranking", "starting", "from", "1", "." ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/preference.py#L76-L93
train
Returns a dictionary that associates the integer representation of each candidate with its position in the ranking starting from 1.
PrefPy/prefpy
prefpy/preference.py
Preference.getReverseRankMap
def getReverseRankMap(self): """ Returns a dictionary that associates each position in the ranking with a list of integer representations of the candidates ranked at that position. """ # We sort the candidates based on the number of incoming edges they have in the graph...
python
def getReverseRankMap(self): """ Returns a dictionary that associates each position in the ranking with a list of integer representations of the candidates ranked at that position. """ # We sort the candidates based on the number of incoming edges they have in the graph...
[ "def", "getReverseRankMap", "(", "self", ")", ":", "# We sort the candidates based on the number of incoming edges they have in the graph. If ", "# two candidates have the same number, we assume that they are tied.", "incEdgesMap", "=", "self", ".", "getIncEdgesMap", "(", ")", "sortedK...
Returns a dictionary that associates each position in the ranking with a list of integer representations of the candidates ranked at that position.
[ "Returns", "a", "dictionary", "that", "associates", "each", "position", "in", "the", "ranking", "with", "a", "list", "of", "integer", "representations", "of", "the", "candidates", "ranked", "at", "that", "position", "." ]
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/preference.py#L95-L111
train
Returns a dictionary that associates each position in the ranking with a list of integer representations of the candidates ranked at that position.
PrefPy/prefpy
prefpy/preference.py
Preference.getOrderVector
def getOrderVector(self): """ Returns a list of lists. Each list represents tiers of candidates. candidates in earlier tiers are preferred to candidates appearing in later tiers. Candidates in the same tier are preferred equally. """ # We sort the candidates based on th...
python
def getOrderVector(self): """ Returns a list of lists. Each list represents tiers of candidates. candidates in earlier tiers are preferred to candidates appearing in later tiers. Candidates in the same tier are preferred equally. """ # We sort the candidates based on th...
[ "def", "getOrderVector", "(", "self", ")", ":", "# We sort the candidates based on the number of incoming edges they have in the graph. If ", "# two candidates have the same number, we assume that they are tied.", "incEdgesMap", "=", "self", ".", "getIncEdgesMap", "(", ")", "sortedKeys...
Returns a list of lists. Each list represents tiers of candidates. candidates in earlier tiers are preferred to candidates appearing in later tiers. Candidates in the same tier are preferred equally.
[ "Returns", "a", "list", "of", "lists", ".", "Each", "list", "represents", "tiers", "of", "candidates", ".", "candidates", "in", "earlier", "tiers", "are", "preferred", "to", "candidates", "appearing", "in", "later", "tiers", ".", "Candidates", "in", "the", "...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/preference.py#L113-L137
train
Returns a list of lists. Each list represents tiers of candidates.
PrefPy/prefpy
prefpy/preference.py
Preference.getOrderVectorEGMM
def getOrderVectorEGMM(self): """ Returns a list of lists. Each list represents tiers of candidates. candidates in earlier tiers are preferred to candidates appearing in later tiers. Candidates in the same tier are preferred equally. """ # We sort the candidates based o...
python
def getOrderVectorEGMM(self): """ Returns a list of lists. Each list represents tiers of candidates. candidates in earlier tiers are preferred to candidates appearing in later tiers. Candidates in the same tier are preferred equally. """ # We sort the candidates based o...
[ "def", "getOrderVectorEGMM", "(", "self", ")", ":", "# We sort the candidates based on the number of incoming edges they have in the graph. If ", "# two candidates have the same number, we assume that they are tied.", "incEdgesMap", "=", "self", ".", "getIncEdgesMap", "(", ")", "sorted...
Returns a list of lists. Each list represents tiers of candidates. candidates in earlier tiers are preferred to candidates appearing in later tiers. Candidates in the same tier are preferred equally.
[ "Returns", "a", "list", "of", "lists", ".", "Each", "list", "represents", "tiers", "of", "candidates", ".", "candidates", "in", "earlier", "tiers", "are", "preferred", "to", "candidates", "appearing", "in", "later", "tiers", ".", "Candidates", "in", "the", "...
f395ba3782f05684fa5de0cece387a6da9391d02
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/preference.py#L139-L163
train
Returns a list of lists that represents tiers of candidates in the same tier.
IRC-SPHERE/HyperStream
hyperstream/utils/statistics/histogram.py
diff
def diff(a, n=1): """ Calculate the n-th discrete difference along given axis. The first difference is given by ``out[n] = a[n+1] - a[n]`` along the given axis, higher differences are calculated by using `diff` recursively. :param a: The list to calculate the diff on :param n: The order of ...
python
def diff(a, n=1): """ Calculate the n-th discrete difference along given axis. The first difference is given by ``out[n] = a[n+1] - a[n]`` along the given axis, higher differences are calculated by using `diff` recursively. :param a: The list to calculate the diff on :param n: The order of ...
[ "def", "diff", "(", "a", ",", "n", "=", "1", ")", ":", "if", "n", "==", "0", ":", "return", "a", "if", "n", "<", "0", ":", "raise", "ValueError", "(", "\"order must be non-negative but got \"", "+", "repr", "(", "n", ")", ")", "b", "=", "map", "(...
Calculate the n-th discrete difference along given axis. The first difference is given by ``out[n] = a[n+1] - a[n]`` along the given axis, higher differences are calculated by using `diff` recursively. :param a: The list to calculate the diff on :param n: The order of the difference :type a: li...
[ "Calculate", "the", "n", "-", "th", "discrete", "difference", "along", "given", "axis", ".", "The", "first", "difference", "is", "given", "by", "out", "[", "n", "]", "=", "a", "[", "n", "+", "1", "]", "-", "a", "[", "n", "]", "along", "the", "giv...
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/statistics/histogram.py#L30-L52
train
Calculate the n - th discrete difference along a given axis.
IRC-SPHERE/HyperStream
hyperstream/utils/statistics/histogram.py
histogram
def histogram(a, bins): """ Compute the histogram of a set of data. :param a: Input data :param bins: int or sequence of scalars or str, optional :type a: list | tuple :type bins: int | list[int] | list[str] :return: """ if any(map(lambda x: x < 0, diff(bins))): raise ValueE...
python
def histogram(a, bins): """ Compute the histogram of a set of data. :param a: Input data :param bins: int or sequence of scalars or str, optional :type a: list | tuple :type bins: int | list[int] | list[str] :return: """ if any(map(lambda x: x < 0, diff(bins))): raise ValueE...
[ "def", "histogram", "(", "a", ",", "bins", ")", ":", "if", "any", "(", "map", "(", "lambda", "x", ":", "x", "<", "0", ",", "diff", "(", "bins", ")", ")", ")", ":", "raise", "ValueError", "(", "'bins must increase monotonically.'", ")", "try", ":", ...
Compute the histogram of a set of data. :param a: Input data :param bins: int or sequence of scalars or str, optional :type a: list | tuple :type bins: int | list[int] | list[str] :return:
[ "Compute", "the", "histogram", "of", "a", "set", "of", "data", "." ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/statistics/histogram.py#L68-L115
train
Compute the histogram of a set of data.
tamasgal/km3pipe
km3pipe/logger.py
deprecation
def deprecation(self, message, *args, **kws): """Show a deprecation warning.""" self._log(DEPRECATION, message, args, **kws)
python
def deprecation(self, message, *args, **kws): """Show a deprecation warning.""" self._log(DEPRECATION, message, args, **kws)
[ "def", "deprecation", "(", "self", ",", "message", ",", "*", "args", ",", "*", "*", "kws", ")", ":", "self", ".", "_log", "(", "DEPRECATION", ",", "message", ",", "args", ",", "*", "*", "kws", ")" ]
Show a deprecation warning.
[ "Show", "a", "deprecation", "warning", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/logger.py#L33-L35
train
Show a deprecation warning.
tamasgal/km3pipe
km3pipe/logger.py
once
def once(self, message, *args, **kws): """Show a message only once, determined by position in source or identifer. This will not work in IPython or Jupyter notebooks if no identifier is specified, since then the determined position in source contains the execution number of the input (cell), which chan...
python
def once(self, message, *args, **kws): """Show a message only once, determined by position in source or identifer. This will not work in IPython or Jupyter notebooks if no identifier is specified, since then the determined position in source contains the execution number of the input (cell), which chan...
[ "def", "once", "(", "self", ",", "message", ",", "*", "args", ",", "*", "*", "kws", ")", ":", "# TODO: after py2 support drop, put this into", "# function signature: identifier=None (between *args and **kws)", "identifier", "=", "kws", ".", "pop", "(", "'identifier'", ...
Show a message only once, determined by position in source or identifer. This will not work in IPython or Jupyter notebooks if no identifier is specified, since then the determined position in source contains the execution number of the input (cell), which changes every time. Set a unique identifier, o...
[ "Show", "a", "message", "only", "once", "determined", "by", "position", "in", "source", "or", "identifer", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/logger.py#L38-L59
train
Show a message only once determined by position in source or identifer.
tamasgal/km3pipe
km3pipe/logger.py
get_logger
def get_logger(name): """Helper function to get a logger""" if name in loggers: return loggers[name] logger = logging.getLogger(name) logger.propagate = False pre1, suf1 = hash_coloured_escapes(name) if supports_color() else ('', '') pre2, suf2 = hash_coloured_escapes(name + 'salt') \ ...
python
def get_logger(name): """Helper function to get a logger""" if name in loggers: return loggers[name] logger = logging.getLogger(name) logger.propagate = False pre1, suf1 = hash_coloured_escapes(name) if supports_color() else ('', '') pre2, suf2 = hash_coloured_escapes(name + 'salt') \ ...
[ "def", "get_logger", "(", "name", ")", ":", "if", "name", "in", "loggers", ":", "return", "loggers", "[", "name", "]", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "logger", ".", "propagate", "=", "False", "pre1", ",", "suf1", "=", "...
Helper function to get a logger
[ "Helper", "function", "to", "get", "a", "logger" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/logger.py#L119-L139
train
Helper function to get a logger
tamasgal/km3pipe
km3pipe/logger.py
get_printer
def get_printer(name, color=None, ansi_code=None, force_color=False): """Return a function which prints a message with a coloured name prefix""" if force_color or supports_color(): if color is None and ansi_code is None: cpre_1, csuf_1 = hash_coloured_escapes(name) cpre_2, csuf_...
python
def get_printer(name, color=None, ansi_code=None, force_color=False): """Return a function which prints a message with a coloured name prefix""" if force_color or supports_color(): if color is None and ansi_code is None: cpre_1, csuf_1 = hash_coloured_escapes(name) cpre_2, csuf_...
[ "def", "get_printer", "(", "name", ",", "color", "=", "None", ",", "ansi_code", "=", "None", ",", "force_color", "=", "False", ")", ":", "if", "force_color", "or", "supports_color", "(", ")", ":", "if", "color", "is", "None", "and", "ansi_code", "is", ...
Return a function which prints a message with a coloured name prefix
[ "Return", "a", "function", "which", "prints", "a", "message", "with", "a", "coloured", "name", "prefix" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/logger.py#L152-L168
train
Return a function which prints a message with a coloured name prefix
tamasgal/km3pipe
km3pipe/logger.py
hash_coloured
def hash_coloured(text): """Return a ANSI coloured text based on its hash""" ansi_code = int(sha256(text.encode('utf-8')).hexdigest(), 16) % 230 return colored(text, ansi_code=ansi_code)
python
def hash_coloured(text): """Return a ANSI coloured text based on its hash""" ansi_code = int(sha256(text.encode('utf-8')).hexdigest(), 16) % 230 return colored(text, ansi_code=ansi_code)
[ "def", "hash_coloured", "(", "text", ")", ":", "ansi_code", "=", "int", "(", "sha256", "(", "text", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", ",", "16", ")", "%", "230", "return", "colored", "(", "text", ",", "ansi_code", ...
Return a ANSI coloured text based on its hash
[ "Return", "a", "ANSI", "coloured", "text", "based", "on", "its", "hash" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/logger.py#L171-L174
train
Return a ANSI coloured text based on its hash
tamasgal/km3pipe
km3pipe/logger.py
hash_coloured_escapes
def hash_coloured_escapes(text): """Return the ANSI hash colour prefix and suffix for a given text""" ansi_code = int(sha256(text.encode('utf-8')).hexdigest(), 16) % 230 prefix, suffix = colored('SPLIT', ansi_code=ansi_code).split('SPLIT') return prefix, suffix
python
def hash_coloured_escapes(text): """Return the ANSI hash colour prefix and suffix for a given text""" ansi_code = int(sha256(text.encode('utf-8')).hexdigest(), 16) % 230 prefix, suffix = colored('SPLIT', ansi_code=ansi_code).split('SPLIT') return prefix, suffix
[ "def", "hash_coloured_escapes", "(", "text", ")", ":", "ansi_code", "=", "int", "(", "sha256", "(", "text", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", ",", "16", ")", "%", "230", "prefix", ",", "suffix", "=", "colored", "(",...
Return the ANSI hash colour prefix and suffix for a given text
[ "Return", "the", "ANSI", "hash", "colour", "prefix", "and", "suffix", "for", "a", "given", "text" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/logger.py#L177-L181
train
Return the ANSI hash colour prefix and suffix for a given text
tamasgal/km3pipe
km3pipe/time.py
tai_timestamp
def tai_timestamp(): """Return current TAI timestamp.""" timestamp = time.time() date = datetime.utcfromtimestamp(timestamp) if date.year < 1972: return timestamp offset = 10 + timestamp leap_seconds = [ (1972, 1, 1), (1972, 7, 1), (1973, 1, 1), (1974, 1, ...
python
def tai_timestamp(): """Return current TAI timestamp.""" timestamp = time.time() date = datetime.utcfromtimestamp(timestamp) if date.year < 1972: return timestamp offset = 10 + timestamp leap_seconds = [ (1972, 1, 1), (1972, 7, 1), (1973, 1, 1), (1974, 1, ...
[ "def", "tai_timestamp", "(", ")", ":", "timestamp", "=", "time", ".", "time", "(", ")", "date", "=", "datetime", ".", "utcfromtimestamp", "(", "timestamp", ")", "if", "date", ".", "year", "<", "1972", ":", "return", "timestamp", "offset", "=", "10", "+...
Return current TAI timestamp.
[ "Return", "current", "TAI", "timestamp", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/time.py#L102-L142
train
Return current TAI timestamp.
tamasgal/km3pipe
km3pipe/time.py
np_to_datetime
def np_to_datetime(intime): """Convert numpy/pandas datetime64 to list[datetime].""" nptime = np.atleast_1d(intime) np_corr = (nptime - np.datetime64('1970-01-01T00:00:00')) / \ np.timedelta64(1, 's') return [datetime.utcfromtimestamp(t) for t in np_corr]
python
def np_to_datetime(intime): """Convert numpy/pandas datetime64 to list[datetime].""" nptime = np.atleast_1d(intime) np_corr = (nptime - np.datetime64('1970-01-01T00:00:00')) / \ np.timedelta64(1, 's') return [datetime.utcfromtimestamp(t) for t in np_corr]
[ "def", "np_to_datetime", "(", "intime", ")", ":", "nptime", "=", "np", ".", "atleast_1d", "(", "intime", ")", "np_corr", "=", "(", "nptime", "-", "np", ".", "datetime64", "(", "'1970-01-01T00:00:00'", ")", ")", "/", "np", ".", "timedelta64", "(", "1", ...
Convert numpy/pandas datetime64 to list[datetime].
[ "Convert", "numpy", "/", "pandas", "datetime64", "to", "list", "[", "datetime", "]", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/time.py#L145-L150
train
Convert numpy datetime64 to list[datetime ].
tamasgal/km3pipe
km3pipe/time.py
Cuckoo.msg
def msg(self, *args, **kwargs): "Only execute callback when interval is reached." if self.timestamp is None or self._interval_reached(): self.callback(*args, **kwargs) self.reset()
python
def msg(self, *args, **kwargs): "Only execute callback when interval is reached." if self.timestamp is None or self._interval_reached(): self.callback(*args, **kwargs) self.reset()
[ "def", "msg", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "timestamp", "is", "None", "or", "self", ".", "_interval_reached", "(", ")", ":", "self", ".", "callback", "(", "*", "args", ",", "*", "*", "kwargs...
Only execute callback when interval is reached.
[ "Only", "execute", "callback", "when", "interval", "is", "reached", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/time.py#L83-L87
train
Only execute callback when interval is reached.
thebigmunch/google-music-utils
src/google_music_utils/compare.py
_gather_field_values
def _gather_field_values( item, *, fields=None, field_map=FIELD_MAP, normalize_values=False, normalize_func=normalize_value): """Create a tuple of normalized metadata field values. Parameter: item (~collections.abc.Mapping, str, os.PathLike): Item dict or filepath. fields (list): A list of fields used to compa...
python
def _gather_field_values( item, *, fields=None, field_map=FIELD_MAP, normalize_values=False, normalize_func=normalize_value): """Create a tuple of normalized metadata field values. Parameter: item (~collections.abc.Mapping, str, os.PathLike): Item dict or filepath. fields (list): A list of fields used to compa...
[ "def", "_gather_field_values", "(", "item", ",", "*", ",", "fields", "=", "None", ",", "field_map", "=", "FIELD_MAP", ",", "normalize_values", "=", "False", ",", "normalize_func", "=", "normalize_value", ")", ":", "it", "=", "get_item_tags", "(", "item", ")"...
Create a tuple of normalized metadata field values. Parameter: item (~collections.abc.Mapping, str, os.PathLike): Item dict or filepath. fields (list): A list of fields used to compare item dicts. field_map (~collections.abc.Mapping): A mapping field name aliases. Default: :data:`~google_music_utils.constant...
[ "Create", "a", "tuple", "of", "normalized", "metadata", "field", "values", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/compare.py#L12-L50
train
Create a tuple of normalized metadata field values from the given item dict or filepath.
thebigmunch/google-music-utils
src/google_music_utils/compare.py
find_existing_items
def find_existing_items( src, dst, *, fields=None, field_map=None, normalize_values=False, normalize_func=normalize_value): """Find items from an item collection that are in another item collection. Parameters: src (list): A list of item dicts or filepaths. dst (list): A list of item dicts or filepaths. fiel...
python
def find_existing_items( src, dst, *, fields=None, field_map=None, normalize_values=False, normalize_func=normalize_value): """Find items from an item collection that are in another item collection. Parameters: src (list): A list of item dicts or filepaths. dst (list): A list of item dicts or filepaths. fiel...
[ "def", "find_existing_items", "(", "src", ",", "dst", ",", "*", ",", "fields", "=", "None", ",", "field_map", "=", "None", ",", "normalize_values", "=", "False", ",", "normalize_func", "=", "normalize_value", ")", ":", "if", "field_map", "is", "None", ":",...
Find items from an item collection that are in another item collection. Parameters: src (list): A list of item dicts or filepaths. dst (list): A list of item dicts or filepaths. fields (list): A list of fields used to compare item dicts. field_map (~collections.abc.Mapping): A mapping field name aliases. D...
[ "Find", "items", "from", "an", "item", "collection", "that", "are", "in", "another", "item", "collection", "." ]
2e8873defe7d5aab7321b9d5ec8a80d72687578e
https://github.com/thebigmunch/google-music-utils/blob/2e8873defe7d5aab7321b9d5ec8a80d72687578e/src/google_music_utils/compare.py#L53-L89
train
Find items from an item collection that are in another item collection.
IRC-SPHERE/HyperStream
hyperstream/utils/hyperstream_logger.py
monitor
def monitor(self, message, *args, **kws): """ Define a monitoring logger that will be added to Logger :param self: The logging object :param message: The logging message :param args: Positional arguments :param kws: Keyword arguments :return: """ if self.isEnabledFor(MON): #...
python
def monitor(self, message, *args, **kws): """ Define a monitoring logger that will be added to Logger :param self: The logging object :param message: The logging message :param args: Positional arguments :param kws: Keyword arguments :return: """ if self.isEnabledFor(MON): #...
[ "def", "monitor", "(", "self", ",", "message", ",", "*", "args", ",", "*", "*", "kws", ")", ":", "if", "self", ".", "isEnabledFor", "(", "MON", ")", ":", "# Yes, logger takes its '*args' as 'args'.", "self", ".", "_log", "(", "MON", ",", "message", ",", ...
Define a monitoring logger that will be added to Logger :param self: The logging object :param message: The logging message :param args: Positional arguments :param kws: Keyword arguments :return:
[ "Define", "a", "monitoring", "logger", "that", "will", "be", "added", "to", "Logger" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/hyperstream_logger.py#L160-L172
train
Add a monitoring logger to the base object that will be monitored.
IRC-SPHERE/HyperStream
hyperstream/utils/hyperstream_logger.py
monitor
def monitor(msg, *args, **kwargs): """ Log a message with severity 'MON' on the root logger. """ if len(logging.root.handlers) == 0: logging.basicConfig() logging.root.monitor(msg, *args, **kwargs)
python
def monitor(msg, *args, **kwargs): """ Log a message with severity 'MON' on the root logger. """ if len(logging.root.handlers) == 0: logging.basicConfig() logging.root.monitor(msg, *args, **kwargs)
[ "def", "monitor", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "logging", ".", "root", ".", "handlers", ")", "==", "0", ":", "logging", ".", "basicConfig", "(", ")", "logging", ".", "root", ".", "monitor", "(...
Log a message with severity 'MON' on the root logger.
[ "Log", "a", "message", "with", "severity", "MON", "on", "the", "root", "logger", "." ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/hyperstream_logger.py#L178-L184
train
Log a message with severity MON on the root logger.
IRC-SPHERE/HyperStream
hyperstream/utils/hyperstream_logger.py
SenMLFormatter.format
def format(self, record): """ The formatting function :param record: The record object :return: The string representation of the record """ try: n = record.n except AttributeError: n = 'default' try: message = record....
python
def format(self, record): """ The formatting function :param record: The record object :return: The string representation of the record """ try: n = record.n except AttributeError: n = 'default' try: message = record....
[ "def", "format", "(", "self", ",", "record", ")", ":", "try", ":", "n", "=", "record", ".", "n", "except", "AttributeError", ":", "n", "=", "'default'", "try", ":", "message", "=", "record", ".", "message", "except", "AttributeError", ":", "message", "...
The formatting function :param record: The record object :return: The string representation of the record
[ "The", "formatting", "function" ]
98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780
https://github.com/IRC-SPHERE/HyperStream/blob/98478f4d31ed938f4aa7c958ed0d4c3ffcb2e780/hyperstream/utils/hyperstream_logger.py#L197-L222
train
The formatting function
wtsi-hgi/consul-lock
consullock/managers.py
_exception_converter
def _exception_converter(callable: Callable) -> Callable: """ Decorator that converts exceptions from underlying libraries to native exceptions. :param callable: the callable to convert exceptions of :return: wrapped callable """ def wrapped(*args, **kwargs) -> Any: try: retu...
python
def _exception_converter(callable: Callable) -> Callable: """ Decorator that converts exceptions from underlying libraries to native exceptions. :param callable: the callable to convert exceptions of :return: wrapped callable """ def wrapped(*args, **kwargs) -> Any: try: retu...
[ "def", "_exception_converter", "(", "callable", ":", "Callable", ")", "->", "Callable", ":", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Any", ":", "try", ":", "return", "callable", "(", "*", "args", ",", "*", "*", "kwarg...
Decorator that converts exceptions from underlying libraries to native exceptions. :param callable: the callable to convert exceptions of :return: wrapped callable
[ "Decorator", "that", "converts", "exceptions", "from", "underlying", "libraries", "to", "native", "exceptions", ".", ":", "param", "callable", ":", "the", "callable", "to", "convert", "exceptions", "of", ":", "return", ":", "wrapped", "callable" ]
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L40-L55
train
Decorator that converts exceptions from underlying libraries to native exceptions.
wtsi-hgi/consul-lock
consullock/managers.py
_raise_if_teardown_called
def _raise_if_teardown_called(callable: Callable) -> Callable: """ Decorator that raises an exception if consul lock manager has been torn down. :param callable: the callable to wrap (where `ConsulLock` is always passed as the first argument) :return: wrapped callable """ def wrapper(consul_lock...
python
def _raise_if_teardown_called(callable: Callable) -> Callable: """ Decorator that raises an exception if consul lock manager has been torn down. :param callable: the callable to wrap (where `ConsulLock` is always passed as the first argument) :return: wrapped callable """ def wrapper(consul_lock...
[ "def", "_raise_if_teardown_called", "(", "callable", ":", "Callable", ")", "->", "Callable", ":", "def", "wrapper", "(", "consul_lock", ":", "\"ConsulLockManager\"", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "consul_lock", ".", "_teardown_call...
Decorator that raises an exception if consul lock manager has been torn down. :param callable: the callable to wrap (where `ConsulLock` is always passed as the first argument) :return: wrapped callable
[ "Decorator", "that", "raises", "an", "exception", "if", "consul", "lock", "manager", "has", "been", "torn", "down", ".", ":", "param", "callable", ":", "the", "callable", "to", "wrap", "(", "where", "ConsulLock", "is", "always", "passed", "as", "the", "fir...
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L58-L68
train
Decorator that raises an exception if the consul lock manager has been torn down.
wtsi-hgi/consul-lock
consullock/managers.py
ConsulLockManager.validate_session_ttl
def validate_session_ttl(session_timeout_in_seconds: float): """ Validates the given session timeout, raising a `ValueError` if it is invalid. :param session_timeout_in_seconds: the timeout to validate :raises InvalidSessionTtlValueError: if the timeout is invalid """ if ...
python
def validate_session_ttl(session_timeout_in_seconds: float): """ Validates the given session timeout, raising a `ValueError` if it is invalid. :param session_timeout_in_seconds: the timeout to validate :raises InvalidSessionTtlValueError: if the timeout is invalid """ if ...
[ "def", "validate_session_ttl", "(", "session_timeout_in_seconds", ":", "float", ")", ":", "if", "session_timeout_in_seconds", "<", "MIN_LOCK_TIMEOUT_IN_SECONDS", "or", "session_timeout_in_seconds", ">", "MAX_LOCK_TIMEOUT_IN_SECONDS", ":", "raise", "InvalidSessionTtlValueError", ...
Validates the given session timeout, raising a `ValueError` if it is invalid. :param session_timeout_in_seconds: the timeout to validate :raises InvalidSessionTtlValueError: if the timeout is invalid
[ "Validates", "the", "given", "session", "timeout", "raising", "a", "ValueError", "if", "it", "is", "invalid", ".", ":", "param", "session_timeout_in_seconds", ":", "the", "timeout", "to", "validate", ":", "raises", "InvalidSessionTtlValueError", ":", "if", "the", ...
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L76-L86
train
Validates the given session timeout in seconds.
wtsi-hgi/consul-lock
consullock/managers.py
ConsulLockManager.validate_key
def validate_key(key: str): """ Validates the given key. :param key: the key to validate :raises InvalidKeyError: raised if the given key is invalid """ if "//" in key: raise DoubleSlashKeyError(key) elif normpath(key) != key: raise NonNorm...
python
def validate_key(key: str): """ Validates the given key. :param key: the key to validate :raises InvalidKeyError: raised if the given key is invalid """ if "//" in key: raise DoubleSlashKeyError(key) elif normpath(key) != key: raise NonNorm...
[ "def", "validate_key", "(", "key", ":", "str", ")", ":", "if", "\"//\"", "in", "key", ":", "raise", "DoubleSlashKeyError", "(", "key", ")", "elif", "normpath", "(", "key", ")", "!=", "key", ":", "raise", "NonNormalisedKeyError", "(", "key", ")" ]
Validates the given key. :param key: the key to validate :raises InvalidKeyError: raised if the given key is invalid
[ "Validates", "the", "given", "key", ".", ":", "param", "key", ":", "the", "key", "to", "validate", ":", "raises", "InvalidKeyError", ":", "raised", "if", "the", "given", "key", "is", "invalid" ]
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L89-L98
train
Validates the given key.
wtsi-hgi/consul-lock
consullock/managers.py
ConsulLockManager.acquire
def acquire(self, key: str, blocking: bool=True, timeout: float=None, metadata: Any=None, on_before_lock: LockEventListener=lambda key: None, on_lock_already_locked: LockEventListener=lambda key: None, lock_poll_interval_generator: Callable[[int], float]=DEFAULT_LOCK_POLL...
python
def acquire(self, key: str, blocking: bool=True, timeout: float=None, metadata: Any=None, on_before_lock: LockEventListener=lambda key: None, on_lock_already_locked: LockEventListener=lambda key: None, lock_poll_interval_generator: Callable[[int], float]=DEFAULT_LOCK_POLL...
[ "def", "acquire", "(", "self", ",", "key", ":", "str", ",", "blocking", ":", "bool", "=", "True", ",", "timeout", ":", "float", "=", "None", ",", "metadata", ":", "Any", "=", "None", ",", "on_before_lock", ":", "LockEventListener", "=", "lambda", "key"...
Acquires a Consul lock. :param key: the lock key :param blocking: whether to block and wait for the lock :param timeout: timeout in seconds :param metadata: metadata to add to the lock information. Must be parsable by default JSON encode/decoder :param on_before_lock: event liste...
[ "Acquires", "a", "Consul", "lock", ".", ":", "param", "key", ":", "the", "lock", "key", ":", "param", "blocking", ":", "whether", "to", "block", "and", "wait", "for", "the", "lock", ":", "param", "timeout", ":", "timeout", "in", "seconds", ":", "param"...
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L135-L194
train
Acquires a Consul lock.
wtsi-hgi/consul-lock
consullock/managers.py
ConsulLockManager.execute
def execute(self, key: str, executable: str, *, capture_stdout: bool=False, capture_stderr: bool=False, **acquire_kwargs) -> Tuple[Optional[int], Optional[bytes], Optional[bytes]]: """ Executes the given executable whilst holding the given lock. :param key: :param executa...
python
def execute(self, key: str, executable: str, *, capture_stdout: bool=False, capture_stderr: bool=False, **acquire_kwargs) -> Tuple[Optional[int], Optional[bytes], Optional[bytes]]: """ Executes the given executable whilst holding the given lock. :param key: :param executa...
[ "def", "execute", "(", "self", ",", "key", ":", "str", ",", "executable", ":", "str", ",", "*", ",", "capture_stdout", ":", "bool", "=", "False", ",", "capture_stderr", ":", "bool", "=", "False", ",", "*", "*", "acquire_kwargs", ")", "->", "Tuple", "...
Executes the given executable whilst holding the given lock. :param key: :param executable: :param capture_stdout: :param capture_stderr: :param acquire_kwargs: :return:
[ "Executes", "the", "given", "executable", "whilst", "holding", "the", "given", "lock", ".", ":", "param", "key", ":", ":", "param", "executable", ":", ":", "param", "capture_stdout", ":", ":", "param", "capture_stderr", ":", ":", "param", "acquire_kwargs", "...
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L198-L212
train
Executes the given executable whilst holding the given lock.
wtsi-hgi/consul-lock
consullock/managers.py
ConsulLockManager.execute_with_lock
def execute_with_lock(self, executable: str, lock: ConnectedConsulLockInformation, *, capture_stdout: bool=False, capture_stderr: bool=False) -> Tuple[int, Optional[bytes], Optional[bytes]]: """ TODO :param executable: :param lock: :param capture_stdout:...
python
def execute_with_lock(self, executable: str, lock: ConnectedConsulLockInformation, *, capture_stdout: bool=False, capture_stderr: bool=False) -> Tuple[int, Optional[bytes], Optional[bytes]]: """ TODO :param executable: :param lock: :param capture_stdout:...
[ "def", "execute_with_lock", "(", "self", ",", "executable", ":", "str", ",", "lock", ":", "ConnectedConsulLockInformation", ",", "*", ",", "capture_stdout", ":", "bool", "=", "False", ",", "capture_stderr", ":", "bool", "=", "False", ")", "->", "Tuple", "[",...
TODO :param executable: :param lock: :param capture_stdout: :param capture_stderr: :return:
[ "TODO", ":", "param", "executable", ":", ":", "param", "lock", ":", ":", "param", "capture_stdout", ":", ":", "param", "capture_stderr", ":", ":", "return", ":" ]
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L216-L250
train
Execute a command with a lock.
wtsi-hgi/consul-lock
consullock/managers.py
ConsulLockManager.release
def release(self, key: str) -> Optional[str]: """ Release the lock. Noop if not locked. :param key: the name of the lock to release :return: the name of the released lock, or `None` if no lock was released :raises InvalidKeyError: if the `key` is not valid """ ...
python
def release(self, key: str) -> Optional[str]: """ Release the lock. Noop if not locked. :param key: the name of the lock to release :return: the name of the released lock, or `None` if no lock was released :raises InvalidKeyError: if the `key` is not valid """ ...
[ "def", "release", "(", "self", ",", "key", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "ConsulLockManager", ".", "validate_key", "(", "key", ")", "key_value", "=", "self", ".", "consul_client", ".", "kv", ".", "get", "(", "key", ")", "["...
Release the lock. Noop if not locked. :param key: the name of the lock to release :return: the name of the released lock, or `None` if no lock was released :raises InvalidKeyError: if the `key` is not valid
[ "Release", "the", "lock", "." ]
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L255-L281
train
Release the lock.
wtsi-hgi/consul-lock
consullock/managers.py
ConsulLockManager.release_regex
def release_regex(self, key_regex: str) -> Set[str]: """ Releases all locks with names that that match the given regular expression. :param key_regex: Python regular expression that captures the names of the locks that are to be released :return: the names of the locks that were released...
python
def release_regex(self, key_regex: str) -> Set[str]: """ Releases all locks with names that that match the given regular expression. :param key_regex: Python regular expression that captures the names of the locks that are to be released :return: the names of the locks that were released...
[ "def", "release_regex", "(", "self", ",", "key_regex", ":", "str", ")", "->", "Set", "[", "str", "]", ":", "keys", "=", "list", "(", "self", ".", "find_regex", "(", "key_regex", ")", ".", "keys", "(", ")", ")", "return", "self", ".", "release_all", ...
Releases all locks with names that that match the given regular expression. :param key_regex: Python regular expression that captures the names of the locks that are to be released :return: the names of the locks that were released
[ "Releases", "all", "locks", "with", "names", "that", "that", "match", "the", "given", "regular", "expression", ".", ":", "param", "key_regex", ":", "Python", "regular", "expression", "that", "captures", "the", "names", "of", "the", "locks", "that", "are", "t...
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L285-L292
train
Releases all locks with names that match the given regular expression.
wtsi-hgi/consul-lock
consullock/managers.py
ConsulLockManager.release_all
def release_all(self, keys: Sequence[str]) -> Set[str]: """ Releases all of the given keys. :param keys: the keys to release :return: the names of the keys that were released """ released: List[str] = [] for key in keys: released.append(self.release(ke...
python
def release_all(self, keys: Sequence[str]) -> Set[str]: """ Releases all of the given keys. :param keys: the keys to release :return: the names of the keys that were released """ released: List[str] = [] for key in keys: released.append(self.release(ke...
[ "def", "release_all", "(", "self", ",", "keys", ":", "Sequence", "[", "str", "]", ")", "->", "Set", "[", "str", "]", ":", "released", ":", "List", "[", "str", "]", "=", "[", "]", "for", "key", "in", "keys", ":", "released", ".", "append", "(", ...
Releases all of the given keys. :param keys: the keys to release :return: the names of the keys that were released
[ "Releases", "all", "of", "the", "given", "keys", ".", ":", "param", "keys", ":", "the", "keys", "to", "release", ":", "return", ":", "the", "names", "of", "the", "keys", "that", "were", "released" ]
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L296-L305
train
Releases all of the given keys.
wtsi-hgi/consul-lock
consullock/managers.py
ConsulLockManager.find
def find(self, name: str) -> Optional[ConnectedConsulLockInformation]: """ Finds the lock with the key name that matches that given. :param name: the lock key to match :return: the found lock """ lock = self.consul_client.kv.get(name)[1] if lock is None: ...
python
def find(self, name: str) -> Optional[ConnectedConsulLockInformation]: """ Finds the lock with the key name that matches that given. :param name: the lock key to match :return: the found lock """ lock = self.consul_client.kv.get(name)[1] if lock is None: ...
[ "def", "find", "(", "self", ",", "name", ":", "str", ")", "->", "Optional", "[", "ConnectedConsulLockInformation", "]", ":", "lock", "=", "self", ".", "consul_client", ".", "kv", ".", "get", "(", "name", ")", "[", "1", "]", "if", "lock", "is", "None"...
Finds the lock with the key name that matches that given. :param name: the lock key to match :return: the found lock
[ "Finds", "the", "lock", "with", "the", "key", "name", "that", "matches", "that", "given", ".", ":", "param", "name", ":", "the", "lock", "key", "to", "match", ":", "return", ":", "the", "found", "lock" ]
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L309-L322
train
Finds the lock with the given name that matches that given.
wtsi-hgi/consul-lock
consullock/managers.py
ConsulLockManager.find_regex
def find_regex(self, name_regex: str) -> Dict[str, Optional[ConnectedConsulLockInformation]]: """ Finds the locks with key names that match the given regex. :param name_regex: key name regex :return: keys that match """ # Gets prefix directory (must not include regex!) ...
python
def find_regex(self, name_regex: str) -> Dict[str, Optional[ConnectedConsulLockInformation]]: """ Finds the locks with key names that match the given regex. :param name_regex: key name regex :return: keys that match """ # Gets prefix directory (must not include regex!) ...
[ "def", "find_regex", "(", "self", ",", "name_regex", ":", "str", ")", "->", "Dict", "[", "str", ",", "Optional", "[", "ConnectedConsulLockInformation", "]", "]", ":", "# Gets prefix directory (must not include regex!)", "escaped_name_regex", "=", "re", ".", "escape"...
Finds the locks with key names that match the given regex. :param name_regex: key name regex :return: keys that match
[ "Finds", "the", "locks", "with", "key", "names", "that", "match", "the", "given", "regex", ".", ":", "param", "name_regex", ":", "key", "name", "regex", ":", "return", ":", "keys", "that", "match" ]
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L327-L353
train
Finds the keys that match the given regular expression.
wtsi-hgi/consul-lock
consullock/managers.py
ConsulLockManager.teardown
def teardown(self): """ Tears down the instance, removing any remaining sessions that this instance has created. The instance must not be used after this method has been called. """ with self._teardown_lock: if not self._teardown_called: self._teardow...
python
def teardown(self): """ Tears down the instance, removing any remaining sessions that this instance has created. The instance must not be used after this method has been called. """ with self._teardown_lock: if not self._teardown_called: self._teardow...
[ "def", "teardown", "(", "self", ")", ":", "with", "self", ".", "_teardown_lock", ":", "if", "not", "self", ".", "_teardown_called", ":", "self", ".", "_teardown_called", "=", "True", "if", "len", "(", "self", ".", "_acquiring_session_ids", ")", ">", "0", ...
Tears down the instance, removing any remaining sessions that this instance has created. The instance must not be used after this method has been called.
[ "Tears", "down", "the", "instance", "removing", "any", "remaining", "sessions", "that", "this", "instance", "has", "created", "." ]
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L356-L375
train
Tear down the instance removing any remaining sessions that have not been acquired.
wtsi-hgi/consul-lock
consullock/managers.py
ConsulLockManager._acquire_lock
def _acquire_lock(self, key: str, session_id: str, seconds_to_lock: float, metadata: Any) \ -> Optional[ConnectedConsulLockInformation]: """ Attempts to get the lock using the given session. :param key: name of the lock :param session_id: the identifier of the Consul session ...
python
def _acquire_lock(self, key: str, session_id: str, seconds_to_lock: float, metadata: Any) \ -> Optional[ConnectedConsulLockInformation]: """ Attempts to get the lock using the given session. :param key: name of the lock :param session_id: the identifier of the Consul session ...
[ "def", "_acquire_lock", "(", "self", ",", "key", ":", "str", ",", "session_id", ":", "str", ",", "seconds_to_lock", ":", "float", ",", "metadata", ":", "Any", ")", "->", "Optional", "[", "ConnectedConsulLockInformation", "]", ":", "lock_information", "=", "C...
Attempts to get the lock using the given session. :param key: name of the lock :param session_id: the identifier of the Consul session that should try to hold the lock :param seconds_to_lock: the number of seconds it took to acquire the lock :param metadata: metadata to add to the lock i...
[ "Attempts", "to", "get", "the", "lock", "using", "the", "given", "session", ".", ":", "param", "key", ":", "name", "of", "the", "lock", ":", "param", "session_id", ":", "the", "identifier", "of", "the", "Consul", "session", "that", "should", "try", "to",...
deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2
https://github.com/wtsi-hgi/consul-lock/blob/deb07ab41dabbb49f4d0bbc062bc3b4b6e5d71b2/consullock/managers.py#L377-L398
train
Attempts to get the lock using the given session.
materials-data-facility/toolbox
mdf_toolbox/sub_helpers.py
AggregateHelper._aggregate
def _aggregate(self, scroll_field, scroll_size=SEARCH_LIMIT): """Perform an advanced query, and return *all* matching results. Will automatically perform multiple queries in order to retrieve all results. Note: All ``aggregate`` queries run in advanced mode. Arguments: scro...
python
def _aggregate(self, scroll_field, scroll_size=SEARCH_LIMIT): """Perform an advanced query, and return *all* matching results. Will automatically perform multiple queries in order to retrieve all results. Note: All ``aggregate`` queries run in advanced mode. Arguments: scro...
[ "def", "_aggregate", "(", "self", ",", "scroll_field", ",", "scroll_size", "=", "SEARCH_LIMIT", ")", ":", "# Make sure scroll_field is valid", "if", "not", "scroll_field", ":", "raise", "AttributeError", "(", "\"scroll_field is required.\"", ")", "# Make sure the query is...
Perform an advanced query, and return *all* matching results. Will automatically perform multiple queries in order to retrieve all results. Note: All ``aggregate`` queries run in advanced mode. Arguments: scroll_field (str): The field on which to scroll. This should be a field ...
[ "Perform", "an", "advanced", "query", "and", "return", "*", "all", "*", "matching", "results", ".", "Will", "automatically", "perform", "multiple", "queries", "in", "order", "to", "retrieve", "all", "results", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/sub_helpers.py#L23-L97
train
Perform an advanced query and return all matching entries.
materials-data-facility/toolbox
mdf_toolbox/sub_helpers.py
AggregateHelper.aggregate
def aggregate(self, q=None, scroll_size=SEARCH_LIMIT, reset_query=True, **kwargs): """Perform an advanced query, and return *all* matching results. Will automatically perform multiple queries in order to retrieve all results. Note: All ``aggregate`` queries run in advanced mode, and...
python
def aggregate(self, q=None, scroll_size=SEARCH_LIMIT, reset_query=True, **kwargs): """Perform an advanced query, and return *all* matching results. Will automatically perform multiple queries in order to retrieve all results. Note: All ``aggregate`` queries run in advanced mode, and...
[ "def", "aggregate", "(", "self", ",", "q", "=", "None", ",", "scroll_size", "=", "SEARCH_LIMIT", ",", "reset_query", "=", "True", ",", "*", "*", "kwargs", ")", ":", "scroll_field", "=", "kwargs", ".", "get", "(", "\"scroll_field\"", ",", "self", ".", "...
Perform an advanced query, and return *all* matching results. Will automatically perform multiple queries in order to retrieve all results. Note: All ``aggregate`` queries run in advanced mode, and ``info`` is not available. Arguments: q (str): The query to execute. **D...
[ "Perform", "an", "advanced", "query", "and", "return", "*", "all", "*", "matching", "results", ".", "Will", "automatically", "perform", "multiple", "queries", "in", "order", "to", "retrieve", "all", "results", "." ]
2a4ac2b6a892238263008efa6a5f3923d9a83505
https://github.com/materials-data-facility/toolbox/blob/2a4ac2b6a892238263008efa6a5f3923d9a83505/mdf_toolbox/sub_helpers.py#L99-L140
train
Perform an aggregate query and return all matching results.
tamasgal/km3pipe
km3pipe/db.py
we_are_in_lyon
def we_are_in_lyon(): """Check if we are on a Lyon machine""" import socket try: hostname = socket.gethostname() ip = socket.gethostbyname(hostname) except socket.gaierror: return False return ip.startswith("134.158.")
python
def we_are_in_lyon(): """Check if we are on a Lyon machine""" import socket try: hostname = socket.gethostname() ip = socket.gethostbyname(hostname) except socket.gaierror: return False return ip.startswith("134.158.")
[ "def", "we_are_in_lyon", "(", ")", ":", "import", "socket", "try", ":", "hostname", "=", "socket", ".", "gethostname", "(", ")", "ip", "=", "socket", ".", "gethostbyname", "(", "hostname", ")", "except", "socket", ".", "gaierror", ":", "return", "False", ...
Check if we are on a Lyon machine
[ "Check", "if", "we", "are", "on", "a", "Lyon", "machine" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L62-L70
train
Check if we are on a Lyon machine
tamasgal/km3pipe
km3pipe/db.py
read_csv
def read_csv(text, sep="\t"): """Create a DataFrame from CSV text""" import pandas as pd # no top level load to make a faster import of db return pd.read_csv(StringIO(text), sep="\t")
python
def read_csv(text, sep="\t"): """Create a DataFrame from CSV text""" import pandas as pd # no top level load to make a faster import of db return pd.read_csv(StringIO(text), sep="\t")
[ "def", "read_csv", "(", "text", ",", "sep", "=", "\"\\t\"", ")", ":", "import", "pandas", "as", "pd", "# no top level load to make a faster import of db", "return", "pd", ".", "read_csv", "(", "StringIO", "(", "text", ")", ",", "sep", "=", "\"\\t\"", ")" ]
Create a DataFrame from CSV text
[ "Create", "a", "DataFrame", "from", "CSV", "text" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L73-L76
train
Create a DataFrame from CSV text
tamasgal/km3pipe
km3pipe/db.py
add_datetime
def add_datetime(dataframe, timestamp_key='UNIXTIME'): """Add an additional DATETIME column with standar datetime format. This currently manipulates the incoming DataFrame! """ def convert_data(timestamp): return datetime.fromtimestamp(float(timestamp) / 1e3, UTC_TZ) try: log.debu...
python
def add_datetime(dataframe, timestamp_key='UNIXTIME'): """Add an additional DATETIME column with standar datetime format. This currently manipulates the incoming DataFrame! """ def convert_data(timestamp): return datetime.fromtimestamp(float(timestamp) / 1e3, UTC_TZ) try: log.debu...
[ "def", "add_datetime", "(", "dataframe", ",", "timestamp_key", "=", "'UNIXTIME'", ")", ":", "def", "convert_data", "(", "timestamp", ")", ":", "return", "datetime", ".", "fromtimestamp", "(", "float", "(", "timestamp", ")", "/", "1e3", ",", "UTC_TZ", ")", ...
Add an additional DATETIME column with standar datetime format. This currently manipulates the incoming DataFrame!
[ "Add", "an", "additional", "DATETIME", "column", "with", "standar", "datetime", "format", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L488-L502
train
Add an additional DATETIME column with standar datetime format.
tamasgal/km3pipe
km3pipe/db.py
show_ahrs_calibration
def show_ahrs_calibration(clb_upi, version='3'): """Show AHRS calibration data for given `clb_upi`.""" db = DBManager() ahrs_upi = clbupi2ahrsupi(clb_upi) print("AHRS UPI: {}".format(ahrs_upi)) content = db._get_content("show_product_test.htm?upi={0}&" "testtype=AHRS-CA...
python
def show_ahrs_calibration(clb_upi, version='3'): """Show AHRS calibration data for given `clb_upi`.""" db = DBManager() ahrs_upi = clbupi2ahrsupi(clb_upi) print("AHRS UPI: {}".format(ahrs_upi)) content = db._get_content("show_product_test.htm?upi={0}&" "testtype=AHRS-CA...
[ "def", "show_ahrs_calibration", "(", "clb_upi", ",", "version", "=", "'3'", ")", ":", "db", "=", "DBManager", "(", ")", "ahrs_upi", "=", "clbupi2ahrsupi", "(", "clb_upi", ")", "print", "(", "\"AHRS UPI: {}\"", ".", "format", "(", "ahrs_upi", ")", ")", "con...
Show AHRS calibration data for given `clb_upi`.
[ "Show", "AHRS", "calibration", "data", "for", "given", "clb_upi", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L826-L848
train
Show AHRS calibration data for given clb_upi.
tamasgal/km3pipe
km3pipe/db.py
DBManager.datalog
def datalog(self, parameter, run, maxrun=None, det_id='D_ARCA001'): "Retrieve datalogs for given parameter, run(s) and detector" parameter = parameter.lower() if maxrun is None: maxrun = run with Timer('Database lookup'): return self._datalog(parameter, run, maxru...
python
def datalog(self, parameter, run, maxrun=None, det_id='D_ARCA001'): "Retrieve datalogs for given parameter, run(s) and detector" parameter = parameter.lower() if maxrun is None: maxrun = run with Timer('Database lookup'): return self._datalog(parameter, run, maxru...
[ "def", "datalog", "(", "self", ",", "parameter", ",", "run", ",", "maxrun", "=", "None", ",", "det_id", "=", "'D_ARCA001'", ")", ":", "parameter", "=", "parameter", ".", "lower", "(", ")", "if", "maxrun", "is", "None", ":", "maxrun", "=", "run", "wit...
Retrieve datalogs for given parameter, run(s) and detector
[ "Retrieve", "datalogs", "for", "given", "parameter", "run", "(", "s", ")", "and", "detector" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L126-L132
train
Retrieve datalogs for given parameter run ( s ) and detector
tamasgal/km3pipe
km3pipe/db.py
DBManager._datalog
def _datalog(self, parameter, run, maxrun, det_id): "Extract data from database" values = { 'parameter_name': parameter, 'minrun': run, 'maxrun': maxrun, 'detid': det_id, } data = urlencode(values) content = self._get_content('strea...
python
def _datalog(self, parameter, run, maxrun, det_id): "Extract data from database" values = { 'parameter_name': parameter, 'minrun': run, 'maxrun': maxrun, 'detid': det_id, } data = urlencode(values) content = self._get_content('strea...
[ "def", "_datalog", "(", "self", ",", "parameter", ",", "run", ",", "maxrun", ",", "det_id", ")", ":", "values", "=", "{", "'parameter_name'", ":", "parameter", ",", "'minrun'", ":", "run", ",", "'maxrun'", ":", "maxrun", ",", "'detid'", ":", "det_id", ...
Extract data from database
[ "Extract", "data", "from", "database" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L134-L162
train
Extract data from database
tamasgal/km3pipe
km3pipe/db.py
DBManager._add_converted_units
def _add_converted_units(self, dataframe, parameter, key='VALUE'): """Add an additional DATA_VALUE column with converted VALUEs""" convert_unit = self.parameters.get_converter(parameter) try: log.debug("Adding unit converted DATA_VALUE to the data") dataframe[key] = dataf...
python
def _add_converted_units(self, dataframe, parameter, key='VALUE'): """Add an additional DATA_VALUE column with converted VALUEs""" convert_unit = self.parameters.get_converter(parameter) try: log.debug("Adding unit converted DATA_VALUE to the data") dataframe[key] = dataf...
[ "def", "_add_converted_units", "(", "self", ",", "dataframe", ",", "parameter", ",", "key", "=", "'VALUE'", ")", ":", "convert_unit", "=", "self", ".", "parameters", ".", "get_converter", "(", "parameter", ")", "try", ":", "log", ".", "debug", "(", "\"Addi...
Add an additional DATA_VALUE column with converted VALUEs
[ "Add", "an", "additional", "DATA_VALUE", "column", "with", "converted", "VALUEs" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L178-L187
train
Add an additional DATA_VALUE column with converted VALUEs
tamasgal/km3pipe
km3pipe/db.py
DBManager.get_det_id
def get_det_id(self, det_oid): """Convert detector string representation (OID) to serialnumber""" try: return self.detectors[self.detectors.OID == det_oid ].SERIALNUMBER.iloc[0] except IndexError: log.critical("No det ID found for OID '{}...
python
def get_det_id(self, det_oid): """Convert detector string representation (OID) to serialnumber""" try: return self.detectors[self.detectors.OID == det_oid ].SERIALNUMBER.iloc[0] except IndexError: log.critical("No det ID found for OID '{}...
[ "def", "get_det_id", "(", "self", ",", "det_oid", ")", ":", "try", ":", "return", "self", ".", "detectors", "[", "self", ".", "detectors", ".", "OID", "==", "det_oid", "]", ".", "SERIALNUMBER", ".", "iloc", "[", "0", "]", "except", "IndexError", ":", ...
Convert detector string representation (OID) to serialnumber
[ "Convert", "detector", "string", "representation", "(", "OID", ")", "to", "serialnumber" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L205-L212
train
Convert detector string representation ( OID to serialnumber
tamasgal/km3pipe
km3pipe/db.py
DBManager.get_det_oid
def get_det_oid(self, det_id): """Convert detector serialnumber to string representation (OID)""" try: return self.detectors[self.detectors.SERIALNUMBER == det_id ].OID.iloc[0] except IndexError: log.critical("No OID found for det ID '{}'...
python
def get_det_oid(self, det_id): """Convert detector serialnumber to string representation (OID)""" try: return self.detectors[self.detectors.SERIALNUMBER == det_id ].OID.iloc[0] except IndexError: log.critical("No OID found for det ID '{}'...
[ "def", "get_det_oid", "(", "self", ",", "det_id", ")", ":", "try", ":", "return", "self", ".", "detectors", "[", "self", ".", "detectors", ".", "SERIALNUMBER", "==", "det_id", "]", ".", "OID", ".", "iloc", "[", "0", "]", "except", "IndexError", ":", ...
Convert detector serialnumber to string representation (OID)
[ "Convert", "detector", "serialnumber", "to", "string", "representation", "(", "OID", ")" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L214-L221
train
Convert detector serialnumber to string representation ( OID
tamasgal/km3pipe
km3pipe/db.py
DBManager.to_det_id
def to_det_id(self, det_id_or_det_oid): """Convert det ID or OID to det ID""" try: int(det_id_or_det_oid) except ValueError: return self.get_det_id(det_id_or_det_oid) else: return det_id_or_det_oid
python
def to_det_id(self, det_id_or_det_oid): """Convert det ID or OID to det ID""" try: int(det_id_or_det_oid) except ValueError: return self.get_det_id(det_id_or_det_oid) else: return det_id_or_det_oid
[ "def", "to_det_id", "(", "self", ",", "det_id_or_det_oid", ")", ":", "try", ":", "int", "(", "det_id_or_det_oid", ")", "except", "ValueError", ":", "return", "self", ".", "get_det_id", "(", "det_id_or_det_oid", ")", "else", ":", "return", "det_id_or_det_oid" ]
Convert det ID or OID to det ID
[ "Convert", "det", "ID", "or", "OID", "to", "det", "ID" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L223-L230
train
Convert det ID or OID to det ID.
tamasgal/km3pipe
km3pipe/db.py
DBManager.to_det_oid
def to_det_oid(self, det_id_or_det_oid): """Convert det OID or ID to det OID""" try: int(det_id_or_det_oid) except ValueError: return det_id_or_det_oid else: return self.get_det_oid(det_id_or_det_oid)
python
def to_det_oid(self, det_id_or_det_oid): """Convert det OID or ID to det OID""" try: int(det_id_or_det_oid) except ValueError: return det_id_or_det_oid else: return self.get_det_oid(det_id_or_det_oid)
[ "def", "to_det_oid", "(", "self", ",", "det_id_or_det_oid", ")", ":", "try", ":", "int", "(", "det_id_or_det_oid", ")", "except", "ValueError", ":", "return", "det_id_or_det_oid", "else", ":", "return", "self", ".", "get_det_oid", "(", "det_id_or_det_oid", ")" ]
Convert det OID or ID to det OID
[ "Convert", "det", "OID", "or", "ID", "to", "det", "OID" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L232-L239
train
Convert det OID or ID to det OID
tamasgal/km3pipe
km3pipe/db.py
DBManager._load_parameters
def _load_parameters(self): "Retrieve a list of available parameters from the database" parameters = self._get_json('allparam/s') data = {} for parameter in parameters: # There is a case-chaos in the DB data[parameter['Name'].lower()] = parameter self._parameters =...
python
def _load_parameters(self): "Retrieve a list of available parameters from the database" parameters = self._get_json('allparam/s') data = {} for parameter in parameters: # There is a case-chaos in the DB data[parameter['Name'].lower()] = parameter self._parameters =...
[ "def", "_load_parameters", "(", "self", ")", ":", "parameters", "=", "self", ".", "_get_json", "(", "'allparam/s'", ")", "data", "=", "{", "}", "for", "parameter", "in", "parameters", ":", "# There is a case-chaos in the DB", "data", "[", "parameter", "[", "'N...
Retrieve a list of available parameters from the database
[ "Retrieve", "a", "list", "of", "available", "parameters", "from", "the", "database" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L248-L254
train
Retrieve a list of available parameters from the database
tamasgal/km3pipe
km3pipe/db.py
DBManager.trigger_setup
def trigger_setup(self, runsetup_oid): "Retrieve the trigger setup for a given runsetup OID" r = self._get_content( "jsonds/rslite/s?rs_oid={}&upifilter=1.1.2.2.3/*". format(runsetup_oid) ) data = json.loads(r)['Data'] if not data: log.error("E...
python
def trigger_setup(self, runsetup_oid): "Retrieve the trigger setup for a given runsetup OID" r = self._get_content( "jsonds/rslite/s?rs_oid={}&upifilter=1.1.2.2.3/*". format(runsetup_oid) ) data = json.loads(r)['Data'] if not data: log.error("E...
[ "def", "trigger_setup", "(", "self", ",", "runsetup_oid", ")", ":", "r", "=", "self", ".", "_get_content", "(", "\"jsonds/rslite/s?rs_oid={}&upifilter=1.1.2.2.3/*\"", ".", "format", "(", "runsetup_oid", ")", ")", "data", "=", "json", ".", "loads", "(", "r", ")...
Retrieve the trigger setup for a given runsetup OID
[ "Retrieve", "the", "trigger", "setup", "for", "a", "given", "runsetup", "OID" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L256-L298
train
Retrieve the trigger setup for a given runsetup OID
tamasgal/km3pipe
km3pipe/db.py
DBManager.detx
def detx(self, det_id, t0set=None, calibration=None): """Retrieve the detector file for given detector id If t0set is given, append the calibration data. """ url = 'detx/{0}?'.format(det_id) # '?' since it's ignored if no args if t0set is not None: url += '&t0set=...
python
def detx(self, det_id, t0set=None, calibration=None): """Retrieve the detector file for given detector id If t0set is given, append the calibration data. """ url = 'detx/{0}?'.format(det_id) # '?' since it's ignored if no args if t0set is not None: url += '&t0set=...
[ "def", "detx", "(", "self", ",", "det_id", ",", "t0set", "=", "None", ",", "calibration", "=", "None", ")", ":", "url", "=", "'detx/{0}?'", ".", "format", "(", "det_id", ")", "# '?' since it's ignored if no args", "if", "t0set", "is", "not", "None", ":", ...
Retrieve the detector file for given detector id If t0set is given, append the calibration data.
[ "Retrieve", "the", "detector", "file", "for", "given", "detector", "id" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L311-L323
train
Retrieve the detector file for given detector id.
tamasgal/km3pipe
km3pipe/db.py
DBManager.ahrs
def ahrs(self, run, maxrun=None, clbupi=None, det_id='D_ARCA001'): "Retrieve AHRS values for given run(s) (optionally CLBs) and detector" if maxrun is None: maxrun = run with Timer('Database lookup'): return self._ahrs(run, maxrun, clbupi, det_id)
python
def ahrs(self, run, maxrun=None, clbupi=None, det_id='D_ARCA001'): "Retrieve AHRS values for given run(s) (optionally CLBs) and detector" if maxrun is None: maxrun = run with Timer('Database lookup'): return self._ahrs(run, maxrun, clbupi, det_id)
[ "def", "ahrs", "(", "self", ",", "run", ",", "maxrun", "=", "None", ",", "clbupi", "=", "None", ",", "det_id", "=", "'D_ARCA001'", ")", ":", "if", "maxrun", "is", "None", ":", "maxrun", "=", "run", "with", "Timer", "(", "'Database lookup'", ")", ":",...
Retrieve AHRS values for given run(s) (optionally CLBs) and detector
[ "Retrieve", "AHRS", "values", "for", "given", "run", "(", "s", ")", "(", "optionally", "CLBs", ")", "and", "detector" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L325-L330
train
Retrieve AHRS values for given run ( s ) ( optionally CLBs and detector
tamasgal/km3pipe
km3pipe/db.py
DBManager._get_json
def _get_json(self, url): "Get JSON-type content" content = self._get_content('jsonds/' + url) try: json_content = json.loads(content.decode()) except AttributeError: json_content = json.loads(content) if json_content['Comment']: log.warning(js...
python
def _get_json(self, url): "Get JSON-type content" content = self._get_content('jsonds/' + url) try: json_content = json.loads(content.decode()) except AttributeError: json_content = json.loads(content) if json_content['Comment']: log.warning(js...
[ "def", "_get_json", "(", "self", ",", "url", ")", ":", "content", "=", "self", ".", "_get_content", "(", "'jsonds/'", "+", "url", ")", "try", ":", "json_content", "=", "json", ".", "loads", "(", "content", ".", "decode", "(", ")", ")", "except", "Att...
Get JSON-type content
[ "Get", "JSON", "-", "type", "content" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L356-L367
train
Get JSON - type content
tamasgal/km3pipe
km3pipe/db.py
DBManager._get_content
def _get_content(self, url): "Get HTML content" target_url = self._db_url + '/' + unquote(url) # .encode('utf-8')) log.debug("Opening '{0}'".format(target_url)) try: f = self.opener.open(target_url) except HTTPError as e: log.error("HTTP error, your ses...
python
def _get_content(self, url): "Get HTML content" target_url = self._db_url + '/' + unquote(url) # .encode('utf-8')) log.debug("Opening '{0}'".format(target_url)) try: f = self.opener.open(target_url) except HTTPError as e: log.error("HTTP error, your ses...
[ "def", "_get_content", "(", "self", ",", "url", ")", ":", "target_url", "=", "self", ".", "_db_url", "+", "'/'", "+", "unquote", "(", "url", ")", "# .encode('utf-8'))", "log", ".", "debug", "(", "\"Opening '{0}'\"", ".", "format", "(", "target_url", ")", ...
Get HTML content
[ "Get", "HTML", "content" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L369-L393
train
Get HTML content
tamasgal/km3pipe
km3pipe/db.py
DBManager.opener
def opener(self): "A reusable connection manager" if self._opener is None: log.debug("Creating connection handler") opener = build_opener() if self._cookies: log.debug("Appending cookies") else: log.debug("No cookies to appe...
python
def opener(self): "A reusable connection manager" if self._opener is None: log.debug("Creating connection handler") opener = build_opener() if self._cookies: log.debug("Appending cookies") else: log.debug("No cookies to appe...
[ "def", "opener", "(", "self", ")", ":", "if", "self", ".", "_opener", "is", "None", ":", "log", ".", "debug", "(", "\"Creating connection handler\"", ")", "opener", "=", "build_opener", "(", ")", "if", "self", ".", "_cookies", ":", "log", ".", "debug", ...
A reusable connection manager
[ "A", "reusable", "connection", "manager" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L396-L411
train
A reusable connection manager
tamasgal/km3pipe
km3pipe/db.py
DBManager.request_sid_cookie
def request_sid_cookie(self, username, password): """Request cookie for permanent session token.""" log.debug("Requesting SID cookie") target_url = self._login_url + '?usr={0}&pwd={1}&persist=y'.format( username, password ) cookie = urlopen(target_url).read() ...
python
def request_sid_cookie(self, username, password): """Request cookie for permanent session token.""" log.debug("Requesting SID cookie") target_url = self._login_url + '?usr={0}&pwd={1}&persist=y'.format( username, password ) cookie = urlopen(target_url).read() ...
[ "def", "request_sid_cookie", "(", "self", ",", "username", ",", "password", ")", ":", "log", ".", "debug", "(", "\"Requesting SID cookie\"", ")", "target_url", "=", "self", ".", "_login_url", "+", "'?usr={0}&pwd={1}&persist=y'", ".", "format", "(", "username", "...
Request cookie for permanent session token.
[ "Request", "cookie", "for", "permanent", "session", "token", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L413-L420
train
Request a cookie for permanent session token.
tamasgal/km3pipe
km3pipe/db.py
DBManager.restore_session
def restore_session(self, cookie): """Establish databse connection using permanent session cookie""" log.debug("Restoring session from cookie: {}".format(cookie)) opener = build_opener() opener.addheaders.append(('Cookie', cookie)) self._opener = opener
python
def restore_session(self, cookie): """Establish databse connection using permanent session cookie""" log.debug("Restoring session from cookie: {}".format(cookie)) opener = build_opener() opener.addheaders.append(('Cookie', cookie)) self._opener = opener
[ "def", "restore_session", "(", "self", ",", "cookie", ")", ":", "log", ".", "debug", "(", "\"Restoring session from cookie: {}\"", ".", "format", "(", "cookie", ")", ")", "opener", "=", "build_opener", "(", ")", "opener", ".", "addheaders", ".", "append", "(...
Establish databse connection using permanent session cookie
[ "Establish", "databse", "connection", "using", "permanent", "session", "cookie" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L422-L427
train
Establish databse connection using permanent session cookie
tamasgal/km3pipe
km3pipe/db.py
DBManager.login
def login(self, username, password): "Login to the database and store cookies for upcoming requests." log.debug("Logging in to the DB") opener = self._build_opener() values = {'usr': username, 'pwd': password} req = self._make_request(self._login_url, values) try: ...
python
def login(self, username, password): "Login to the database and store cookies for upcoming requests." log.debug("Logging in to the DB") opener = self._build_opener() values = {'usr': username, 'pwd': password} req = self._make_request(self._login_url, values) try: ...
[ "def", "login", "(", "self", ",", "username", ",", "password", ")", ":", "log", ".", "debug", "(", "\"Logging in to the DB\"", ")", "opener", "=", "self", ".", "_build_opener", "(", ")", "values", "=", "{", "'usr'", ":", "username", ",", "'pwd'", ":", ...
Login to the database and store cookies for upcoming requests.
[ "Login", "to", "the", "database", "and", "store", "cookies", "for", "upcoming", "requests", "." ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L449-L467
train
Login to the database and store cookies for upcoming requests.
tamasgal/km3pipe
km3pipe/db.py
StreamDS._update_streams
def _update_streams(self): """Update the list of available straems""" content = self._db._get_content("streamds") self._stream_df = read_csv(content).sort_values("STREAM") self._streams = None for stream in self.streams: setattr(self, stream, self.__getattr__(stream))
python
def _update_streams(self): """Update the list of available straems""" content = self._db._get_content("streamds") self._stream_df = read_csv(content).sort_values("STREAM") self._streams = None for stream in self.streams: setattr(self, stream, self.__getattr__(stream))
[ "def", "_update_streams", "(", "self", ")", ":", "content", "=", "self", ".", "_db", ".", "_get_content", "(", "\"streamds\"", ")", "self", ".", "_stream_df", "=", "read_csv", "(", "content", ")", ".", "sort_values", "(", "\"STREAM\"", ")", "self", ".", ...
Update the list of available straems
[ "Update", "the", "list", "of", "available", "straems" ]
7a9b59ac899a28775b5bdc5d391d9a5340d08040
https://github.com/tamasgal/km3pipe/blob/7a9b59ac899a28775b5bdc5d391d9a5340d08040/km3pipe/db.py#L517-L523
train
Update the list of available straems