repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
cuihantao/andes
andes/variables/fileman.py
FileMan.get_fullpath
def get_fullpath(self, fullname=None, relative_to=None): """ Return the original full path if full path is specified, otherwise search in the case file path """ # if is an empty path if not fullname: return fullname isabs = os.path.isabs(fullname) ...
python
def get_fullpath(self, fullname=None, relative_to=None): """ Return the original full path if full path is specified, otherwise search in the case file path """ # if is an empty path if not fullname: return fullname isabs = os.path.isabs(fullname) ...
[ "def", "get_fullpath", "(", "self", ",", "fullname", "=", "None", ",", "relative_to", "=", "None", ")", ":", "# if is an empty path", "if", "not", "fullname", ":", "return", "fullname", "isabs", "=", "os", ".", "path", ".", "isabs", "(", "fullname", ")", ...
Return the original full path if full path is specified, otherwise search in the case file path
[ "Return", "the", "original", "full", "path", "if", "full", "path", "is", "specified", "otherwise", "search", "in", "the", "case", "file", "path" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/fileman.py#L99-L118
cuihantao/andes
andes/models/agc.py
eAGC.switch
def switch(self): """Switch if time for eAgc has come""" t = self.system.dae.t for idx in range(0, self.n): if t >= self.tl[idx]: if self.en[idx] == 0: self.en[idx] = 1 logger.info( 'Extended ACE <{}> act...
python
def switch(self): """Switch if time for eAgc has come""" t = self.system.dae.t for idx in range(0, self.n): if t >= self.tl[idx]: if self.en[idx] == 0: self.en[idx] = 1 logger.info( 'Extended ACE <{}> act...
[ "def", "switch", "(", "self", ")", ":", "t", "=", "self", ".", "system", ".", "dae", ".", "t", "for", "idx", "in", "range", "(", "0", ",", "self", ".", "n", ")", ":", "if", "t", ">=", "self", ".", "tl", "[", "idx", "]", ":", "if", "self", ...
Switch if time for eAgc has come
[ "Switch", "if", "time", "for", "eAgc", "has", "come" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/agc.py#L169-L178
cuihantao/andes
andes/routines/__init__.py
get_command
def get_command(all_pkg, hook): """ Collect the command-line interface names by querying ``hook`` in ``all_pkg`` Parameters ---------- all_pkg: list list of package files hook: str A variable where the command is stored. ``__cli__`` by default. Returns ------- list ...
python
def get_command(all_pkg, hook): """ Collect the command-line interface names by querying ``hook`` in ``all_pkg`` Parameters ---------- all_pkg: list list of package files hook: str A variable where the command is stored. ``__cli__`` by default. Returns ------- list ...
[ "def", "get_command", "(", "all_pkg", ",", "hook", ")", ":", "ret", "=", "[", "]", "for", "r", "in", "all_pkg", ":", "module", "=", "importlib", ".", "import_module", "(", "__name__", "+", "'.'", "+", "r", ".", "lower", "(", ")", ")", "ret", ".", ...
Collect the command-line interface names by querying ``hook`` in ``all_pkg`` Parameters ---------- all_pkg: list list of package files hook: str A variable where the command is stored. ``__cli__`` by default. Returns ------- list
[ "Collect", "the", "command", "-", "line", "interface", "names", "by", "querying", "hook", "in", "all_pkg" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/__init__.py#L7-L25
cuihantao/andes
andes/models/event.py
EventBase.get_times
def get_times(self): """ Return a list of occurrance times of the events :return: list of times """ if not self.n: return list() ret = list() for item in self._event_times: ret += list(self.__dict__[item]) return ret + list(matr...
python
def get_times(self): """ Return a list of occurrance times of the events :return: list of times """ if not self.n: return list() ret = list() for item in self._event_times: ret += list(self.__dict__[item]) return ret + list(matr...
[ "def", "get_times", "(", "self", ")", ":", "if", "not", "self", ".", "n", ":", "return", "list", "(", ")", "ret", "=", "list", "(", ")", "for", "item", "in", "self", ".", "_event_times", ":", "ret", "+=", "list", "(", "self", ".", "__dict__", "["...
Return a list of occurrance times of the events :return: list of times
[ "Return", "a", "list", "of", "occurrance", "times", "of", "the", "events" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/event.py#L20-L34
cuihantao/andes
andes/models/event.py
EventBase.apply
def apply(self, sim_time): """ Apply the event and :param sim_time: :return: """ if not self.n: return # skip if already applied if self._last_time != sim_time: self._last_time = sim_time else: return
python
def apply(self, sim_time): """ Apply the event and :param sim_time: :return: """ if not self.n: return # skip if already applied if self._last_time != sim_time: self._last_time = sim_time else: return
[ "def", "apply", "(", "self", ",", "sim_time", ")", ":", "if", "not", "self", ".", "n", ":", "return", "# skip if already applied", "if", "self", ".", "_last_time", "!=", "sim_time", ":", "self", ".", "_last_time", "=", "sim_time", "else", ":", "return" ]
Apply the event and :param sim_time: :return:
[ "Apply", "the", "event", "and", ":", "param", "sim_time", ":", ":", "return", ":" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/event.py#L49-L62
cuihantao/andes
andes/models/line.py
Line.build_y
def build_y(self): """Build transmission line admittance matrix into self.Y""" if not self.n: return self.y1 = mul(self.u, self.g1 + self.b1 * 1j) self.y2 = mul(self.u, self.g2 + self.b2 * 1j) self.y12 = div(self.u, self.r + self.x * 1j) self.m = polar(self.ta...
python
def build_y(self): """Build transmission line admittance matrix into self.Y""" if not self.n: return self.y1 = mul(self.u, self.g1 + self.b1 * 1j) self.y2 = mul(self.u, self.g2 + self.b2 * 1j) self.y12 = div(self.u, self.r + self.x * 1j) self.m = polar(self.ta...
[ "def", "build_y", "(", "self", ")", ":", "if", "not", "self", ".", "n", ":", "return", "self", ".", "y1", "=", "mul", "(", "self", ".", "u", ",", "self", ".", "g1", "+", "self", ".", "b1", "*", "1j", ")", "self", ".", "y2", "=", "mul", "(",...
Build transmission line admittance matrix into self.Y
[ "Build", "transmission", "line", "admittance", "matrix", "into", "self", ".", "Y" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L131-L152
cuihantao/andes
andes/models/line.py
Line.build_b
def build_b(self): """build Bp and Bpp for fast decoupled method""" if not self.n: return method = self.system.pflow.config.method.lower() # Build B prime matrix y1 = mul( self.u, self.g1 ) # y1 neglects line charging shunt, and g1 is usually 0 i...
python
def build_b(self): """build Bp and Bpp for fast decoupled method""" if not self.n: return method = self.system.pflow.config.method.lower() # Build B prime matrix y1 = mul( self.u, self.g1 ) # y1 neglects line charging shunt, and g1 is usually 0 i...
[ "def", "build_b", "(", "self", ")", ":", "if", "not", "self", ".", "n", ":", "return", "method", "=", "self", ".", "system", ".", "pflow", ".", "config", ".", "method", ".", "lower", "(", ")", "# Build B prime matrix", "y1", "=", "mul", "(", "self", ...
build Bp and Bpp for fast decoupled method
[ "build", "Bp", "and", "Bpp", "for", "fast", "decoupled", "method" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L159-L219
cuihantao/andes
andes/models/line.py
Line.incidence
def incidence(self): """Build incidence matrix into self.C""" self.C = \ spmatrix(self.u, range(self.n), self.a1, (self.n, self.nb), 'd') -\ spmatrix(self.u, range(self.n), self.a2, (self.n, self.nb), 'd')
python
def incidence(self): """Build incidence matrix into self.C""" self.C = \ spmatrix(self.u, range(self.n), self.a1, (self.n, self.nb), 'd') -\ spmatrix(self.u, range(self.n), self.a2, (self.n, self.nb), 'd')
[ "def", "incidence", "(", "self", ")", ":", "self", ".", "C", "=", "spmatrix", "(", "self", ".", "u", ",", "range", "(", "self", ".", "n", ")", ",", "self", ".", "a1", ",", "(", "self", ".", "n", ",", "self", ".", "nb", ")", ",", "'d'", ")",...
Build incidence matrix into self.C
[ "Build", "incidence", "matrix", "into", "self", ".", "C" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L221-L225
cuihantao/andes
andes/models/line.py
Line.connectivity
def connectivity(self, bus): """check connectivity of network using Goderya's algorithm""" if not self.n: return n = self.nb fr = self.a1 to = self.a2 os = [0] * self.n # find islanded buses diag = list( matrix( spm...
python
def connectivity(self, bus): """check connectivity of network using Goderya's algorithm""" if not self.n: return n = self.nb fr = self.a1 to = self.a2 os = [0] * self.n # find islanded buses diag = list( matrix( spm...
[ "def", "connectivity", "(", "self", ",", "bus", ")", ":", "if", "not", "self", ".", "n", ":", "return", "n", "=", "self", ".", "nb", "fr", "=", "self", ".", "a1", "to", "=", "self", ".", "a2", "os", "=", "[", "0", "]", "*", "self", ".", "n"...
check connectivity of network using Goderya's algorithm
[ "check", "connectivity", "of", "network", "using", "Goderya", "s", "algorithm" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L227-L285
cuihantao/andes
andes/models/line.py
Line.build_gy
def build_gy(self, dae): """Build line Jacobian matrix""" if not self.n: idx = range(dae.m) dae.set_jac(Gy, 1e-6, idx, idx) return Vn = polar(1.0, dae.y[self.a]) Vc = mul(dae.y[self.v], Vn) Ic = self.Y * Vc diagVn = spdiag(Vn) ...
python
def build_gy(self, dae): """Build line Jacobian matrix""" if not self.n: idx = range(dae.m) dae.set_jac(Gy, 1e-6, idx, idx) return Vn = polar(1.0, dae.y[self.a]) Vc = mul(dae.y[self.v], Vn) Ic = self.Y * Vc diagVn = spdiag(Vn) ...
[ "def", "build_gy", "(", "self", ",", "dae", ")", ":", "if", "not", "self", ".", "n", ":", "idx", "=", "range", "(", "dae", ".", "m", ")", "dae", ".", "set_jac", "(", "Gy", ",", "1e-6", ",", "idx", ",", "idx", ")", "return", "Vn", "=", "polar"...
Build line Jacobian matrix
[ "Build", "line", "Jacobian", "matrix" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L313-L339
cuihantao/andes
andes/models/line.py
Line.seriesflow
def seriesflow(self, dae): """ Compute the flow through the line after solving PF. Compute terminal injections, line losses """ # Vm = dae.y[self.v] # Va = dae.y[self.a] # V1 = polar(Vm[self.a1], Va[self.a1]) # V2 = polar(Vm[self.a2], Va[self.a2]) ...
python
def seriesflow(self, dae): """ Compute the flow through the line after solving PF. Compute terminal injections, line losses """ # Vm = dae.y[self.v] # Va = dae.y[self.a] # V1 = polar(Vm[self.a1], Va[self.a1]) # V2 = polar(Vm[self.a2], Va[self.a2]) ...
[ "def", "seriesflow", "(", "self", ",", "dae", ")", ":", "# Vm = dae.y[self.v]", "# Va = dae.y[self.a]", "# V1 = polar(Vm[self.a1], Va[self.a1])", "# V2 = polar(Vm[self.a2], Va[self.a2])", "I1", "=", "mul", "(", "self", ".", "v1", ",", "div", "(", "self", ".", "y12", ...
Compute the flow through the line after solving PF. Compute terminal injections, line losses
[ "Compute", "the", "flow", "through", "the", "line", "after", "solving", "PF", "." ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L341-L382
cuihantao/andes
andes/models/line.py
Line.v1
def v1(self): """Return voltage phasors at the "from buses" (bus1)""" Vm = self.system.dae.y[self.v] Va = self.system.dae.y[self.a] return polar(Vm[self.a1], Va[self.a1])
python
def v1(self): """Return voltage phasors at the "from buses" (bus1)""" Vm = self.system.dae.y[self.v] Va = self.system.dae.y[self.a] return polar(Vm[self.a1], Va[self.a1])
[ "def", "v1", "(", "self", ")", ":", "Vm", "=", "self", ".", "system", ".", "dae", ".", "y", "[", "self", ".", "v", "]", "Va", "=", "self", ".", "system", ".", "dae", ".", "y", "[", "self", ".", "a", "]", "return", "polar", "(", "Vm", "[", ...
Return voltage phasors at the "from buses" (bus1)
[ "Return", "voltage", "phasors", "at", "the", "from", "buses", "(", "bus1", ")" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L385-L389
cuihantao/andes
andes/models/line.py
Line.v2
def v2(self): """Return voltage phasors at the "to buses" (bus2)""" Vm = self.system.dae.y[self.v] Va = self.system.dae.y[self.a] return polar(Vm[self.a2], Va[self.a2])
python
def v2(self): """Return voltage phasors at the "to buses" (bus2)""" Vm = self.system.dae.y[self.v] Va = self.system.dae.y[self.a] return polar(Vm[self.a2], Va[self.a2])
[ "def", "v2", "(", "self", ")", ":", "Vm", "=", "self", ".", "system", ".", "dae", ".", "y", "[", "self", ".", "v", "]", "Va", "=", "self", ".", "system", ".", "dae", ".", "y", "[", "self", ".", "a", "]", "return", "polar", "(", "Vm", "[", ...
Return voltage phasors at the "to buses" (bus2)
[ "Return", "voltage", "phasors", "at", "the", "to", "buses", "(", "bus2", ")" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L392-L396
cuihantao/andes
andes/models/line.py
Line.switch
def switch(self, idx, u): """switch the status of Line idx""" self.u[self.uid[idx]] = u self.rebuild = True self.system.dae.factorize = True logger.debug('<Line> Status switch to {} on idx {}.'.format(u, idx))
python
def switch(self, idx, u): """switch the status of Line idx""" self.u[self.uid[idx]] = u self.rebuild = True self.system.dae.factorize = True logger.debug('<Line> Status switch to {} on idx {}.'.format(u, idx))
[ "def", "switch", "(", "self", ",", "idx", ",", "u", ")", ":", "self", ".", "u", "[", "self", ".", "uid", "[", "idx", "]", "]", "=", "u", "self", ".", "rebuild", "=", "True", "self", ".", "system", ".", "dae", ".", "factorize", "=", "True", "l...
switch the status of Line idx
[ "switch", "the", "status", "of", "Line", "idx" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L398-L403
cuihantao/andes
andes/models/line.py
Line._varname_flow
def _varname_flow(self): """Build variable names for Pij, Pji, Qij, Qji, Sij, Sji""" if not self.n: return mpq = self.system.dae.m + 2 * self.system.Bus.n nl = self.n # Pij xy_idx = range(mpq, mpq + nl) self.system.varname.append( listnam...
python
def _varname_flow(self): """Build variable names for Pij, Pji, Qij, Qji, Sij, Sji""" if not self.n: return mpq = self.system.dae.m + 2 * self.system.Bus.n nl = self.n # Pij xy_idx = range(mpq, mpq + nl) self.system.varname.append( listnam...
[ "def", "_varname_flow", "(", "self", ")", ":", "if", "not", "self", ".", "n", ":", "return", "mpq", "=", "self", ".", "system", ".", "dae", ".", "m", "+", "2", "*", "self", ".", "system", ".", "Bus", ".", "n", "nl", "=", "self", ".", "n", "# ...
Build variable names for Pij, Pji, Qij, Qji, Sij, Sji
[ "Build", "variable", "names", "for", "Pij", "Pji", "Qij", "Qji", "Sij", "Sji" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L409-L519
cuihantao/andes
andes/models/line.py
Line.get_flow_by_idx
def get_flow_by_idx(self, idx, bus): """Return seriesflow based on the external idx on the `bus` side""" P, Q = [], [] if type(idx) is not list: idx = [idx] if type(bus) is not list: bus = [bus] for line_idx, bus_idx in zip(idx, bus): line_int...
python
def get_flow_by_idx(self, idx, bus): """Return seriesflow based on the external idx on the `bus` side""" P, Q = [], [] if type(idx) is not list: idx = [idx] if type(bus) is not list: bus = [bus] for line_idx, bus_idx in zip(idx, bus): line_int...
[ "def", "get_flow_by_idx", "(", "self", ",", "idx", ",", "bus", ")", ":", "P", ",", "Q", "=", "[", "]", ",", "[", "]", "if", "type", "(", "idx", ")", "is", "not", "list", ":", "idx", "=", "[", "idx", "]", "if", "type", "(", "bus", ")", "is",...
Return seriesflow based on the external idx on the `bus` side
[ "Return", "seriesflow", "based", "on", "the", "external", "idx", "on", "the", "bus", "side" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L521-L537
cuihantao/andes
andes/models/line.py
Line.leaf_bus
def leaf_bus(self, df=False): """ Return leaf bus idx, line idx, and the line foreign key Returns ------- (list, list, list) or DataFrame """ # leafs - leaf bus idx # lines - line idx # fkey - the foreign key of Line, in 'bus1' or 'bus2', linking...
python
def leaf_bus(self, df=False): """ Return leaf bus idx, line idx, and the line foreign key Returns ------- (list, list, list) or DataFrame """ # leafs - leaf bus idx # lines - line idx # fkey - the foreign key of Line, in 'bus1' or 'bus2', linking...
[ "def", "leaf_bus", "(", "self", ",", "df", "=", "False", ")", ":", "# leafs - leaf bus idx", "# lines - line idx", "# fkey - the foreign key of Line, in 'bus1' or 'bus2', linking the bus", "leafs", ",", "lines", ",", "fkeys", "=", "list", "(", ")", ",", "list", "(", ...
Return leaf bus idx, line idx, and the line foreign key Returns ------- (list, list, list) or DataFrame
[ "Return", "leaf", "bus", "idx", "line", "idx", "and", "the", "line", "foreign", "key" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L539-L576
Legobot/Legobot
Legobot/Utilities.py
Utilities.truncate
def truncate(text, length=255): """ Splits the message into a list of strings of of length `length` Args: text (str): The text to be divided length (int, optional): The length of the chunks of text. \ Defaults to 255. Returns: lis...
python
def truncate(text, length=255): """ Splits the message into a list of strings of of length `length` Args: text (str): The text to be divided length (int, optional): The length of the chunks of text. \ Defaults to 255. Returns: lis...
[ "def", "truncate", "(", "text", ",", "length", "=", "255", ")", ":", "lines", "=", "[", "]", "i", "=", "0", "while", "i", "<", "len", "(", "text", ")", "-", "1", ":", "try", ":", "lines", ".", "append", "(", "text", "[", "i", ":", "i", "+",...
Splits the message into a list of strings of of length `length` Args: text (str): The text to be divided length (int, optional): The length of the chunks of text. \ Defaults to 255. Returns: list: Text divided into chunks of length `length`
[ "Splits", "the", "message", "into", "a", "list", "of", "strings", "of", "of", "length", "length" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Utilities.py#L24-L46
cuihantao/andes
andes/variables/varname.py
VarName.resize
def resize(self): """Resize (extend) the list for variable names""" yext = self.system.dae.m - len(self.unamey) xext = self.system.dae.n - len(self.unamex) if yext > 0: self.unamey.extend([''] * yext) self.fnamey.extend([''] * yext) if xext > 0: ...
python
def resize(self): """Resize (extend) the list for variable names""" yext = self.system.dae.m - len(self.unamey) xext = self.system.dae.n - len(self.unamex) if yext > 0: self.unamey.extend([''] * yext) self.fnamey.extend([''] * yext) if xext > 0: ...
[ "def", "resize", "(", "self", ")", ":", "yext", "=", "self", ".", "system", ".", "dae", ".", "m", "-", "len", "(", "self", ".", "unamey", ")", "xext", "=", "self", ".", "system", ".", "dae", ".", "n", "-", "len", "(", "self", ".", "unamex", "...
Resize (extend) the list for variable names
[ "Resize", "(", "extend", ")", "the", "list", "for", "variable", "names" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L16-L25
cuihantao/andes
andes/variables/varname.py
VarName.resize_for_flows
def resize_for_flows(self): """Extend `unamey` and `fnamey` for bus injections and line flows""" if self.system.config.dime_enable: self.system.tds.config.compute_flows = True if self.system.tds.config.compute_flows: nflows = 2 * self.system.Bus.n + \ ...
python
def resize_for_flows(self): """Extend `unamey` and `fnamey` for bus injections and line flows""" if self.system.config.dime_enable: self.system.tds.config.compute_flows = True if self.system.tds.config.compute_flows: nflows = 2 * self.system.Bus.n + \ ...
[ "def", "resize_for_flows", "(", "self", ")", ":", "if", "self", ".", "system", ".", "config", ".", "dime_enable", ":", "self", ".", "system", ".", "tds", ".", "config", ".", "compute_flows", "=", "True", "if", "self", ".", "system", ".", "tds", ".", ...
Extend `unamey` and `fnamey` for bus injections and line flows
[ "Extend", "unamey", "and", "fnamey", "for", "bus", "injections", "and", "line", "flows" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L27-L37
cuihantao/andes
andes/variables/varname.py
VarName.append
def append(self, listname, xy_idx, var_name, element_name): """Append variable names to the name lists""" self.resize() string = '{0} {1}' if listname not in ['unamex', 'unamey', 'fnamex', 'fnamey']: logger.error('Wrong list name for varname.') return elif...
python
def append(self, listname, xy_idx, var_name, element_name): """Append variable names to the name lists""" self.resize() string = '{0} {1}' if listname not in ['unamex', 'unamey', 'fnamex', 'fnamey']: logger.error('Wrong list name for varname.') return elif...
[ "def", "append", "(", "self", ",", "listname", ",", "xy_idx", ",", "var_name", ",", "element_name", ")", ":", "self", ".", "resize", "(", ")", "string", "=", "'{0} {1}'", "if", "listname", "not", "in", "[", "'unamex'", ",", "'unamey'", ",", "'fnamex'", ...
Append variable names to the name lists
[ "Append", "variable", "names", "to", "the", "name", "lists" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L39-L60
cuihantao/andes
andes/variables/varname.py
VarName.bus_line_names
def bus_line_names(self): """Append bus injection and line flow names to `varname`""" if self.system.tds.config.compute_flows: self.system.Bus._varname_inj() self.system.Line._varname_flow() self.system.Area._varname_inter()
python
def bus_line_names(self): """Append bus injection and line flow names to `varname`""" if self.system.tds.config.compute_flows: self.system.Bus._varname_inj() self.system.Line._varname_flow() self.system.Area._varname_inter()
[ "def", "bus_line_names", "(", "self", ")", ":", "if", "self", ".", "system", ".", "tds", ".", "config", ".", "compute_flows", ":", "self", ".", "system", ".", "Bus", ".", "_varname_inj", "(", ")", "self", ".", "system", ".", "Line", ".", "_varname_flow...
Append bus injection and line flow names to `varname`
[ "Append", "bus", "injection", "and", "line", "flow", "names", "to", "varname" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L62-L67
cuihantao/andes
andes/variables/varname.py
VarName.get_xy_name
def get_xy_name(self, yidx, xidx=0): """ Return variable names for the given indices :param yidx: :param xidx: :return: """ assert isinstance(xidx, int) if isinstance(yidx, int): yidx = [yidx] uname = ['Time [s]'] + self.uname ...
python
def get_xy_name(self, yidx, xidx=0): """ Return variable names for the given indices :param yidx: :param xidx: :return: """ assert isinstance(xidx, int) if isinstance(yidx, int): yidx = [yidx] uname = ['Time [s]'] + self.uname ...
[ "def", "get_xy_name", "(", "self", ",", "yidx", ",", "xidx", "=", "0", ")", ":", "assert", "isinstance", "(", "xidx", ",", "int", ")", "if", "isinstance", "(", "yidx", ",", "int", ")", ":", "yidx", "=", "[", "yidx", "]", "uname", "=", "[", "'Time...
Return variable names for the given indices :param yidx: :param xidx: :return:
[ "Return", "variable", "names", "for", "the", "given", "indices" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L89-L113
DiamondLightSource/python-workflows
workflows/services/__init__.py
get_known_services
def get_known_services(): """Return a dictionary of all known services. :return: A dictionary containing entries { service name : service class } Future: This will change to a dictionary containing references to factories: { service name : service class factory } A fac...
python
def get_known_services(): """Return a dictionary of all known services. :return: A dictionary containing entries { service name : service class } Future: This will change to a dictionary containing references to factories: { service name : service class factory } A fac...
[ "def", "get_known_services", "(", ")", ":", "if", "not", "hasattr", "(", "get_known_services", ",", "\"cache\"", ")", ":", "setattr", "(", "get_known_services", ",", "\"cache\"", ",", "{", "e", ".", "name", ":", "e", ".", "load", "(", ")", "for", "e", ...
Return a dictionary of all known services. :return: A dictionary containing entries { service name : service class } Future: This will change to a dictionary containing references to factories: { service name : service class factory } A factory is a function that takes no ...
[ "Return", "a", "dictionary", "of", "all", "known", "services", ".", ":", "return", ":", "A", "dictionary", "containing", "entries", "{", "service", "name", ":", "service", "class", "}" ]
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/__init__.py#L14-L34
cuihantao/andes
andes/plot.py
cli_parse
def cli_parse(): """command line input parser""" parser = ArgumentParser(prog='andesplot') parser.add_argument('datfile', nargs=1, default=[], help='dat file name.') parser.add_argument('x', nargs=1, type=int, help='x axis variable index') parser.add_argument('y', nargs='*', help='y axis variable in...
python
def cli_parse(): """command line input parser""" parser = ArgumentParser(prog='andesplot') parser.add_argument('datfile', nargs=1, default=[], help='dat file name.') parser.add_argument('x', nargs=1, type=int, help='x axis variable index') parser.add_argument('y', nargs='*', help='y axis variable in...
[ "def", "cli_parse", "(", ")", ":", "parser", "=", "ArgumentParser", "(", "prog", "=", "'andesplot'", ")", "parser", ".", "add_argument", "(", "'datfile'", ",", "nargs", "=", "1", ",", "default", "=", "[", "]", ",", "help", "=", "'dat file name.'", ")", ...
command line input parser
[ "command", "line", "input", "parser" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L209-L241
cuihantao/andes
andes/plot.py
add_plot
def add_plot(x, y, xl, yl, fig, ax, LATEX=False, linestyle=None, **kwargs): """Add plots to an existing plot""" if LATEX: xl_data = xl[1] # NOQA yl_data = yl[1] else: xl_data = xl[0] # NOQA yl_data = yl[0] for idx in range(len(y)): ax.plot(x, y[idx], label=yl_d...
python
def add_plot(x, y, xl, yl, fig, ax, LATEX=False, linestyle=None, **kwargs): """Add plots to an existing plot""" if LATEX: xl_data = xl[1] # NOQA yl_data = yl[1] else: xl_data = xl[0] # NOQA yl_data = yl[0] for idx in range(len(y)): ax.plot(x, y[idx], label=yl_d...
[ "def", "add_plot", "(", "x", ",", "y", ",", "xl", ",", "yl", ",", "fig", ",", "ax", ",", "LATEX", "=", "False", ",", "linestyle", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "LATEX", ":", "xl_data", "=", "xl", "[", "1", "]", "# NOQA...
Add plots to an existing plot
[ "Add", "plots", "to", "an", "existing", "plot" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L481-L494
cuihantao/andes
andes/plot.py
check_init
def check_init(yval, yl): """"Check initialization by comparing t=0 and t=end values""" suspect = [] for var, label in zip(yval, yl): if abs(var[0] - var[-1]) >= 1e-6: suspect.append(label) if suspect: print('Initialization failure:') print(', '.join(suspect)) els...
python
def check_init(yval, yl): """"Check initialization by comparing t=0 and t=end values""" suspect = [] for var, label in zip(yval, yl): if abs(var[0] - var[-1]) >= 1e-6: suspect.append(label) if suspect: print('Initialization failure:') print(', '.join(suspect)) els...
[ "def", "check_init", "(", "yval", ",", "yl", ")", ":", "suspect", "=", "[", "]", "for", "var", ",", "label", "in", "zip", "(", "yval", ",", "yl", ")", ":", "if", "abs", "(", "var", "[", "0", "]", "-", "var", "[", "-", "1", "]", ")", ">=", ...
Check initialization by comparing t=0 and t=end values
[ "Check", "initialization", "by", "comparing", "t", "=", "0", "and", "t", "=", "end", "values" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L577-L587
cuihantao/andes
andes/plot.py
TDSData.load_lst
def load_lst(self): """ Load the lst file into internal data structures """ with open(self._lst_file, 'r') as fd: lines = fd.readlines() idx, uname, fname = list(), list(), list() for line in lines: values = line.split(',') values = ...
python
def load_lst(self): """ Load the lst file into internal data structures """ with open(self._lst_file, 'r') as fd: lines = fd.readlines() idx, uname, fname = list(), list(), list() for line in lines: values = line.split(',') values = ...
[ "def", "load_lst", "(", "self", ")", ":", "with", "open", "(", "self", ".", "_lst_file", ",", "'r'", ")", "as", "fd", ":", "lines", "=", "fd", ".", "readlines", "(", ")", "idx", ",", "uname", ",", "fname", "=", "list", "(", ")", ",", "list", "(...
Load the lst file into internal data structures
[ "Load", "the", "lst", "file", "into", "internal", "data", "structures" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L73-L95
cuihantao/andes
andes/plot.py
TDSData.find_var
def find_var(self, query, formatted=False): """ Return variable names and indices matching ``query`` """ # load the variable list to search in names = self._uname if formatted is False else self._fname found_idx, found_names = list(), list() for idx, name in zi...
python
def find_var(self, query, formatted=False): """ Return variable names and indices matching ``query`` """ # load the variable list to search in names = self._uname if formatted is False else self._fname found_idx, found_names = list(), list() for idx, name in zi...
[ "def", "find_var", "(", "self", ",", "query", ",", "formatted", "=", "False", ")", ":", "# load the variable list to search in", "names", "=", "self", ".", "_uname", "if", "formatted", "is", "False", "else", "self", ".", "_fname", "found_idx", ",", "found_name...
Return variable names and indices matching ``query``
[ "Return", "variable", "names", "and", "indices", "matching", "query" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L97-L112
cuihantao/andes
andes/plot.py
TDSData.load_dat
def load_dat(self, delimiter=','): """ Load the dat file into internal data structures, ``self._data`` """ try: data = np.loadtxt(self._dat_file, delimiter=',') except ValueError: data = np.loadtxt(self._dat_file) self._data = data
python
def load_dat(self, delimiter=','): """ Load the dat file into internal data structures, ``self._data`` """ try: data = np.loadtxt(self._dat_file, delimiter=',') except ValueError: data = np.loadtxt(self._dat_file) self._data = data
[ "def", "load_dat", "(", "self", ",", "delimiter", "=", "','", ")", ":", "try", ":", "data", "=", "np", ".", "loadtxt", "(", "self", ".", "_dat_file", ",", "delimiter", "=", "','", ")", "except", "ValueError", ":", "data", "=", "np", ".", "loadtxt", ...
Load the dat file into internal data structures, ``self._data``
[ "Load", "the", "dat", "file", "into", "internal", "data", "structures", "self", ".", "_data" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L114-L123
cuihantao/andes
andes/plot.py
TDSData.get_values
def get_values(self, idx): """ Return the variable values at the given indices """ if isinstance(idx, list): idx = np.array(idx, dtype=int) return self._data[:, idx]
python
def get_values(self, idx): """ Return the variable values at the given indices """ if isinstance(idx, list): idx = np.array(idx, dtype=int) return self._data[:, idx]
[ "def", "get_values", "(", "self", ",", "idx", ")", ":", "if", "isinstance", "(", "idx", ",", "list", ")", ":", "idx", "=", "np", ".", "array", "(", "idx", ",", "dtype", "=", "int", ")", "return", "self", ".", "_data", "[", ":", ",", "idx", "]" ...
Return the variable values at the given indices
[ "Return", "the", "variable", "values", "at", "the", "given", "indices" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L125-L132
cuihantao/andes
andes/plot.py
TDSData.get_header
def get_header(self, idx, formatted=False): """ Return a list of the variable names at the given indices """ header = self._uname if not formatted else self._fname return [header[x] for x in idx]
python
def get_header(self, idx, formatted=False): """ Return a list of the variable names at the given indices """ header = self._uname if not formatted else self._fname return [header[x] for x in idx]
[ "def", "get_header", "(", "self", ",", "idx", ",", "formatted", "=", "False", ")", ":", "header", "=", "self", ".", "_uname", "if", "not", "formatted", "else", "self", ".", "_fname", "return", "[", "header", "[", "x", "]", "for", "x", "in", "idx", ...
Return a list of the variable names at the given indices
[ "Return", "a", "list", "of", "the", "variable", "names", "at", "the", "given", "indices" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L134-L139
cuihantao/andes
andes/plot.py
TDSData.export_csv
def export_csv(self, path, idx=None, header=None, formatted=False, sort_idx=True, fmt='%.18e'): """ Export to a csv file Parameters ---------- path : str path of the csv file to save idx : None or array-like, optional the indice...
python
def export_csv(self, path, idx=None, header=None, formatted=False, sort_idx=True, fmt='%.18e'): """ Export to a csv file Parameters ---------- path : str path of the csv file to save idx : None or array-like, optional the indice...
[ "def", "export_csv", "(", "self", ",", "path", ",", "idx", "=", "None", ",", "header", "=", "None", ",", "formatted", "=", "False", ",", "sort_idx", "=", "True", ",", "fmt", "=", "'%.18e'", ")", ":", "if", "not", "idx", ":", "idx", "=", "self", "...
Export to a csv file Parameters ---------- path : str path of the csv file to save idx : None or array-like, optional the indices of the variables to export. Export all by default header : None or array-like, optional customized header if not ...
[ "Export", "to", "a", "csv", "file" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L141-L175
cuihantao/andes
andes/utils/tab.py
Tab.auto_style
def auto_style(self): """ automatic styling according to _row_size 76 characters in a row """ if self._row_size is None: return elif self._row_size == 3: self.set_cols_align(['l', 'l', 'l']) self.set_cols_valign(['t', 't', 't']) ...
python
def auto_style(self): """ automatic styling according to _row_size 76 characters in a row """ if self._row_size is None: return elif self._row_size == 3: self.set_cols_align(['l', 'l', 'l']) self.set_cols_valign(['t', 't', 't']) ...
[ "def", "auto_style", "(", "self", ")", ":", "if", "self", ".", "_row_size", "is", "None", ":", "return", "elif", "self", ".", "_row_size", "==", "3", ":", "self", ".", "set_cols_align", "(", "[", "'l'", ",", "'l'", ",", "'l'", "]", ")", "self", "."...
automatic styling according to _row_size 76 characters in a row
[ "automatic", "styling", "according", "to", "_row_size", "76", "characters", "in", "a", "row" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/tab.py#L45-L59
cuihantao/andes
andes/utils/tab.py
Tab.add_left_space
def add_left_space(self, nspace=1): """elem_add n cols of spaces before the first col. (for texttable 0.8.3)""" sp = ' ' * nspace for item in self._rows: item[0] = sp + item[0]
python
def add_left_space(self, nspace=1): """elem_add n cols of spaces before the first col. (for texttable 0.8.3)""" sp = ' ' * nspace for item in self._rows: item[0] = sp + item[0]
[ "def", "add_left_space", "(", "self", ",", "nspace", "=", "1", ")", ":", "sp", "=", "' '", "*", "nspace", "for", "item", "in", "self", ".", "_rows", ":", "item", "[", "0", "]", "=", "sp", "+", "item", "[", "0", "]" ]
elem_add n cols of spaces before the first col. (for texttable 0.8.3)
[ "elem_add", "n", "cols", "of", "spaces", "before", "the", "first", "col", ".", "(", "for", "texttable", "0", ".", "8", ".", "3", ")" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/tab.py#L65-L70
cuihantao/andes
andes/utils/tab.py
Tab.draw
def draw(self): """generate texttable formatted string""" self.guess_header() self.add_left_space( ) # for Texttable, elem_add a column of whitespace on the left for # better visual effect if self._title and self._descr: pre = self._title + '\n' + self...
python
def draw(self): """generate texttable formatted string""" self.guess_header() self.add_left_space( ) # for Texttable, elem_add a column of whitespace on the left for # better visual effect if self._title and self._descr: pre = self._title + '\n' + self...
[ "def", "draw", "(", "self", ")", ":", "self", ".", "guess_header", "(", ")", "self", ".", "add_left_space", "(", ")", "# for Texttable, elem_add a column of whitespace on the left for", "# better visual effect", "if", "self", ".", "_title", "and", "self", ".", "_des...
generate texttable formatted string
[ "generate", "texttable", "formatted", "string" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/tab.py#L72-L88
cuihantao/andes
andes/utils/tab.py
simpletab.guess_width
def guess_width(self): """auto fit column width""" if len(self.header) <= 4: nspace = 6 elif len(self.header) <= 6: nspace = 5 else: nspace = 4 ncol = len(self.header) self._width = [nspace] * ncol width = [0] * ncol # ...
python
def guess_width(self): """auto fit column width""" if len(self.header) <= 4: nspace = 6 elif len(self.header) <= 6: nspace = 5 else: nspace = 4 ncol = len(self.header) self._width = [nspace] * ncol width = [0] * ncol # ...
[ "def", "guess_width", "(", "self", ")", ":", "if", "len", "(", "self", ".", "header", ")", "<=", "4", ":", "nspace", "=", "6", "elif", "len", "(", "self", ".", "header", ")", "<=", "6", ":", "nspace", "=", "5", "else", ":", "nspace", "=", "4", ...
auto fit column width
[ "auto", "fit", "column", "width" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/tab.py#L104-L133
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.subscribe
def subscribe(self, channel, callback, **kwargs): """Listen to a queue, notify via callback function. :param channel: Queue name to subscribe to :param callback: Function to be called when messages are received. The callback will pass two arguments, the header as a ...
python
def subscribe(self, channel, callback, **kwargs): """Listen to a queue, notify via callback function. :param channel: Queue name to subscribe to :param callback: Function to be called when messages are received. The callback will pass two arguments, the header as a ...
[ "def", "subscribe", "(", "self", ",", "channel", ",", "callback", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__subscription_id", "+=", "1", "def", "mangled_callback", "(", "header", ",", "message", ")", ":", "return", "callback", "(", "header", ","...
Listen to a queue, notify via callback function. :param channel: Queue name to subscribe to :param callback: Function to be called when messages are received. The callback will pass two arguments, the header as a dictionary structure, and the message. ...
[ "Listen", "to", "a", "queue", "notify", "via", "callback", "function", ".", ":", "param", "channel", ":", "Queue", "name", "to", "subscribe", "to", ":", "param", "callback", ":", "Function", "to", "be", "called", "when", "messages", "are", "received", ".",...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L43-L73
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.unsubscribe
def unsubscribe(self, subscription, drop_callback_reference=False, **kwargs): """Stop listening to a queue or a broadcast :param subscription: Subscription ID to cancel :param drop_callback_reference: Drop the reference to the registered callback function ...
python
def unsubscribe(self, subscription, drop_callback_reference=False, **kwargs): """Stop listening to a queue or a broadcast :param subscription: Subscription ID to cancel :param drop_callback_reference: Drop the reference to the registered callback function ...
[ "def", "unsubscribe", "(", "self", ",", "subscription", ",", "drop_callback_reference", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "subscription", "not", "in", "self", ".", "__subscriptions", ":", "raise", "workflows", ".", "Error", "(", "\"Attem...
Stop listening to a queue or a broadcast :param subscription: Subscription ID to cancel :param drop_callback_reference: Drop the reference to the registered callback function immediately. This means any buffered messages sti...
[ "Stop", "listening", "to", "a", "queue", "or", "a", "broadcast", ":", "param", "subscription", ":", "Subscription", "ID", "to", "cancel", ":", "param", "drop_callback_reference", ":", "Drop", "the", "reference", "to", "the", "registered", "callback", "function",...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L75-L95
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.drop_callback_reference
def drop_callback_reference(self, subscription): """Drop reference to the callback function after unsubscribing. Any future messages arriving for that subscription will result in exceptions being raised. :param subscription: Subscription ID to delete callback reference for. """ ...
python
def drop_callback_reference(self, subscription): """Drop reference to the callback function after unsubscribing. Any future messages arriving for that subscription will result in exceptions being raised. :param subscription: Subscription ID to delete callback reference for. """ ...
[ "def", "drop_callback_reference", "(", "self", ",", "subscription", ")", ":", "if", "subscription", "not", "in", "self", ".", "__subscriptions", ":", "raise", "workflows", ".", "Error", "(", "\"Attempting to drop callback reference for unknown subscription\"", ")", "if"...
Drop reference to the callback function after unsubscribing. Any future messages arriving for that subscription will result in exceptions being raised. :param subscription: Subscription ID to delete callback reference for.
[ "Drop", "reference", "to", "the", "callback", "function", "after", "unsubscribing", ".", "Any", "future", "messages", "arriving", "for", "that", "subscription", "will", "result", "in", "exceptions", "being", "raised", ".", ":", "param", "subscription", ":", "Sub...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L97-L111
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.subscribe_broadcast
def subscribe_broadcast(self, channel, callback, **kwargs): """Listen to a broadcast topic, notify via callback function. :param channel: Topic name to subscribe to :param callback: Function to be called when messages are received. The callback will pass two arguments, t...
python
def subscribe_broadcast(self, channel, callback, **kwargs): """Listen to a broadcast topic, notify via callback function. :param channel: Topic name to subscribe to :param callback: Function to be called when messages are received. The callback will pass two arguments, t...
[ "def", "subscribe_broadcast", "(", "self", ",", "channel", ",", "callback", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__subscription_id", "+=", "1", "def", "mangled_callback", "(", "header", ",", "message", ")", ":", "return", "callback", "(", "head...
Listen to a broadcast topic, notify via callback function. :param channel: Topic name to subscribe to :param callback: Function to be called when messages are received. The callback will pass two arguments, the header as a dictionary structure, and the m...
[ "Listen", "to", "a", "broadcast", "topic", "notify", "via", "callback", "function", ".", ":", "param", "channel", ":", "Topic", "name", "to", "subscribe", "to", ":", "param", "callback", ":", "Function", "to", "be", "called", "when", "messages", "are", "re...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L113-L147
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.subscription_callback
def subscription_callback(self, subscription): """Retrieve the callback function for a subscription. Raise a workflows.Error if the subscription does not exist. All transport callbacks can be intercepted by setting an interceptor function with subscription_callback_intercept(). :...
python
def subscription_callback(self, subscription): """Retrieve the callback function for a subscription. Raise a workflows.Error if the subscription does not exist. All transport callbacks can be intercepted by setting an interceptor function with subscription_callback_intercept(). :...
[ "def", "subscription_callback", "(", "self", ",", "subscription", ")", ":", "subscription_record", "=", "self", ".", "__subscriptions", ".", "get", "(", "subscription", ")", "if", "not", "subscription_record", ":", "raise", "workflows", ".", "Error", "(", "\"Att...
Retrieve the callback function for a subscription. Raise a workflows.Error if the subscription does not exist. All transport callbacks can be intercepted by setting an interceptor function with subscription_callback_intercept(). :param subscription: Subscription ID to look up :re...
[ "Retrieve", "the", "callback", "function", "for", "a", "subscription", ".", "Raise", "a", "workflows", ".", "Error", "if", "the", "subscription", "does", "not", "exist", ".", "All", "transport", "callbacks", "can", "be", "intercepted", "by", "setting", "an", ...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L149-L163
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.send
def send(self, destination, message, **kwargs): """Send a message to a queue. :param destination: Queue name to send to :param message: Either a string or a serializable object to be sent :param **kwargs: Further parameters for the transport layer. For example delay: Delay...
python
def send(self, destination, message, **kwargs): """Send a message to a queue. :param destination: Queue name to send to :param message: Either a string or a serializable object to be sent :param **kwargs: Further parameters for the transport layer. For example delay: Delay...
[ "def", "send", "(", "self", ",", "destination", ",", "message", ",", "*", "*", "kwargs", ")", ":", "message", "=", "self", ".", "_mangle_for_sending", "(", "message", ")", "self", ".", "_send", "(", "destination", ",", "message", ",", "*", "*", "kwargs...
Send a message to a queue. :param destination: Queue name to send to :param message: Either a string or a serializable object to be sent :param **kwargs: Further parameters for the transport layer. For example delay: Delay transport of message by this many seconds h...
[ "Send", "a", "message", "to", "a", "queue", ".", ":", "param", "destination", ":", "Queue", "name", "to", "send", "to", ":", "param", "message", ":", "Either", "a", "string", "or", "a", "serializable", "object", "to", "be", "sent", ":", "param", "**", ...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L175-L187
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.raw_send
def raw_send(self, destination, message, **kwargs): """Send a raw (unmangled) message to a queue. This may cause errors if the receiver expects a mangled message. :param destination: Queue name to send to :param message: Either a string or a serializable object to be sent :param ...
python
def raw_send(self, destination, message, **kwargs): """Send a raw (unmangled) message to a queue. This may cause errors if the receiver expects a mangled message. :param destination: Queue name to send to :param message: Either a string or a serializable object to be sent :param ...
[ "def", "raw_send", "(", "self", ",", "destination", ",", "message", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_send", "(", "destination", ",", "message", ",", "*", "*", "kwargs", ")" ]
Send a raw (unmangled) message to a queue. This may cause errors if the receiver expects a mangled message. :param destination: Queue name to send to :param message: Either a string or a serializable object to be sent :param **kwargs: Further parameters for the transport layer. For examp...
[ "Send", "a", "raw", "(", "unmangled", ")", "message", "to", "a", "queue", ".", "This", "may", "cause", "errors", "if", "the", "receiver", "expects", "a", "mangled", "message", ".", ":", "param", "destination", ":", "Queue", "name", "to", "send", "to", ...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L189-L201
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.broadcast
def broadcast(self, destination, message, **kwargs): """Broadcast a message. :param destination: Topic name to send to :param message: Either a string or a serializable object to be sent :param **kwargs: Further parameters for the transport layer. For example delay: Delay ...
python
def broadcast(self, destination, message, **kwargs): """Broadcast a message. :param destination: Topic name to send to :param message: Either a string or a serializable object to be sent :param **kwargs: Further parameters for the transport layer. For example delay: Delay ...
[ "def", "broadcast", "(", "self", ",", "destination", ",", "message", ",", "*", "*", "kwargs", ")", ":", "message", "=", "self", ".", "_mangle_for_sending", "(", "message", ")", "self", ".", "_broadcast", "(", "destination", ",", "message", ",", "*", "*",...
Broadcast a message. :param destination: Topic name to send to :param message: Either a string or a serializable object to be sent :param **kwargs: Further parameters for the transport layer. For example delay: Delay transport of message by this many seconds headers...
[ "Broadcast", "a", "message", ".", ":", "param", "destination", ":", "Topic", "name", "to", "send", "to", ":", "param", "message", ":", "Either", "a", "string", "or", "a", "serializable", "object", "to", "be", "sent", ":", "param", "**", "kwargs", ":", ...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L203-L215
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.raw_broadcast
def raw_broadcast(self, destination, message, **kwargs): """Broadcast a raw (unmangled) message. This may cause errors if the receiver expects a mangled message. :param destination: Topic name to send to :param message: Either a string or a serializable object to be sent :param *...
python
def raw_broadcast(self, destination, message, **kwargs): """Broadcast a raw (unmangled) message. This may cause errors if the receiver expects a mangled message. :param destination: Topic name to send to :param message: Either a string or a serializable object to be sent :param *...
[ "def", "raw_broadcast", "(", "self", ",", "destination", ",", "message", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_broadcast", "(", "destination", ",", "message", ",", "*", "*", "kwargs", ")" ]
Broadcast a raw (unmangled) message. This may cause errors if the receiver expects a mangled message. :param destination: Topic name to send to :param message: Either a string or a serializable object to be sent :param **kwargs: Further parameters for the transport layer. For example ...
[ "Broadcast", "a", "raw", "(", "unmangled", ")", "message", ".", "This", "may", "cause", "errors", "if", "the", "receiver", "expects", "a", "mangled", "message", ".", ":", "param", "destination", ":", "Topic", "name", "to", "send", "to", ":", "param", "me...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L217-L229
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.ack
def ack(self, message, subscription_id=None, **kwargs): """Acknowledge receipt of a message. This only makes sense when the 'acknowledgement' flag was set for the relevant subscription. :param message: ID of the message to be acknowledged, OR a dictionary containing a fie...
python
def ack(self, message, subscription_id=None, **kwargs): """Acknowledge receipt of a message. This only makes sense when the 'acknowledgement' flag was set for the relevant subscription. :param message: ID of the message to be acknowledged, OR a dictionary containing a fie...
[ "def", "ack", "(", "self", ",", "message", ",", "subscription_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "message", ",", "dict", ")", ":", "message_id", "=", "message", ".", "get", "(", "\"message-id\"", ")", "if", ...
Acknowledge receipt of a message. This only makes sense when the 'acknowledgement' flag was set for the relevant subscription. :param message: ID of the message to be acknowledged, OR a dictionary containing a field 'message-id'. :param subscription_id: ID of the associat...
[ "Acknowledge", "receipt", "of", "a", "message", ".", "This", "only", "makes", "sense", "when", "the", "acknowledgement", "flag", "was", "set", "for", "the", "relevant", "subscription", ".", ":", "param", "message", ":", "ID", "of", "the", "message", "to", ...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L231-L258
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.nack
def nack(self, message, subscription_id=None, **kwargs): """Reject receipt of a message. This only makes sense when the 'acknowledgement' flag was set for the relevant subscription. :param message: ID of the message to be rejected, OR a dictionary containing a field 'mess...
python
def nack(self, message, subscription_id=None, **kwargs): """Reject receipt of a message. This only makes sense when the 'acknowledgement' flag was set for the relevant subscription. :param message: ID of the message to be rejected, OR a dictionary containing a field 'mess...
[ "def", "nack", "(", "self", ",", "message", ",", "subscription_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "message", ",", "dict", ")", ":", "message_id", "=", "message", ".", "get", "(", "\"message-id\"", ")", "if", ...
Reject receipt of a message. This only makes sense when the 'acknowledgement' flag was set for the relevant subscription. :param message: ID of the message to be rejected, OR a dictionary containing a field 'message-id'. :param subscription_id: ID of the associated subscr...
[ "Reject", "receipt", "of", "a", "message", ".", "This", "only", "makes", "sense", "when", "the", "acknowledgement", "flag", "was", "set", "for", "the", "relevant", "subscription", ".", ":", "param", "message", ":", "ID", "of", "the", "message", "to", "be",...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L260-L285
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.transaction_begin
def transaction_begin(self, **kwargs): """Start a new transaction. :param **kwargs: Further parameters for the transport layer. For example :return: A transaction ID that can be passed to other functions. """ self.__transaction_id += 1 self.__transactions.add(self.__trans...
python
def transaction_begin(self, **kwargs): """Start a new transaction. :param **kwargs: Further parameters for the transport layer. For example :return: A transaction ID that can be passed to other functions. """ self.__transaction_id += 1 self.__transactions.add(self.__trans...
[ "def", "transaction_begin", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "__transaction_id", "+=", "1", "self", ".", "__transactions", ".", "add", "(", "self", ".", "__transaction_id", ")", "self", ".", "log", ".", "debug", "(", "\"Starti...
Start a new transaction. :param **kwargs: Further parameters for the transport layer. For example :return: A transaction ID that can be passed to other functions.
[ "Start", "a", "new", "transaction", ".", ":", "param", "**", "kwargs", ":", "Further", "parameters", "for", "the", "transport", "layer", ".", "For", "example", ":", "return", ":", "A", "transaction", "ID", "that", "can", "be", "passed", "to", "other", "f...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L287-L296
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.transaction_abort
def transaction_abort(self, transaction_id, **kwargs): """Abort a transaction and roll back all operations. :param transaction_id: ID of transaction to be aborted. :param **kwargs: Further parameters for the transport layer. """ if transaction_id not in self.__transactions: ...
python
def transaction_abort(self, transaction_id, **kwargs): """Abort a transaction and roll back all operations. :param transaction_id: ID of transaction to be aborted. :param **kwargs: Further parameters for the transport layer. """ if transaction_id not in self.__transactions: ...
[ "def", "transaction_abort", "(", "self", ",", "transaction_id", ",", "*", "*", "kwargs", ")", ":", "if", "transaction_id", "not", "in", "self", ".", "__transactions", ":", "raise", "workflows", ".", "Error", "(", "\"Attempting to abort unknown transaction\"", ")",...
Abort a transaction and roll back all operations. :param transaction_id: ID of transaction to be aborted. :param **kwargs: Further parameters for the transport layer.
[ "Abort", "a", "transaction", "and", "roll", "back", "all", "operations", ".", ":", "param", "transaction_id", ":", "ID", "of", "transaction", "to", "be", "aborted", ".", ":", "param", "**", "kwargs", ":", "Further", "parameters", "for", "the", "transport", ...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L298-L307
DiamondLightSource/python-workflows
workflows/transport/common_transport.py
CommonTransport.transaction_commit
def transaction_commit(self, transaction_id, **kwargs): """Commit a transaction. :param transaction_id: ID of transaction to be committed. :param **kwargs: Further parameters for the transport layer. """ if transaction_id not in self.__transactions: raise workflows.Er...
python
def transaction_commit(self, transaction_id, **kwargs): """Commit a transaction. :param transaction_id: ID of transaction to be committed. :param **kwargs: Further parameters for the transport layer. """ if transaction_id not in self.__transactions: raise workflows.Er...
[ "def", "transaction_commit", "(", "self", ",", "transaction_id", ",", "*", "*", "kwargs", ")", ":", "if", "transaction_id", "not", "in", "self", ".", "__transactions", ":", "raise", "workflows", ".", "Error", "(", "\"Attempting to commit unknown transaction\"", ")...
Commit a transaction. :param transaction_id: ID of transaction to be committed. :param **kwargs: Further parameters for the transport layer.
[ "Commit", "a", "transaction", ".", ":", "param", "transaction_id", ":", "ID", "of", "transaction", "to", "be", "committed", ".", ":", "param", "**", "kwargs", ":", "Further", "parameters", "for", "the", "transport", "layer", "." ]
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L309-L318
cuihantao/andes
andes/filters/matpower.py
read
def read(file, system): """Read a MATPOWER data file into mpc and build andes device elements""" func = re.compile('function\\s') mva = re.compile('\\s*mpc.baseMVA\\s*=\\s*') bus = re.compile('\\s*mpc.bus\\s*=\\s*\\[') gen = re.compile('\\s*mpc.gen\\s*=\\s*\\[') branch = re.compile('\\s*mpc.bran...
python
def read(file, system): """Read a MATPOWER data file into mpc and build andes device elements""" func = re.compile('function\\s') mva = re.compile('\\s*mpc.baseMVA\\s*=\\s*') bus = re.compile('\\s*mpc.bus\\s*=\\s*\\[') gen = re.compile('\\s*mpc.gen\\s*=\\s*\\[') branch = re.compile('\\s*mpc.bran...
[ "def", "read", "(", "file", ",", "system", ")", ":", "func", "=", "re", ".", "compile", "(", "'function\\\\s'", ")", "mva", "=", "re", ".", "compile", "(", "'\\\\s*mpc.baseMVA\\\\s*=\\\\s*'", ")", "bus", "=", "re", ".", "compile", "(", "'\\\\s*mpc.bus\\\\s...
Read a MATPOWER data file into mpc and build andes device elements
[ "Read", "a", "MATPOWER", "data", "file", "into", "mpc", "and", "build", "andes", "device", "elements" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/matpower.py#L14-L250
cuihantao/andes
andes/models/shunt.py
Shunt.full_y
def full_y(self, Y): """Add self(shunt) into full Jacobian Y""" if not self.n: return Ysh = matrix(self.g, (self.n, 1), 'd') + 1j * matrix(self.b, (self.n, 1), 'd') uYsh = mul(self.u, Ysh) Y += spmatrix(uYsh, self.a, self.a, Y.size, 'z')
python
def full_y(self, Y): """Add self(shunt) into full Jacobian Y""" if not self.n: return Ysh = matrix(self.g, (self.n, 1), 'd') + 1j * matrix(self.b, (self.n, 1), 'd') uYsh = mul(self.u, Ysh) Y += spmatrix(uYsh, self.a, self.a, Y.size, 'z')
[ "def", "full_y", "(", "self", ",", "Y", ")", ":", "if", "not", "self", ".", "n", ":", "return", "Ysh", "=", "matrix", "(", "self", ".", "g", ",", "(", "self", ".", "n", ",", "1", ")", ",", "'d'", ")", "+", "1j", "*", "matrix", "(", "self", ...
Add self(shunt) into full Jacobian Y
[ "Add", "self", "(", "shunt", ")", "into", "full", "Jacobian", "Y" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/shunt.py#L51-L58
cuihantao/andes
andes/models/jit.py
JIT.jit_load
def jit_load(self): """ Import and instantiate this JIT object Returns ------- """ try: model = importlib.import_module('.' + self.model, 'andes.models') device = getattr(model, self.device) self.system.__dict__[self.name] = device(se...
python
def jit_load(self): """ Import and instantiate this JIT object Returns ------- """ try: model = importlib.import_module('.' + self.model, 'andes.models') device = getattr(model, self.device) self.system.__dict__[self.name] = device(se...
[ "def", "jit_load", "(", "self", ")", ":", "try", ":", "model", "=", "importlib", ".", "import_module", "(", "'.'", "+", "self", ".", "model", ",", "'andes.models'", ")", "device", "=", "getattr", "(", "model", ",", "self", ".", "device", ")", "self", ...
Import and instantiate this JIT object Returns -------
[ "Import", "and", "instantiate", "this", "JIT", "object" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/jit.py#L20-L49
cuihantao/andes
andes/models/jit.py
JIT.elem_add
def elem_add(self, idx=None, name=None, **kwargs): """overloading elem_add function of a JIT class""" self.jit_load() if self.loaded: return self.system.__dict__[self.name].elem_add( idx, name, **kwargs)
python
def elem_add(self, idx=None, name=None, **kwargs): """overloading elem_add function of a JIT class""" self.jit_load() if self.loaded: return self.system.__dict__[self.name].elem_add( idx, name, **kwargs)
[ "def", "elem_add", "(", "self", ",", "idx", "=", "None", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "jit_load", "(", ")", "if", "self", ".", "loaded", ":", "return", "self", ".", "system", ".", "__dict__", "[", "sel...
overloading elem_add function of a JIT class
[ "overloading", "elem_add", "function", "of", "a", "JIT", "class" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/jit.py#L56-L61
DiamondLightSource/python-workflows
workflows/services/sample_transaction.py
SampleTxn.initializing
def initializing(self): """Subscribe to a channel. Received messages must be acknowledged.""" self.subid = self._transport.subscribe( "transient.transaction", self.receive_message, acknowledgement=True )
python
def initializing(self): """Subscribe to a channel. Received messages must be acknowledged.""" self.subid = self._transport.subscribe( "transient.transaction", self.receive_message, acknowledgement=True )
[ "def", "initializing", "(", "self", ")", ":", "self", ".", "subid", "=", "self", ".", "_transport", ".", "subscribe", "(", "\"transient.transaction\"", ",", "self", ".", "receive_message", ",", "acknowledgement", "=", "True", ")" ]
Subscribe to a channel. Received messages must be acknowledged.
[ "Subscribe", "to", "a", "channel", ".", "Received", "messages", "must", "be", "acknowledged", "." ]
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/sample_transaction.py#L19-L23
DiamondLightSource/python-workflows
workflows/services/sample_transaction.py
SampleTxn.receive_message
def receive_message(self, header, message): """Receive a message""" print("=== Receive ===") print(header) print(message) print("MsgID: {0}".format(header["message-id"])) assert header["message-id"] txn = self._transport.transaction_begin() print(" 1. T...
python
def receive_message(self, header, message): """Receive a message""" print("=== Receive ===") print(header) print(message) print("MsgID: {0}".format(header["message-id"])) assert header["message-id"] txn = self._transport.transaction_begin() print(" 1. T...
[ "def", "receive_message", "(", "self", ",", "header", ",", "message", ")", ":", "print", "(", "\"=== Receive ===\"", ")", "print", "(", "header", ")", "print", "(", "message", ")", "print", "(", "\"MsgID: {0}\"", ".", "format", "(", "header", "[", "\"messa...
Receive a message
[ "Receive", "a", "message" ]
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/sample_transaction.py#L31-L65
DiamondLightSource/python-workflows
workflows/services/sample_transaction.py
SampleTxnProducer.create_message
def create_message(self): """Create and send a unique message for this service.""" self.counter += 1 self._transport.send( "transient.transaction", "TXMessage #%d\n++++++++Produced@ %f" % (self.counter, (time.time() % 1000) * 1000), ) self.log....
python
def create_message(self): """Create and send a unique message for this service.""" self.counter += 1 self._transport.send( "transient.transaction", "TXMessage #%d\n++++++++Produced@ %f" % (self.counter, (time.time() % 1000) * 1000), ) self.log....
[ "def", "create_message", "(", "self", ")", ":", "self", ".", "counter", "+=", "1", "self", ".", "_transport", ".", "send", "(", "\"transient.transaction\"", ",", "\"TXMessage #%d\\n++++++++Produced@ %f\"", "%", "(", "self", ".", "counter", ",", "(", "time", "....
Create and send a unique message for this service.
[ "Create", "and", "send", "a", "unique", "message", "for", "this", "service", "." ]
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/sample_transaction.py#L85-L93
cuihantao/andes
andes/utils/time.py
elapsed
def elapsed(t0=0.0): """get elapsed time from the give time Returns: now: the absolute time now dt_str: elapsed time in string """ now = time() dt = now - t0 dt_sec = Decimal(str(dt)).quantize(Decimal('.0001'), rounding=ROUND_DOWN) if dt_sec <= 1: dt_str = str(dt...
python
def elapsed(t0=0.0): """get elapsed time from the give time Returns: now: the absolute time now dt_str: elapsed time in string """ now = time() dt = now - t0 dt_sec = Decimal(str(dt)).quantize(Decimal('.0001'), rounding=ROUND_DOWN) if dt_sec <= 1: dt_str = str(dt...
[ "def", "elapsed", "(", "t0", "=", "0.0", ")", ":", "now", "=", "time", "(", ")", "dt", "=", "now", "-", "t0", "dt_sec", "=", "Decimal", "(", "str", "(", "dt", ")", ")", ".", "quantize", "(", "Decimal", "(", "'.0001'", ")", ",", "rounding", "=",...
get elapsed time from the give time Returns: now: the absolute time now dt_str: elapsed time in string
[ "get", "elapsed", "time", "from", "the", "give", "time" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/time.py#L5-L19
cuihantao/andes
andes/models/pss.py
PSS1.set_flag
def set_flag(self, value, flag, reset_val=False): """Set a flag to 0 if the corresponding value is 0""" if not self.__dict__[flag]: self.__dict__[flag] = matrix(1.0, (len(self.__dict__[value]), 1), 'd') for idx, item in enumerate(self.__dict__...
python
def set_flag(self, value, flag, reset_val=False): """Set a flag to 0 if the corresponding value is 0""" if not self.__dict__[flag]: self.__dict__[flag] = matrix(1.0, (len(self.__dict__[value]), 1), 'd') for idx, item in enumerate(self.__dict__...
[ "def", "set_flag", "(", "self", ",", "value", ",", "flag", ",", "reset_val", "=", "False", ")", ":", "if", "not", "self", ".", "__dict__", "[", "flag", "]", ":", "self", ".", "__dict__", "[", "flag", "]", "=", "matrix", "(", "1.0", ",", "(", "len...
Set a flag to 0 if the corresponding value is 0
[ "Set", "a", "flag", "to", "0", "if", "the", "corresponding", "value", "is", "0" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/pss.py#L139-L148
cuihantao/andes
andes/variables/report.py
Report._update_summary
def _update_summary(self, system): """ Update the summary data Parameters ---------- system Returns ------- None """ self.basic.update({ 'nbus': system.Bus.n, 'ngen': system.PV.n + system.SW.n, 'ngen_on...
python
def _update_summary(self, system): """ Update the summary data Parameters ---------- system Returns ------- None """ self.basic.update({ 'nbus': system.Bus.n, 'ngen': system.PV.n + system.SW.n, 'ngen_on...
[ "def", "_update_summary", "(", "self", ",", "system", ")", ":", "self", ".", "basic", ".", "update", "(", "{", "'nbus'", ":", "system", ".", "Bus", ".", "n", ",", "'ngen'", ":", "system", ".", "PV", ".", "n", "+", "system", ".", "SW", ".", "n", ...
Update the summary data Parameters ---------- system Returns ------- None
[ "Update", "the", "summary", "data" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/report.py#L64-L85
cuihantao/andes
andes/variables/report.py
Report._update_extended
def _update_extended(self, system): """Update the extended data""" if self.system.pflow.solved is False: logger.warning( 'Cannot update extended summary. Power flow not solved.') return Sloss = sum(system.Line.S1 + system.Line.S2) self.extended.up...
python
def _update_extended(self, system): """Update the extended data""" if self.system.pflow.solved is False: logger.warning( 'Cannot update extended summary. Power flow not solved.') return Sloss = sum(system.Line.S1 + system.Line.S2) self.extended.up...
[ "def", "_update_extended", "(", "self", ",", "system", ")", ":", "if", "self", ".", "system", ".", "pflow", ".", "solved", "is", "False", ":", "logger", ".", "warning", "(", "'Cannot update extended summary. Power flow not solved.'", ")", "return", "Sloss", "=",...
Update the extended data
[ "Update", "the", "extended", "data" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/report.py#L87-L128
cuihantao/andes
andes/variables/report.py
Report.update
def update(self, content=None): """ Update values based on the requested content Parameters ---------- content Returns ------- """ if not content: return if content == 'summary' or 'extended' or 'powerflow': self....
python
def update(self, content=None): """ Update values based on the requested content Parameters ---------- content Returns ------- """ if not content: return if content == 'summary' or 'extended' or 'powerflow': self....
[ "def", "update", "(", "self", ",", "content", "=", "None", ")", ":", "if", "not", "content", ":", "return", "if", "content", "==", "'summary'", "or", "'extended'", "or", "'powerflow'", ":", "self", ".", "_update_summary", "(", "self", ".", "system", ")",...
Update values based on the requested content Parameters ---------- content Returns -------
[ "Update", "values", "based", "on", "the", "requested", "content" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/report.py#L130-L147
cuihantao/andes
andes/variables/report.py
Report.write
def write(self, content=None): """ Write report to file. Parameters ---------- content: str 'summary', 'extended', 'powerflow' """ if self.system.files.no_output is True: return t, _ = elapsed() if not content: ...
python
def write(self, content=None): """ Write report to file. Parameters ---------- content: str 'summary', 'extended', 'powerflow' """ if self.system.files.no_output is True: return t, _ = elapsed() if not content: ...
[ "def", "write", "(", "self", ",", "content", "=", "None", ")", ":", "if", "self", ".", "system", ".", "files", ".", "no_output", "is", "True", ":", "return", "t", ",", "_", "=", "elapsed", "(", ")", "if", "not", "content", ":", "logger", ".", "wa...
Write report to file. Parameters ---------- content: str 'summary', 'extended', 'powerflow'
[ "Write", "report", "to", "file", "." ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/report.py#L149-L264
DiamondLightSource/python-workflows
workflows/recipe/wrapper.py
RecipeWrapper.send
def send(self, *args, **kwargs): """Send messages to another service that is connected to the currently running service via the recipe. The 'send' method will either use a default channel name, set via the set_default_channel method, or an unnamed output definition. """ i...
python
def send(self, *args, **kwargs): """Send messages to another service that is connected to the currently running service via the recipe. The 'send' method will either use a default channel name, set via the set_default_channel method, or an unnamed output definition. """ i...
[ "def", "send", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "transport", ":", "raise", "ValueError", "(", "\"This RecipeWrapper object does not contain \"", "\"a reference to a transport object.\"", ")", "if", "not", ...
Send messages to another service that is connected to the currently running service via the recipe. The 'send' method will either use a default channel name, set via the set_default_channel method, or an unnamed output definition.
[ "Send", "messages", "to", "another", "service", "that", "is", "connected", "to", "the", "currently", "running", "service", "via", "the", "recipe", ".", "The", "send", "method", "will", "either", "use", "a", "default", "channel", "name", "set", "via", "the", ...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L40-L70
DiamondLightSource/python-workflows
workflows/recipe/wrapper.py
RecipeWrapper.start
def start(self, header=None, **kwargs): """Trigger the start of a recipe, sending the defined payloads to the recipients set in the recipe. Any parameters to this function are passed to the transport send/broadcast methods. If the wrapped recipe has already been started then a ValueError...
python
def start(self, header=None, **kwargs): """Trigger the start of a recipe, sending the defined payloads to the recipients set in the recipe. Any parameters to this function are passed to the transport send/broadcast methods. If the wrapped recipe has already been started then a ValueError...
[ "def", "start", "(", "self", ",", "header", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "transport", ":", "raise", "ValueError", "(", "\"This RecipeWrapper object does not contain \"", "\"a reference to a transport object.\"", ")", "i...
Trigger the start of a recipe, sending the defined payloads to the recipients set in the recipe. Any parameters to this function are passed to the transport send/broadcast methods. If the wrapped recipe has already been started then a ValueError will be raised.
[ "Trigger", "the", "start", "of", "a", "recipe", "sending", "the", "defined", "payloads", "to", "the", "recipients", "set", "in", "the", "recipe", ".", "Any", "parameters", "to", "this", "function", "are", "passed", "to", "the", "transport", "send", "/", "b...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L111-L128
DiamondLightSource/python-workflows
workflows/recipe/wrapper.py
RecipeWrapper.checkpoint
def checkpoint(self, message, header=None, delay=0, **kwargs): """Send a message to the current recipe destination. This can be used to keep a state for longer processing tasks. :param delay: Delay transport of message by this many seconds """ if not self.transport: r...
python
def checkpoint(self, message, header=None, delay=0, **kwargs): """Send a message to the current recipe destination. This can be used to keep a state for longer processing tasks. :param delay: Delay transport of message by this many seconds """ if not self.transport: r...
[ "def", "checkpoint", "(", "self", ",", "message", ",", "header", "=", "None", ",", "delay", "=", "0", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "transport", ":", "raise", "ValueError", "(", "\"This RecipeWrapper object does not contain \""...
Send a message to the current recipe destination. This can be used to keep a state for longer processing tasks. :param delay: Delay transport of message by this many seconds
[ "Send", "a", "message", "to", "the", "current", "recipe", "destination", ".", "This", "can", "be", "used", "to", "keep", "a", "state", "for", "longer", "processing", "tasks", ".", ":", "param", "delay", ":", "Delay", "transport", "of", "message", "by", "...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L130-L151
DiamondLightSource/python-workflows
workflows/recipe/wrapper.py
RecipeWrapper.apply_parameters
def apply_parameters(self, parameters): """Recursively apply parameter replacement (see recipe.py) to the wrapped recipe, updating internal references afterwards. While this operation is useful for testing it should not be used in production. Replacing parameters means that the recipe ch...
python
def apply_parameters(self, parameters): """Recursively apply parameter replacement (see recipe.py) to the wrapped recipe, updating internal references afterwards. While this operation is useful for testing it should not be used in production. Replacing parameters means that the recipe ch...
[ "def", "apply_parameters", "(", "self", ",", "parameters", ")", ":", "self", ".", "recipe", ".", "apply_parameters", "(", "parameters", ")", "self", ".", "recipe_step", "=", "self", ".", "recipe", "[", "self", ".", "recipe_pointer", "]" ]
Recursively apply parameter replacement (see recipe.py) to the wrapped recipe, updating internal references afterwards. While this operation is useful for testing it should not be used in production. Replacing parameters means that the recipe changes as it is passed down the chain of ser...
[ "Recursively", "apply", "parameter", "replacement", "(", "see", "recipe", ".", "py", ")", "to", "the", "wrapped", "recipe", "updating", "internal", "references", "afterwards", ".", "While", "this", "operation", "is", "useful", "for", "testing", "it", "should", ...
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L153-L161
DiamondLightSource/python-workflows
workflows/recipe/wrapper.py
RecipeWrapper._generate_full_recipe_message
def _generate_full_recipe_message(self, destination, message, add_path_step): """Factory function to generate independent message objects for downstream recipients with different destinations.""" if add_path_step and self.recipe_pointer: recipe_path = self.recipe_path + [self.recipe_...
python
def _generate_full_recipe_message(self, destination, message, add_path_step): """Factory function to generate independent message objects for downstream recipients with different destinations.""" if add_path_step and self.recipe_pointer: recipe_path = self.recipe_path + [self.recipe_...
[ "def", "_generate_full_recipe_message", "(", "self", ",", "destination", ",", "message", ",", "add_path_step", ")", ":", "if", "add_path_step", "and", "self", ".", "recipe_pointer", ":", "recipe_path", "=", "self", ".", "recipe_path", "+", "[", "self", ".", "r...
Factory function to generate independent message objects for downstream recipients with different destinations.
[ "Factory", "function", "to", "generate", "independent", "message", "objects", "for", "downstream", "recipients", "with", "different", "destinations", "." ]
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L163-L177
DiamondLightSource/python-workflows
workflows/recipe/wrapper.py
RecipeWrapper._send_to_destinations
def _send_to_destinations(self, destinations, message, header=None, **kwargs): """Send messages to a list of numbered destinations. This is an internal helper method used by the public 'send' methods. """ if not isinstance(destinations, list): destinations = (destinations,) ...
python
def _send_to_destinations(self, destinations, message, header=None, **kwargs): """Send messages to a list of numbered destinations. This is an internal helper method used by the public 'send' methods. """ if not isinstance(destinations, list): destinations = (destinations,) ...
[ "def", "_send_to_destinations", "(", "self", ",", "destinations", ",", "message", ",", "header", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "destinations", ",", "list", ")", ":", "destinations", "=", "(", "destinations"...
Send messages to a list of numbered destinations. This is an internal helper method used by the public 'send' methods.
[ "Send", "messages", "to", "a", "list", "of", "numbered", "destinations", ".", "This", "is", "an", "internal", "helper", "method", "used", "by", "the", "public", "send", "methods", "." ]
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L179-L186
DiamondLightSource/python-workflows
workflows/recipe/wrapper.py
RecipeWrapper._send_to_destination
def _send_to_destination( self, destination, header, payload, transport_kwargs, add_path_step=True ): """Helper function to send a message to a specific recipe destination.""" if header: header = header.copy() header["workflows-recipe"] = True else: ...
python
def _send_to_destination( self, destination, header, payload, transport_kwargs, add_path_step=True ): """Helper function to send a message to a specific recipe destination.""" if header: header = header.copy() header["workflows-recipe"] = True else: ...
[ "def", "_send_to_destination", "(", "self", ",", "destination", ",", "header", ",", "payload", ",", "transport_kwargs", ",", "add_path_step", "=", "True", ")", ":", "if", "header", ":", "header", "=", "header", ".", "copy", "(", ")", "header", "[", "\"work...
Helper function to send a message to a specific recipe destination.
[ "Helper", "function", "to", "send", "a", "message", "to", "a", "specific", "recipe", "destination", "." ]
train
https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L188-L217
Legobot/Legobot
Legobot/Connectors/Slack.py
RtmBot.on_message
def on_message(self, event): '''Runs when a message event is received Args: event: RTM API event. Returns: Legobot.messge ''' metadata = self._parse_metadata(event) message = Message(text=metadata['text'], metadata=meta...
python
def on_message(self, event): '''Runs when a message event is received Args: event: RTM API event. Returns: Legobot.messge ''' metadata = self._parse_metadata(event) message = Message(text=metadata['text'], metadata=meta...
[ "def", "on_message", "(", "self", ",", "event", ")", ":", "metadata", "=", "self", ".", "_parse_metadata", "(", "event", ")", "message", "=", "Message", "(", "text", "=", "metadata", "[", "'text'", "]", ",", "metadata", "=", "metadata", ")", ".", "__di...
Runs when a message event is received Args: event: RTM API event. Returns: Legobot.messge
[ "Runs", "when", "a", "message", "event", "is", "received" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L75-L93
Legobot/Legobot
Legobot/Connectors/Slack.py
RtmBot.run
def run(self): '''Extends the run() method of threading.Thread ''' self.connect() while True: for event in self.slack_client.rtm_read(): logger.debug(event) if 'type' in event and event['type'] in self.supported_events: eve...
python
def run(self): '''Extends the run() method of threading.Thread ''' self.connect() while True: for event in self.slack_client.rtm_read(): logger.debug(event) if 'type' in event and event['type'] in self.supported_events: eve...
[ "def", "run", "(", "self", ")", ":", "self", ".", "connect", "(", ")", "while", "True", ":", "for", "event", "in", "self", ".", "slack_client", ".", "rtm_read", "(", ")", ":", "logger", ".", "debug", "(", "event", ")", "if", "'type'", "in", "event"...
Extends the run() method of threading.Thread
[ "Extends", "the", "run", "()", "method", "of", "threading", ".", "Thread" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L95-L111
Legobot/Legobot
Legobot/Connectors/Slack.py
RtmBot.find_and_replace_userids
def find_and_replace_userids(self, text): '''Finds occurrences of Slack userids and attempts to replace them with display names. Args: text (string): The message text Returns: string: The message text with userids replaced. ''' match = True ...
python
def find_and_replace_userids(self, text): '''Finds occurrences of Slack userids and attempts to replace them with display names. Args: text (string): The message text Returns: string: The message text with userids replaced. ''' match = True ...
[ "def", "find_and_replace_userids", "(", "self", ",", "text", ")", ":", "match", "=", "True", "pattern", "=", "re", ".", "compile", "(", "'<@([A-Z0-9]{9})>'", ")", "while", "match", ":", "match", "=", "pattern", ".", "search", "(", "text", ")", "if", "mat...
Finds occurrences of Slack userids and attempts to replace them with display names. Args: text (string): The message text Returns: string: The message text with userids replaced.
[ "Finds", "occurrences", "of", "Slack", "userids", "and", "attempts", "to", "replace", "them", "with", "display", "names", "." ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L113-L131
Legobot/Legobot
Legobot/Connectors/Slack.py
RtmBot.find_and_replace_channel_refs
def find_and_replace_channel_refs(self, text): '''Find occurrences of Slack channel referenfces and attempts to replace them with just channel names. Args: text (string): The message text Returns: string: The message text with channel references replaced. ...
python
def find_and_replace_channel_refs(self, text): '''Find occurrences of Slack channel referenfces and attempts to replace them with just channel names. Args: text (string): The message text Returns: string: The message text with channel references replaced. ...
[ "def", "find_and_replace_channel_refs", "(", "self", ",", "text", ")", ":", "match", "=", "True", "pattern", "=", "re", ".", "compile", "(", "'<#([A-Z0-9]{9})\\|([A-Za-z0-9-]+)>'", ")", "while", "match", ":", "match", "=", "pattern", ".", "search", "(", "text"...
Find occurrences of Slack channel referenfces and attempts to replace them with just channel names. Args: text (string): The message text Returns: string: The message text with channel references replaced.
[ "Find", "occurrences", "of", "Slack", "channel", "referenfces", "and", "attempts", "to", "replace", "them", "with", "just", "channel", "names", "." ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L133-L150
Legobot/Legobot
Legobot/Connectors/Slack.py
RtmBot.get_channels
def get_channels(self, condensed=False): '''Grabs all channels in the slack team Args: condensed (bool): if true triggers list condensing functionality Returns: dic: Dict of channels in Slack team. See also: https://api.slack.com/methods/channels.list ...
python
def get_channels(self, condensed=False): '''Grabs all channels in the slack team Args: condensed (bool): if true triggers list condensing functionality Returns: dic: Dict of channels in Slack team. See also: https://api.slack.com/methods/channels.list ...
[ "def", "get_channels", "(", "self", ",", "condensed", "=", "False", ")", ":", "channel_list", "=", "self", ".", "slack_client", ".", "api_call", "(", "'channels.list'", ")", "if", "not", "channel_list", ".", "get", "(", "'ok'", ")", ":", "return", "None", ...
Grabs all channels in the slack team Args: condensed (bool): if true triggers list condensing functionality Returns: dic: Dict of channels in Slack team. See also: https://api.slack.com/methods/channels.list
[ "Grabs", "all", "channels", "in", "the", "slack", "team" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L182-L202
Legobot/Legobot
Legobot/Connectors/Slack.py
RtmBot.get_users
def get_users(self, condensed=False): '''Grabs all users in the slack team This should should only be used for getting list of all users. Do not use it for searching users. Use get_user_info instead. Args: condensed (bool): if true triggers list condensing functionality ...
python
def get_users(self, condensed=False): '''Grabs all users in the slack team This should should only be used for getting list of all users. Do not use it for searching users. Use get_user_info instead. Args: condensed (bool): if true triggers list condensing functionality ...
[ "def", "get_users", "(", "self", ",", "condensed", "=", "False", ")", ":", "user_list", "=", "self", ".", "slack_client", ".", "api_call", "(", "'users.list'", ")", "if", "not", "user_list", ".", "get", "(", "'ok'", ")", ":", "return", "None", "if", "c...
Grabs all users in the slack team This should should only be used for getting list of all users. Do not use it for searching users. Use get_user_info instead. Args: condensed (bool): if true triggers list condensing functionality Returns: dict: Dict of users in...
[ "Grabs", "all", "users", "in", "the", "slack", "team" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L204-L227
Legobot/Legobot
Legobot/Connectors/Slack.py
RtmBot.get_user_display_name
def get_user_display_name(self, userid): '''Given a Slack userid, grabs user display_name from api. Args: userid (string): the user id of the user being queried Returns: dict: a dictionary of the api response ''' user_info = self.slack_client.api_call('u...
python
def get_user_display_name(self, userid): '''Given a Slack userid, grabs user display_name from api. Args: userid (string): the user id of the user being queried Returns: dict: a dictionary of the api response ''' user_info = self.slack_client.api_call('u...
[ "def", "get_user_display_name", "(", "self", ",", "userid", ")", ":", "user_info", "=", "self", ".", "slack_client", ".", "api_call", "(", "'users.info'", ",", "user", "=", "userid", ")", "if", "user_info", ".", "get", "(", "'ok'", ")", ":", "user", "=",...
Given a Slack userid, grabs user display_name from api. Args: userid (string): the user id of the user being queried Returns: dict: a dictionary of the api response
[ "Given", "a", "Slack", "userid", "grabs", "user", "display_name", "from", "api", "." ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L229-L246
Legobot/Legobot
Legobot/Connectors/Slack.py
RtmBot.get_dm_channel
def get_dm_channel(self, userid): '''Perform a lookup of users to resolve a userid to a DM channel Args: userid (string): Slack userid to lookup. Returns: string: DM channel ID of user ''' dm_open = self.slack_client.api_call('im.open', user=userid) ...
python
def get_dm_channel(self, userid): '''Perform a lookup of users to resolve a userid to a DM channel Args: userid (string): Slack userid to lookup. Returns: string: DM channel ID of user ''' dm_open = self.slack_client.api_call('im.open', user=userid) ...
[ "def", "get_dm_channel", "(", "self", ",", "userid", ")", ":", "dm_open", "=", "self", ".", "slack_client", ".", "api_call", "(", "'im.open'", ",", "user", "=", "userid", ")", "return", "dm_open", "[", "'channel'", "]", "[", "'id'", "]" ]
Perform a lookup of users to resolve a userid to a DM channel Args: userid (string): Slack userid to lookup. Returns: string: DM channel ID of user
[ "Perform", "a", "lookup", "of", "users", "to", "resolve", "a", "userid", "to", "a", "DM", "channel" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L248-L259
Legobot/Legobot
Legobot/Connectors/Slack.py
RtmBot.get_username
def get_username(self, userid): '''Perform a lookup of users to resolve a userid to a username Args: userid (string): Slack userid to lookup. Returns: string: Human-friendly name of the user ''' username = self.user_map.get(userid) if not userna...
python
def get_username(self, userid): '''Perform a lookup of users to resolve a userid to a username Args: userid (string): Slack userid to lookup. Returns: string: Human-friendly name of the user ''' username = self.user_map.get(userid) if not userna...
[ "def", "get_username", "(", "self", ",", "userid", ")", ":", "username", "=", "self", ".", "user_map", ".", "get", "(", "userid", ")", "if", "not", "username", ":", "users", "=", "self", ".", "get_users", "(", ")", "if", "users", ":", "members", "=",...
Perform a lookup of users to resolve a userid to a username Args: userid (string): Slack userid to lookup. Returns: string: Human-friendly name of the user
[ "Perform", "a", "lookup", "of", "users", "to", "resolve", "a", "userid", "to", "a", "username" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L264-L289
Legobot/Legobot
Legobot/Connectors/Slack.py
RtmBot.get_userid_from_botid
def get_userid_from_botid(self, botid): '''Perform a lookup of bots.info to resolve a botid to a userid Args: botid (string): Slack botid to lookup. Returns: string: userid value ''' botinfo = self.slack_client.api_call('bots.info', bot=botid) if ...
python
def get_userid_from_botid(self, botid): '''Perform a lookup of bots.info to resolve a botid to a userid Args: botid (string): Slack botid to lookup. Returns: string: userid value ''' botinfo = self.slack_client.api_call('bots.info', bot=botid) if ...
[ "def", "get_userid_from_botid", "(", "self", ",", "botid", ")", ":", "botinfo", "=", "self", ".", "slack_client", ".", "api_call", "(", "'bots.info'", ",", "bot", "=", "botid", ")", "if", "botinfo", "[", "'ok'", "]", "is", "True", ":", "return", "botinfo...
Perform a lookup of bots.info to resolve a botid to a userid Args: botid (string): Slack botid to lookup. Returns: string: userid value
[ "Perform", "a", "lookup", "of", "bots", ".", "info", "to", "resolve", "a", "botid", "to", "a", "userid" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L291-L303
Legobot/Legobot
Legobot/Connectors/Slack.py
RtmBot._parse_metadata
def _parse_metadata(self, message): '''Parse incoming messages to build metadata dict Lots of 'if' statements. It sucks, I know. Args: message (dict): JSON dump of message sent from Slack Returns: Legobot.Metadata ''' # Try to handle all the fie...
python
def _parse_metadata(self, message): '''Parse incoming messages to build metadata dict Lots of 'if' statements. It sucks, I know. Args: message (dict): JSON dump of message sent from Slack Returns: Legobot.Metadata ''' # Try to handle all the fie...
[ "def", "_parse_metadata", "(", "self", ",", "message", ")", ":", "# Try to handle all the fields of events we care about.", "metadata", "=", "Metadata", "(", "source", "=", "self", ".", "actor_urn", ")", ".", "__dict__", "metadata", "[", "'thread_ts'", "]", "=", "...
Parse incoming messages to build metadata dict Lots of 'if' statements. It sucks, I know. Args: message (dict): JSON dump of message sent from Slack Returns: Legobot.Metadata
[ "Parse", "incoming", "messages", "to", "build", "metadata", "dict", "Lots", "of", "if", "statements", ".", "It", "sucks", "I", "know", "." ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L305-L356
Legobot/Legobot
Legobot/Connectors/Slack.py
Slack.build_attachment
def build_attachment(self, text, target, attachment, thread): '''Builds a slack attachment. Args: message (Legobot.Message): message w/ metadata to send. Returns: attachment (dict): attachment data. ''' attachment = { 'as_user': True, ...
python
def build_attachment(self, text, target, attachment, thread): '''Builds a slack attachment. Args: message (Legobot.Message): message w/ metadata to send. Returns: attachment (dict): attachment data. ''' attachment = { 'as_user': True, ...
[ "def", "build_attachment", "(", "self", ",", "text", ",", "target", ",", "attachment", ",", "thread", ")", ":", "attachment", "=", "{", "'as_user'", ":", "True", ",", "'text'", ":", "text", ",", "'channel'", ":", "target", ",", "'attachments'", ":", "[",...
Builds a slack attachment. Args: message (Legobot.Message): message w/ metadata to send. Returns: attachment (dict): attachment data.
[ "Builds", "a", "slack", "attachment", "." ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L403-L426
Legobot/Legobot
Legobot/Connectors/Slack.py
Slack.handle
def handle(self, message): '''Attempts to send a message to the specified destination in Slack. Extends Legobot.Lego.handle() Args: message (Legobot.Message): message w/ metadata to send. ''' logger.debug(message) if Utilities.isNotEmpty(message['metadata'][...
python
def handle(self, message): '''Attempts to send a message to the specified destination in Slack. Extends Legobot.Lego.handle() Args: message (Legobot.Message): message w/ metadata to send. ''' logger.debug(message) if Utilities.isNotEmpty(message['metadata'][...
[ "def", "handle", "(", "self", ",", "message", ")", ":", "logger", ".", "debug", "(", "message", ")", "if", "Utilities", ".", "isNotEmpty", "(", "message", "[", "'metadata'", "]", "[", "'opts'", "]", ")", ":", "target", "=", "message", "[", "'metadata'"...
Attempts to send a message to the specified destination in Slack. Extends Legobot.Lego.handle() Args: message (Legobot.Message): message w/ metadata to send.
[ "Attempts", "to", "send", "a", "message", "to", "the", "specified", "destination", "in", "Slack", ".", "Extends", "Legobot", ".", "Lego", ".", "handle", "()" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L428-L487
cuihantao/andes
andes/filters/__init__.py
guess
def guess(system): """ input format guess function. First guess by extension, then test by lines """ files = system.files maybe = [] if files.input_format: maybe.append(files.input_format) # first, guess by extension for key, val in input_formats.items(): if type(val) == ...
python
def guess(system): """ input format guess function. First guess by extension, then test by lines """ files = system.files maybe = [] if files.input_format: maybe.append(files.input_format) # first, guess by extension for key, val in input_formats.items(): if type(val) == ...
[ "def", "guess", "(", "system", ")", ":", "files", "=", "system", ".", "files", "maybe", "=", "[", "]", "if", "files", ".", "input_format", ":", "maybe", ".", "append", "(", "files", ".", "input_format", ")", "# first, guess by extension", "for", "key", "...
input format guess function. First guess by extension, then test by lines
[ "input", "format", "guess", "function", ".", "First", "guess", "by", "extension", "then", "test", "by", "lines" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/__init__.py#L32-L85
cuihantao/andes
andes/filters/__init__.py
parse
def parse(system): """ Parse input file with the given format in system.files.input_format """ t, _ = elapsed() input_format = system.files.input_format add_format = system.files.add_format # exit when no input format is given if not input_format: logger.error( 'No ...
python
def parse(system): """ Parse input file with the given format in system.files.input_format """ t, _ = elapsed() input_format = system.files.input_format add_format = system.files.add_format # exit when no input format is given if not input_format: logger.error( 'No ...
[ "def", "parse", "(", "system", ")", ":", "t", ",", "_", "=", "elapsed", "(", ")", "input_format", "=", "system", ".", "files", ".", "input_format", "add_format", "=", "system", ".", "files", ".", "add_format", "# exit when no input format is given", "if", "n...
Parse input file with the given format in system.files.input_format
[ "Parse", "input", "file", "with", "the", "given", "format", "in", "system", ".", "files", ".", "input_format" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/__init__.py#L88-L151
cuihantao/andes
andes/routines/eig.py
EIG.calc_state_matrix
def calc_state_matrix(self): """ Return state matrix and store to ``self.As`` Returns ------- matrix state matrix """ system = self.system Gyx = matrix(system.dae.Gx) self.solver.linsolve(system.dae.Gy, Gyx) self.As = matrix(...
python
def calc_state_matrix(self): """ Return state matrix and store to ``self.As`` Returns ------- matrix state matrix """ system = self.system Gyx = matrix(system.dae.Gx) self.solver.linsolve(system.dae.Gy, Gyx) self.As = matrix(...
[ "def", "calc_state_matrix", "(", "self", ")", ":", "system", "=", "self", ".", "system", "Gyx", "=", "matrix", "(", "system", ".", "dae", ".", "Gx", ")", "self", ".", "solver", ".", "linsolve", "(", "system", ".", "dae", ".", "Gy", ",", "Gyx", ")",...
Return state matrix and store to ``self.As`` Returns ------- matrix state matrix
[ "Return", "state", "matrix", "and", "store", "to", "self", ".", "As" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/eig.py#L39-L63
cuihantao/andes
andes/routines/eig.py
EIG.calc_eigvals
def calc_eigvals(self): """ Solve eigenvalues of the state matrix ``self.As`` Returns ------- None """ self.eigs = numpy.linalg.eigvals(self.As) # TODO: use scipy.sparse.linalg.eigs(self.As) return self.eigs
python
def calc_eigvals(self): """ Solve eigenvalues of the state matrix ``self.As`` Returns ------- None """ self.eigs = numpy.linalg.eigvals(self.As) # TODO: use scipy.sparse.linalg.eigs(self.As) return self.eigs
[ "def", "calc_eigvals", "(", "self", ")", ":", "self", ".", "eigs", "=", "numpy", ".", "linalg", ".", "eigvals", "(", "self", ".", "As", ")", "# TODO: use scipy.sparse.linalg.eigs(self.As)", "return", "self", ".", "eigs" ]
Solve eigenvalues of the state matrix ``self.As`` Returns ------- None
[ "Solve", "eigenvalues", "of", "the", "state", "matrix", "self", ".", "As" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/eig.py#L65-L76
cuihantao/andes
andes/routines/eig.py
EIG.calc_part_factor
def calc_part_factor(self): """ Compute participation factor of states in eigenvalues Returns ------- """ mu, N = numpy.linalg.eig(self.As) # TODO: use scipy.sparse.linalg.eigs(self.As) N = matrix(N) n = len(mu) idx = range(n) W...
python
def calc_part_factor(self): """ Compute participation factor of states in eigenvalues Returns ------- """ mu, N = numpy.linalg.eig(self.As) # TODO: use scipy.sparse.linalg.eigs(self.As) N = matrix(N) n = len(mu) idx = range(n) W...
[ "def", "calc_part_factor", "(", "self", ")", ":", "mu", ",", "N", "=", "numpy", ".", "linalg", ".", "eig", "(", "self", ".", "As", ")", "# TODO: use scipy.sparse.linalg.eigs(self.As)", "N", "=", "matrix", "(", "N", ")", "n", "=", "len", "(", "mu", ")",...
Compute participation factor of states in eigenvalues Returns -------
[ "Compute", "participation", "factor", "of", "states", "in", "eigenvalues" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/eig.py#L78-L112
cuihantao/andes
andes/routines/eig.py
EIG.dump_results
def dump_results(self): """ Save eigenvalue analysis reports Returns ------- None """ system = self.system mu = self.mu partfact = self.part_fact if system.files.no_output: return text = [] header = [] ...
python
def dump_results(self): """ Save eigenvalue analysis reports Returns ------- None """ system = self.system mu = self.mu partfact = self.part_fact if system.files.no_output: return text = [] header = [] ...
[ "def", "dump_results", "(", "self", ")", ":", "system", "=", "self", ".", "system", "mu", "=", "self", ".", "mu", "partfact", "=", "self", ".", "part_fact", "if", "system", ".", "files", ".", "no_output", ":", "return", "text", "=", "[", "]", "header...
Save eigenvalue analysis reports Returns ------- None
[ "Save", "eigenvalue", "analysis", "reports" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/eig.py#L186-L286
cuihantao/andes
andes/models/breaker.py
Breaker.get_times
def get_times(self): """Return all the action times and times-1e-6 in a list""" if not self.n: return [] self.times = list(mul(self.u1, self.t1)) + \ list(mul(self.u2, self.t2)) + \ list(mul(self.u3, self.t3)) + \ list(mul(self.u4, self.t4)) ...
python
def get_times(self): """Return all the action times and times-1e-6 in a list""" if not self.n: return [] self.times = list(mul(self.u1, self.t1)) + \ list(mul(self.u2, self.t2)) + \ list(mul(self.u3, self.t3)) + \ list(mul(self.u4, self.t4)) ...
[ "def", "get_times", "(", "self", ")", ":", "if", "not", "self", ".", "n", ":", "return", "[", "]", "self", ".", "times", "=", "list", "(", "mul", "(", "self", ".", "u1", ",", "self", ".", "t1", ")", ")", "+", "list", "(", "mul", "(", "self", ...
Return all the action times and times-1e-6 in a list
[ "Return", "all", "the", "action", "times", "and", "times", "-", "1e", "-", "6", "in", "a", "list" ]
train
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/breaker.py#L75-L86
Legobot/Legobot
Legobot/Connectors/Discord.py
Heartbeat.send
def send(self, ws, seq): """ Sends heartbeat message to Discord Attributes: ws: Websocket connection to discord seq: Sequence number of heartbeat """ payload = {'op': 1, 'd': seq} payload = json.dumps(payload) logger.debug("Sending heartb...
python
def send(self, ws, seq): """ Sends heartbeat message to Discord Attributes: ws: Websocket connection to discord seq: Sequence number of heartbeat """ payload = {'op': 1, 'd': seq} payload = json.dumps(payload) logger.debug("Sending heartb...
[ "def", "send", "(", "self", ",", "ws", ",", "seq", ")", ":", "payload", "=", "{", "'op'", ":", "1", ",", "'d'", ":", "seq", "}", "payload", "=", "json", ".", "dumps", "(", "payload", ")", "logger", ".", "debug", "(", "\"Sending heartbeat with payload...
Sends heartbeat message to Discord Attributes: ws: Websocket connection to discord seq: Sequence number of heartbeat
[ "Sends", "heartbeat", "message", "to", "Discord" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L37-L50
Legobot/Legobot
Legobot/Connectors/Discord.py
DiscoBot.create_message
def create_message(self, channel_id, text): """ Sends a message to a Discord channel or user via REST API Args: channel_id (string): ID of destingation Discord channel text (string): Content of message """ baseurl = self.rest_baseurl + \ '/ch...
python
def create_message(self, channel_id, text): """ Sends a message to a Discord channel or user via REST API Args: channel_id (string): ID of destingation Discord channel text (string): Content of message """ baseurl = self.rest_baseurl + \ '/ch...
[ "def", "create_message", "(", "self", ",", "channel_id", ",", "text", ")", ":", "baseurl", "=", "self", ".", "rest_baseurl", "+", "'/channels/{}/messages'", ".", "format", "(", "channel_id", ")", "requests", ".", "post", "(", "baseurl", ",", "headers", "=", ...
Sends a message to a Discord channel or user via REST API Args: channel_id (string): ID of destingation Discord channel text (string): Content of message
[ "Sends", "a", "message", "to", "a", "Discord", "channel", "or", "user", "via", "REST", "API" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L109-L122
Legobot/Legobot
Legobot/Connectors/Discord.py
DiscoBot.identify
def identify(self, token): """ Identifies to the websocket endpoint Args: token (string): Discord bot token """ payload = { 'op': 2, 'd': { 'token': self.token, 'properties': { '$os': sys.pl...
python
def identify(self, token): """ Identifies to the websocket endpoint Args: token (string): Discord bot token """ payload = { 'op': 2, 'd': { 'token': self.token, 'properties': { '$os': sys.pl...
[ "def", "identify", "(", "self", ",", "token", ")", ":", "payload", "=", "{", "'op'", ":", "2", ",", "'d'", ":", "{", "'token'", ":", "self", ".", "token", ",", "'properties'", ":", "{", "'$os'", ":", "sys", ".", "platform", ",", "'$browser'", ":", ...
Identifies to the websocket endpoint Args: token (string): Discord bot token
[ "Identifies", "to", "the", "websocket", "endpoint" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L124-L149
Legobot/Legobot
Legobot/Connectors/Discord.py
DiscoBot.on_hello
def on_hello(self, message): """ Runs on a hello event from websocket connection Args: message (dict): Full message from Discord websocket connection" """ logger.info("Got a hello") self.identify(self.token) self.heartbeat_thread = Heartbeat(self.ws,...
python
def on_hello(self, message): """ Runs on a hello event from websocket connection Args: message (dict): Full message from Discord websocket connection" """ logger.info("Got a hello") self.identify(self.token) self.heartbeat_thread = Heartbeat(self.ws,...
[ "def", "on_hello", "(", "self", ",", "message", ")", ":", "logger", ".", "info", "(", "\"Got a hello\"", ")", "self", ".", "identify", "(", "self", ".", "token", ")", "self", ".", "heartbeat_thread", "=", "Heartbeat", "(", "self", ".", "ws", ",", "mess...
Runs on a hello event from websocket connection Args: message (dict): Full message from Discord websocket connection"
[ "Runs", "on", "a", "hello", "event", "from", "websocket", "connection" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L151-L164
Legobot/Legobot
Legobot/Connectors/Discord.py
DiscoBot.on_heartbeat
def on_heartbeat(self, message): """ Runs on a heartbeat event from websocket connection Args: message (dict): Full message from Discord websocket connection" """ logger.info("Got a heartbeat") logger.info("Heartbeat message: {}".format(message)) sel...
python
def on_heartbeat(self, message): """ Runs on a heartbeat event from websocket connection Args: message (dict): Full message from Discord websocket connection" """ logger.info("Got a heartbeat") logger.info("Heartbeat message: {}".format(message)) sel...
[ "def", "on_heartbeat", "(", "self", ",", "message", ")", ":", "logger", ".", "info", "(", "\"Got a heartbeat\"", ")", "logger", ".", "info", "(", "\"Heartbeat message: {}\"", ".", "format", "(", "message", ")", ")", "self", ".", "heartbeat_thread", ".", "upd...
Runs on a heartbeat event from websocket connection Args: message (dict): Full message from Discord websocket connection"
[ "Runs", "on", "a", "heartbeat", "event", "from", "websocket", "connection" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L166-L177
Legobot/Legobot
Legobot/Connectors/Discord.py
DiscoBot.on_message
def on_message(self, message): """ Runs on a create_message event from websocket connection Args: message (dict): Full message from Discord websocket connection" """ if 'content' in message['d']: metadata = self._parse_metadata(message) messa...
python
def on_message(self, message): """ Runs on a create_message event from websocket connection Args: message (dict): Full message from Discord websocket connection" """ if 'content' in message['d']: metadata = self._parse_metadata(message) messa...
[ "def", "on_message", "(", "self", ",", "message", ")", ":", "if", "'content'", "in", "message", "[", "'d'", "]", ":", "metadata", "=", "self", ".", "_parse_metadata", "(", "message", ")", "message", "=", "Message", "(", "text", "=", "message", "[", "'d...
Runs on a create_message event from websocket connection Args: message (dict): Full message from Discord websocket connection"
[ "Runs", "on", "a", "create_message", "event", "from", "websocket", "connection" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L179-L192
Legobot/Legobot
Legobot/Connectors/Discord.py
DiscoBot._parse_metadata
def _parse_metadata(self, message): """ Sets metadata in Legobot message Args: message (dict): Full message from Discord websocket connection" Returns: Legobot.Metadata """ metadata = Metadata(source=self.actor_urn).__dict__ if 'author' ...
python
def _parse_metadata(self, message): """ Sets metadata in Legobot message Args: message (dict): Full message from Discord websocket connection" Returns: Legobot.Metadata """ metadata = Metadata(source=self.actor_urn).__dict__ if 'author' ...
[ "def", "_parse_metadata", "(", "self", ",", "message", ")", ":", "metadata", "=", "Metadata", "(", "source", "=", "self", ".", "actor_urn", ")", ".", "__dict__", "if", "'author'", "in", "message", "[", "'d'", "]", ":", "metadata", "[", "'source_user'", "...
Sets metadata in Legobot message Args: message (dict): Full message from Discord websocket connection" Returns: Legobot.Metadata
[ "Sets", "metadata", "in", "Legobot", "message" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L194-L219
Legobot/Legobot
Legobot/Connectors/Discord.py
DiscoBot.handle
def handle(self, message): """ Dispatches messages to appropriate handler based on opcode Args: message (dict): Full message from Discord websocket connection """ opcode = message['op'] if opcode == 10: self.on_hello(message) elif opcode ...
python
def handle(self, message): """ Dispatches messages to appropriate handler based on opcode Args: message (dict): Full message from Discord websocket connection """ opcode = message['op'] if opcode == 10: self.on_hello(message) elif opcode ...
[ "def", "handle", "(", "self", ",", "message", ")", ":", "opcode", "=", "message", "[", "'op'", "]", "if", "opcode", "==", "10", ":", "self", ".", "on_hello", "(", "message", ")", "elif", "opcode", "==", "11", ":", "self", ".", "on_heartbeat", "(", ...
Dispatches messages to appropriate handler based on opcode Args: message (dict): Full message from Discord websocket connection
[ "Dispatches", "messages", "to", "appropriate", "handler", "based", "on", "opcode" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L227-L244
Legobot/Legobot
Legobot/Connectors/Discord.py
DiscoBot.run
def run(self): """ Overrides run method of threading.Thread. Called by DiscoBot.start(), inherited from threading.Thread """ self.ws = self.connect() while True: try: data = json.loads(self.ws.recv()) self.handle(data) ...
python
def run(self): """ Overrides run method of threading.Thread. Called by DiscoBot.start(), inherited from threading.Thread """ self.ws = self.connect() while True: try: data = json.loads(self.ws.recv()) self.handle(data) ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "ws", "=", "self", ".", "connect", "(", ")", "while", "True", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "self", ".", "ws", ".", "recv", "(", ")", ")", "self", ".", "handle", "("...
Overrides run method of threading.Thread. Called by DiscoBot.start(), inherited from threading.Thread
[ "Overrides", "run", "method", "of", "threading", ".", "Thread", ".", "Called", "by", "DiscoBot", ".", "start", "()", "inherited", "from", "threading", ".", "Thread" ]
train
https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L246-L258