nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
ospalh/anki-addons
4ece13423bd541e29d9b40ebe26ca0999a6962b1
add_kanji_embeds.py
python
kanji_svg_rest
(txt, *args)
return kanji_svg_var(txt, show_rest=True)
Copy the variant kanji. ...
Copy the variant kanji.
[ "Copy", "the", "variant", "kanji", "." ]
def kanji_svg_rest(txt, *args): """ Copy the variant kanji. ... """ return kanji_svg_var(txt, show_rest=True)
[ "def", "kanji_svg_rest", "(", "txt", ",", "*", "args", ")", ":", "return", "kanji_svg_var", "(", "txt", ",", "show_rest", "=", "True", ")" ]
https://github.com/ospalh/anki-addons/blob/4ece13423bd541e29d9b40ebe26ca0999a6962b1/add_kanji_embeds.py#L117-L123
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/python27/1.0/lib/logging/__init__.py
python
debug
(msg, *args, **kwargs)
Log a message with severity 'DEBUG' on the root logger.
Log a message with severity 'DEBUG' on the root logger.
[ "Log", "a", "message", "with", "severity", "DEBUG", "on", "the", "root", "logger", "." ]
def debug(msg, *args, **kwargs): """ Log a message with severity 'DEBUG' on the root logger. """ if len(root.handlers) == 0: basicConfig() root.debug(msg, *args, **kwargs)
[ "def", "debug", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "root", ".", "handlers", ")", "==", "0", ":", "basicConfig", "(", ")", "root", ".", "debug", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/python27/1.0/lib/logging/__init__.py#L1623-L1629
xgi/castero
766965fb1d3586d62ab6fd6dd144fa510c1e0ecb
castero/perspectives/primaryperspective.py
python
PrimaryPerspective.display
(self)
Draws all windows and sub-features, including titles and borders.
Draws all windows and sub-features, including titles and borders.
[ "Draws", "all", "windows", "and", "sub", "-", "features", "including", "titles", "and", "borders", "." ]
def display(self) -> None: """Draws all windows and sub-features, including titles and borders.""" # clear dynamic menu headers self._feed_window.addstr(0, 0, " " * self._feed_window.getmaxyx()[1]) self._episode_window.addstr(0, 0, " " * self._episode_window.getmaxyx()[1]) # add window headers self._feed_window.addstr(0, 0, self._feed_menu.title, curses.color_pair(7) | curses.A_BOLD) self._episode_window.addstr(0, 0, self._episode_menu.title, curses.color_pair(7) | curses.A_BOLD) self._metadata_window.addstr(0, 0, "Metadata", curses.color_pair(7) | curses.A_BOLD) # add window borders self._feed_window.hline( 1, 0, 0, self._feed_window.getmaxyx()[1], curses.ACS_HLINE | curses.color_pair(8) ) self._episode_window.hline( 1, 0, 0, self._episode_window.getmaxyx()[1], curses.ACS_HLINE | curses.color_pair(8) ) self._metadata_window.hline( 1, 0, 0, self._metadata_window.getmaxyx()[1] - 1, curses.ACS_HLINE | curses.color_pair(8) ) if not helpers.is_true(Config["disable_vertical_borders"]): self._feed_window.vline( 0, self._feed_window.getmaxyx()[1] - 1, 0, self._feed_window.getmaxyx()[0] - 2, curses.ACS_VLINE | curses.color_pair(8), ) self._episode_window.vline( 0, self._episode_window.getmaxyx()[1] - 1, 0, self._episode_window.getmaxyx()[0] - 2, curses.ACS_VLINE | curses.color_pair(8), ) # draw metadata if not self._metadata_updated: self._draw_metadata(self._metadata_window) self._metadata_window.refresh() self._metadata_updated = True self._feed_window.refresh() self._episode_window.refresh()
[ "def", "display", "(", "self", ")", "->", "None", ":", "# clear dynamic menu headers", "self", ".", "_feed_window", ".", "addstr", "(", "0", ",", "0", ",", "\" \"", "*", "self", ".", "_feed_window", ".", "getmaxyx", "(", ")", "[", "1", "]", ")", "self", ".", "_episode_window", ".", "addstr", "(", "0", ",", "0", ",", "\" \"", "*", "self", ".", "_episode_window", ".", "getmaxyx", "(", ")", "[", "1", "]", ")", "# add window headers", "self", ".", "_feed_window", ".", "addstr", "(", "0", ",", "0", ",", "self", ".", "_feed_menu", ".", "title", ",", "curses", ".", "color_pair", "(", "7", ")", "|", "curses", ".", "A_BOLD", ")", "self", ".", "_episode_window", ".", "addstr", "(", "0", ",", "0", ",", "self", ".", "_episode_menu", ".", "title", ",", "curses", ".", "color_pair", "(", "7", ")", "|", "curses", ".", "A_BOLD", ")", "self", ".", "_metadata_window", ".", "addstr", "(", "0", ",", "0", ",", "\"Metadata\"", ",", "curses", ".", "color_pair", "(", "7", ")", "|", "curses", ".", "A_BOLD", ")", "# add window borders", "self", ".", "_feed_window", ".", "hline", "(", "1", ",", "0", ",", "0", ",", "self", ".", "_feed_window", ".", "getmaxyx", "(", ")", "[", "1", "]", ",", "curses", ".", "ACS_HLINE", "|", "curses", ".", "color_pair", "(", "8", ")", ")", "self", ".", "_episode_window", ".", "hline", "(", "1", ",", "0", ",", "0", ",", "self", ".", "_episode_window", ".", "getmaxyx", "(", ")", "[", "1", "]", ",", "curses", ".", "ACS_HLINE", "|", "curses", ".", "color_pair", "(", "8", ")", ")", "self", ".", "_metadata_window", ".", "hline", "(", "1", ",", "0", ",", "0", ",", "self", ".", "_metadata_window", ".", "getmaxyx", "(", ")", "[", "1", "]", "-", "1", ",", "curses", ".", "ACS_HLINE", "|", "curses", ".", "color_pair", "(", "8", ")", ")", "if", "not", "helpers", ".", "is_true", "(", "Config", "[", "\"disable_vertical_borders\"", "]", ")", ":", "self", ".", "_feed_window", ".", "vline", "(", "0", ",", "self", ".", "_feed_window", ".", "getmaxyx", "(", ")", "[", "1", "]", "-", "1", ",", "0", ",", "self", ".", "_feed_window", ".", "getmaxyx", "(", ")", "[", "0", "]", "-", "2", ",", "curses", ".", "ACS_VLINE", "|", "curses", ".", "color_pair", "(", "8", ")", ",", ")", "self", ".", "_episode_window", ".", "vline", "(", "0", ",", "self", ".", "_episode_window", ".", "getmaxyx", "(", ")", "[", "1", "]", "-", "1", ",", "0", ",", "self", ".", "_episode_window", ".", "getmaxyx", "(", ")", "[", "0", "]", "-", "2", ",", "curses", ".", "ACS_VLINE", "|", "curses", ".", "color_pair", "(", "8", ")", ",", ")", "# draw metadata", "if", "not", "self", ".", "_metadata_updated", ":", "self", ".", "_draw_metadata", "(", "self", ".", "_metadata_window", ")", "self", ".", "_metadata_window", ".", "refresh", "(", ")", "self", ".", "_metadata_updated", "=", "True", "self", ".", "_feed_window", ".", "refresh", "(", ")", "self", ".", "_episode_window", ".", "refresh", "(", ")" ]
https://github.com/xgi/castero/blob/766965fb1d3586d62ab6fd6dd144fa510c1e0ecb/castero/perspectives/primaryperspective.py#L68-L112
meteorshowers/X-StereoLab
d18a61953991d6b2e2bccea9e6e0a504292cd9e9
disparity/eval/kitti-object-eval-python/kitti_common.py
python
iou
(boxes1, boxes2, add1=False)
return intersect / union
Computes pairwise intersection-over-union between box collections. Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwise iou scores.
Computes pairwise intersection-over-union between box collections.
[ "Computes", "pairwise", "intersection", "-", "over", "-", "union", "between", "box", "collections", "." ]
def iou(boxes1, boxes2, add1=False): """Computes pairwise intersection-over-union between box collections. Args: boxes1: a numpy array with shape [N, 4] holding N boxes. boxes2: a numpy array with shape [M, 4] holding N boxes. Returns: a numpy array with shape [N, M] representing pairwise iou scores. """ intersect = intersection(boxes1, boxes2, add1) area1 = area(boxes1, add1) area2 = area(boxes2, add1) union = np.expand_dims( area1, axis=1) + np.expand_dims( area2, axis=0) - intersect return intersect / union
[ "def", "iou", "(", "boxes1", ",", "boxes2", ",", "add1", "=", "False", ")", ":", "intersect", "=", "intersection", "(", "boxes1", ",", "boxes2", ",", "add1", ")", "area1", "=", "area", "(", "boxes1", ",", "add1", ")", "area2", "=", "area", "(", "boxes2", ",", "add1", ")", "union", "=", "np", ".", "expand_dims", "(", "area1", ",", "axis", "=", "1", ")", "+", "np", ".", "expand_dims", "(", "area2", ",", "axis", "=", "0", ")", "-", "intersect", "return", "intersect", "/", "union" ]
https://github.com/meteorshowers/X-StereoLab/blob/d18a61953991d6b2e2bccea9e6e0a504292cd9e9/disparity/eval/kitti-object-eval-python/kitti_common.py#L402-L418
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/optparse.py
python
OptionContainer.add_option
(self, *args, **kwargs)
return option
add_option(Option) add_option(opt_str, ..., kwarg=val, ...)
add_option(Option) add_option(opt_str, ..., kwarg=val, ...)
[ "add_option", "(", "Option", ")", "add_option", "(", "opt_str", "...", "kwarg", "=", "val", "...", ")" ]
def add_option(self, *args, **kwargs): """add_option(Option) add_option(opt_str, ..., kwarg=val, ...) """ if type(args[0]) in types.StringTypes: option = self.option_class(*args, **kwargs) elif len(args) == 1 and not kwargs: option = args[0] if not isinstance(option, Option): raise TypeError, "not an Option instance: %r" % option else: raise TypeError, "invalid arguments" self._check_conflict(option) self.option_list.append(option) option.container = self for opt in option._short_opts: self._short_opt[opt] = option for opt in option._long_opts: self._long_opt[opt] = option if option.dest is not None: # option has a dest, we need a default if option.default is not NO_DEFAULT: self.defaults[option.dest] = option.default elif option.dest not in self.defaults: self.defaults[option.dest] = None return option
[ "def", "add_option", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "type", "(", "args", "[", "0", "]", ")", "in", "types", ".", "StringTypes", ":", "option", "=", "self", ".", "option_class", "(", "*", "args", ",", "*", "*", "kwargs", ")", "elif", "len", "(", "args", ")", "==", "1", "and", "not", "kwargs", ":", "option", "=", "args", "[", "0", "]", "if", "not", "isinstance", "(", "option", ",", "Option", ")", ":", "raise", "TypeError", ",", "\"not an Option instance: %r\"", "%", "option", "else", ":", "raise", "TypeError", ",", "\"invalid arguments\"", "self", ".", "_check_conflict", "(", "option", ")", "self", ".", "option_list", ".", "append", "(", "option", ")", "option", ".", "container", "=", "self", "for", "opt", "in", "option", ".", "_short_opts", ":", "self", ".", "_short_opt", "[", "opt", "]", "=", "option", "for", "opt", "in", "option", ".", "_long_opts", ":", "self", ".", "_long_opt", "[", "opt", "]", "=", "option", "if", "option", ".", "dest", "is", "not", "None", ":", "# option has a dest, we need a default", "if", "option", ".", "default", "is", "not", "NO_DEFAULT", ":", "self", ".", "defaults", "[", "option", ".", "dest", "]", "=", "option", ".", "default", "elif", "option", ".", "dest", "not", "in", "self", ".", "defaults", ":", "self", ".", "defaults", "[", "option", ".", "dest", "]", "=", "None", "return", "option" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/packages/IronPython.StdLib.2.7.4/content/Lib/optparse.py#L1007-L1035
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/plugins/demo.py
python
demo_end
(self, event=None, chain=False)
End the present demo.
End the present demo.
[ "End", "the", "present", "demo", "." ]
def demo_end(self, event=None, chain=False): """End the present demo.""" if getattr(g.app, 'demo', None): g.app.demo.end() else: g.trace('no demo instance')
[ "def", "demo_end", "(", "self", ",", "event", "=", "None", ",", "chain", "=", "False", ")", ":", "if", "getattr", "(", "g", ".", "app", ",", "'demo'", ",", "None", ")", ":", "g", ".", "app", ".", "demo", ".", "end", "(", ")", "else", ":", "g", ".", "trace", "(", "'no demo instance'", ")" ]
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/demo.py#L48-L53
frescobaldi/frescobaldi
301cc977fc4ba7caa3df9e4bf905212ad5d06912
frescobaldi_app/midifile/player.py
python
Player.time_event
(self, msec)
(Private) Called on every time update.
(Private) Called on every time update.
[ "(", "Private", ")", "Called", "on", "every", "time", "update", "." ]
def time_event(self, msec): """(Private) Called on every time update."""
[ "def", "time_event", "(", "self", ",", "msec", ")", ":" ]
https://github.com/frescobaldi/frescobaldi/blob/301cc977fc4ba7caa3df9e4bf905212ad5d06912/frescobaldi_app/midifile/player.py#L237-L238
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/common/lib/python2.7/site-packages/libxml2.py
python
SchemaValidCtxtCore.setValidityErrorHandler
(self, err_func, warn_func, arg=None)
Register error and warning handlers for Schema validation. These will be called back as f(msg,arg)
Register error and warning handlers for Schema validation. These will be called back as f(msg,arg)
[ "Register", "error", "and", "warning", "handlers", "for", "Schema", "validation", ".", "These", "will", "be", "called", "back", "as", "f", "(", "msg", "arg", ")" ]
def setValidityErrorHandler(self, err_func, warn_func, arg=None): """ Register error and warning handlers for Schema validation. These will be called back as f(msg,arg) """ libxml2mod.xmlSchemaSetValidErrors(self._o, err_func, warn_func, arg)
[ "def", "setValidityErrorHandler", "(", "self", ",", "err_func", ",", "warn_func", ",", "arg", "=", "None", ")", ":", "libxml2mod", ".", "xmlSchemaSetValidErrors", "(", "self", ".", "_o", ",", "err_func", ",", "warn_func", ",", "arg", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/common/lib/python2.7/site-packages/libxml2.py#L664-L669
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
examples/pytorch/graphsage/train_cv_multi_gpu.py
python
evaluate
(model, g, labels, val_mask, batch_size, device)
return compute_acc(pred[val_mask], labels[val_mask])
Evaluate the model on the validation set specified by ``val_mask``. g : The entire graph. inputs : The features of all the nodes. labels : The labels of all the nodes. val_mask : A 0-1 mask indicating which nodes do we actually compute the accuracy for. batch_size : Number of nodes to compute at the same time. device : The GPU device to evaluate on.
Evaluate the model on the validation set specified by ``val_mask``. g : The entire graph. inputs : The features of all the nodes. labels : The labels of all the nodes. val_mask : A 0-1 mask indicating which nodes do we actually compute the accuracy for. batch_size : Number of nodes to compute at the same time. device : The GPU device to evaluate on.
[ "Evaluate", "the", "model", "on", "the", "validation", "set", "specified", "by", "val_mask", ".", "g", ":", "The", "entire", "graph", ".", "inputs", ":", "The", "features", "of", "all", "the", "nodes", ".", "labels", ":", "The", "labels", "of", "all", "the", "nodes", ".", "val_mask", ":", "A", "0", "-", "1", "mask", "indicating", "which", "nodes", "do", "we", "actually", "compute", "the", "accuracy", "for", ".", "batch_size", ":", "Number", "of", "nodes", "to", "compute", "at", "the", "same", "time", ".", "device", ":", "The", "GPU", "device", "to", "evaluate", "on", "." ]
def evaluate(model, g, labels, val_mask, batch_size, device): """ Evaluate the model on the validation set specified by ``val_mask``. g : The entire graph. inputs : The features of all the nodes. labels : The labels of all the nodes. val_mask : A 0-1 mask indicating which nodes do we actually compute the accuracy for. batch_size : Number of nodes to compute at the same time. device : The GPU device to evaluate on. """ model.eval() with th.no_grad(): inputs = g.ndata['features'] pred = model.inference(g, inputs, batch_size, device) # also recomputes history tensors model.train() return compute_acc(pred[val_mask], labels[val_mask])
[ "def", "evaluate", "(", "model", ",", "g", ",", "labels", ",", "val_mask", ",", "batch_size", ",", "device", ")", ":", "model", ".", "eval", "(", ")", "with", "th", ".", "no_grad", "(", ")", ":", "inputs", "=", "g", ".", "ndata", "[", "'features'", "]", "pred", "=", "model", ".", "inference", "(", "g", ",", "inputs", ",", "batch_size", ",", "device", ")", "# also recomputes history tensors", "model", ".", "train", "(", ")", "return", "compute_acc", "(", "pred", "[", "val_mask", "]", ",", "labels", "[", "val_mask", "]", ")" ]
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/examples/pytorch/graphsage/train_cv_multi_gpu.py#L155-L170
glitchdotcom/WebPutty
4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7
libs/babel/messages/catalog.py
python
Catalog.__len__
(self)
return len(self._messages)
The number of messages in the catalog. This does not include the special ``msgid ""`` entry.
The number of messages in the catalog.
[ "The", "number", "of", "messages", "in", "the", "catalog", "." ]
def __len__(self): """The number of messages in the catalog. This does not include the special ``msgid ""`` entry. """ return len(self._messages)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_messages", ")" ]
https://github.com/glitchdotcom/WebPutty/blob/4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7/libs/babel/messages/catalog.py#L508-L513
gnuradio/pybombs
17044241bf835b93571026b112f179f2db7448a4
pybombs/commands/deploy.py
python
Deploy.setup_subparser
(parser, cmd=None)
Set up a subparser for 'deploy'
Set up a subparser for 'deploy'
[ "Set", "up", "a", "subparser", "for", "deploy" ]
def setup_subparser(parser, cmd=None): """ Set up a subparser for 'deploy' """ parser.add_argument( 'target', help="Deployment destination", ) parser.add_argument( '-t', '--tar', help="Deploy to .tar", dest="ttype", action='store_const', const='tar', ) parser.add_argument( '-z', '--gzip', help="Deploy to .tar.gz", dest="ttype", action='store_const', const='gzip', ) parser.add_argument( '-j', '--bzip2', help="Deploy to .tar.bz2", dest="ttype", action='store_const', const='bzip2', ) parser.add_argument( '-J', '--xz', help="Deploy to .tar.xz", dest="ttype", action='store_const', const='xz', ) parser.add_argument( '-s', '--ssh', help="Deploy to remote target", dest="ttype", action='store_const', const='ssh', ) parser.add_argument( '--keep-src', help="Include the source directory", action='store_true', ) parser.add_argument( '--keep-config', help="Include the config directory", action='store_true', )
[ "def", "setup_subparser", "(", "parser", ",", "cmd", "=", "None", ")", ":", "parser", ".", "add_argument", "(", "'target'", ",", "help", "=", "\"Deployment destination\"", ",", ")", "parser", ".", "add_argument", "(", "'-t'", ",", "'--tar'", ",", "help", "=", "\"Deploy to .tar\"", ",", "dest", "=", "\"ttype\"", ",", "action", "=", "'store_const'", ",", "const", "=", "'tar'", ",", ")", "parser", ".", "add_argument", "(", "'-z'", ",", "'--gzip'", ",", "help", "=", "\"Deploy to .tar.gz\"", ",", "dest", "=", "\"ttype\"", ",", "action", "=", "'store_const'", ",", "const", "=", "'gzip'", ",", ")", "parser", ".", "add_argument", "(", "'-j'", ",", "'--bzip2'", ",", "help", "=", "\"Deploy to .tar.bz2\"", ",", "dest", "=", "\"ttype\"", ",", "action", "=", "'store_const'", ",", "const", "=", "'bzip2'", ",", ")", "parser", ".", "add_argument", "(", "'-J'", ",", "'--xz'", ",", "help", "=", "\"Deploy to .tar.xz\"", ",", "dest", "=", "\"ttype\"", ",", "action", "=", "'store_const'", ",", "const", "=", "'xz'", ",", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--ssh'", ",", "help", "=", "\"Deploy to remote target\"", ",", "dest", "=", "\"ttype\"", ",", "action", "=", "'store_const'", ",", "const", "=", "'ssh'", ",", ")", "parser", ".", "add_argument", "(", "'--keep-src'", ",", "help", "=", "\"Include the source directory\"", ",", "action", "=", "'store_true'", ",", ")", "parser", ".", "add_argument", "(", "'--keep-config'", ",", "help", "=", "\"Include the config directory\"", ",", "action", "=", "'store_true'", ",", ")" ]
https://github.com/gnuradio/pybombs/blob/17044241bf835b93571026b112f179f2db7448a4/pybombs/commands/deploy.py#L168-L219
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/stat.py
python
filemode
(mode)
return "".join(perm)
Convert a file's mode to a string of the form '-rwxrwxrwx'.
Convert a file's mode to a string of the form '-rwxrwxrwx'.
[ "Convert", "a", "file", "s", "mode", "to", "a", "string", "of", "the", "form", "-", "rwxrwxrwx", "." ]
def filemode(mode): """Convert a file's mode to a string of the form '-rwxrwxrwx'.""" perm = [] for table in _filemode_table: for bit, char in table: if mode & bit == bit: perm.append(char) break else: perm.append("-") return "".join(perm)
[ "def", "filemode", "(", "mode", ")", ":", "perm", "=", "[", "]", "for", "table", "in", "_filemode_table", ":", "for", "bit", ",", "char", "in", "table", ":", "if", "mode", "&", "bit", "==", "bit", ":", "perm", ".", "append", "(", "char", ")", "break", "else", ":", "perm", ".", "append", "(", "\"-\"", ")", "return", "\"\"", ".", "join", "(", "perm", ")" ]
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/stat.py#L139-L149
FORTH-ICS-INSPIRE/artemis
f0774af8abc25ef5c6b307960c048ff7528d8a9c
monitor-services/riperistap/core/ripe_ris.py
python
RipeRisTapDataWorker.__init__
(self, connection, shared_memory_manager_dict)
[]
def __init__(self, connection, shared_memory_manager_dict): self.connection = connection self.shared_memory_manager_dict = shared_memory_manager_dict self.prefixes = self.shared_memory_manager_dict["monitored_prefixes"] self.hosts = self.shared_memory_manager_dict["hosts"] # EXCHANGES self.update_exchange = create_exchange( "bgp-update", self.connection, declare=True ) log.info("data worker initiated")
[ "def", "__init__", "(", "self", ",", "connection", ",", "shared_memory_manager_dict", ")", ":", "self", ".", "connection", "=", "connection", "self", ".", "shared_memory_manager_dict", "=", "shared_memory_manager_dict", "self", ".", "prefixes", "=", "self", ".", "shared_memory_manager_dict", "[", "\"monitored_prefixes\"", "]", "self", ".", "hosts", "=", "self", ".", "shared_memory_manager_dict", "[", "\"hosts\"", "]", "# EXCHANGES", "self", ".", "update_exchange", "=", "create_exchange", "(", "\"bgp-update\"", ",", "self", ".", "connection", ",", "declare", "=", "True", ")", "log", ".", "info", "(", "\"data worker initiated\"", ")" ]
https://github.com/FORTH-ICS-INSPIRE/artemis/blob/f0774af8abc25ef5c6b307960c048ff7528d8a9c/monitor-services/riperistap/core/ripe_ris.py#L370-L381
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/html5lib/html5parser.py
python
HTMLParser.documentEncoding
(self)
return self.tokenizer.stream.charEncoding[0].name
Name of the character encoding that was used to decode the input stream, or :obj:`None` if that is not determined yet
Name of the character encoding that was used to decode the input stream, or :obj:`None` if that is not determined yet
[ "Name", "of", "the", "character", "encoding", "that", "was", "used", "to", "decode", "the", "input", "stream", "or", ":", "obj", ":", "None", "if", "that", "is", "not", "determined", "yet" ]
def documentEncoding(self): """Name of the character encoding that was used to decode the input stream, or :obj:`None` if that is not determined yet """ if not hasattr(self, 'tokenizer'): return None return self.tokenizer.stream.charEncoding[0].name
[ "def", "documentEncoding", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'tokenizer'", ")", ":", "return", "None", "return", "self", ".", "tokenizer", ".", "stream", ".", "charEncoding", "[", "0", "]", ".", "name" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/html5lib/html5parser.py#L173-L180
hyperledger/aries-cloudagent-python
2f36776e99f6053ae92eed8123b5b1b2e891c02a
aries_cloudagent/messaging/agent_message.py
python
AgentMessage.set_signature
(self, field_name: str, signature: SignatureDecorator)
Add or replace the signature for a named field. Args: field_name: Field to set signature on signature: Signature for the field
Add or replace the signature for a named field.
[ "Add", "or", "replace", "the", "signature", "for", "a", "named", "field", "." ]
def set_signature(self, field_name: str, signature: SignatureDecorator): """ Add or replace the signature for a named field. Args: field_name: Field to set signature on signature: Signature for the field """ self._decorators.field(field_name)["sig"] = signature
[ "def", "set_signature", "(", "self", ",", "field_name", ":", "str", ",", "signature", ":", "SignatureDecorator", ")", ":", "self", ".", "_decorators", ".", "field", "(", "field_name", ")", "[", "\"sig\"", "]", "=", "signature" ]
https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/messaging/agent_message.py#L161-L170
uqfoundation/mystic
154e6302d1f2f94e8f13e88ecc5f24241cc28ac7
examples3/ouq.py
python
BaseOUQ.lower_bound
(self, axis=None, **kwds)
return tuple(i.bestEnergy for i in solvers)
find the lower bound on the statistical quantity Input: axis: int, the index of y on which to find bound (all, by default) instance: bool, if True, return the solver instance (False, by default) Additional Input: kwds: dict, with updates to the instance's stored kwds Returns: lower bound on the statistical quantity, for the specified axis
find the lower bound on the statistical quantity
[ "find", "the", "lower", "bound", "on", "the", "statistical", "quantity" ]
def lower_bound(self, axis=None, **kwds): """find the lower bound on the statistical quantity Input: axis: int, the index of y on which to find bound (all, by default) instance: bool, if True, return the solver instance (False, by default) Additional Input: kwds: dict, with updates to the instance's stored kwds Returns: lower bound on the statistical quantity, for the specified axis """ full = kwds.pop('instance', False) #self._lower.clear() #XXX: good idea? if self.axes is None or axis is not None: # solve for lower bound of objective (in measure space) solver = self._lower_bound(axis, **kwds) self._lower[None if self.axes is None else axis] = solver if full: return solver return solver.bestEnergy # else axis is None solvers = self._lower_bound(axis, **kwds) for i,solver in enumerate(solvers): self._lower[i] = solver if full: return solvers return tuple(i.bestEnergy for i in solvers)
[ "def", "lower_bound", "(", "self", ",", "axis", "=", "None", ",", "*", "*", "kwds", ")", ":", "full", "=", "kwds", ".", "pop", "(", "'instance'", ",", "False", ")", "#self._lower.clear() #XXX: good idea?", "if", "self", ".", "axes", "is", "None", "or", "axis", "is", "not", "None", ":", "# solve for lower bound of objective (in measure space)", "solver", "=", "self", ".", "_lower_bound", "(", "axis", ",", "*", "*", "kwds", ")", "self", ".", "_lower", "[", "None", "if", "self", ".", "axes", "is", "None", "else", "axis", "]", "=", "solver", "if", "full", ":", "return", "solver", "return", "solver", ".", "bestEnergy", "# else axis is None", "solvers", "=", "self", ".", "_lower_bound", "(", "axis", ",", "*", "*", "kwds", ")", "for", "i", ",", "solver", "in", "enumerate", "(", "solvers", ")", ":", "self", ".", "_lower", "[", "i", "]", "=", "solver", "if", "full", ":", "return", "solvers", "return", "tuple", "(", "i", ".", "bestEnergy", "for", "i", "in", "solvers", ")" ]
https://github.com/uqfoundation/mystic/blob/154e6302d1f2f94e8f13e88ecc5f24241cc28ac7/examples3/ouq.py#L112-L138
ruiminshen/yolo-tf
eae65c8071fe5069f5e3bb1e26f19a761b1b68bc
detect.py
python
std
(image)
return utils.preprocess.per_image_standardization(image)
[]
def std(image): return utils.preprocess.per_image_standardization(image)
[ "def", "std", "(", "image", ")", ":", "return", "utils", ".", "preprocess", ".", "per_image_standardization", "(", "image", ")" ]
https://github.com/ruiminshen/yolo-tf/blob/eae65c8071fe5069f5e3bb1e26f19a761b1b68bc/detect.py#L33-L34
enthought/traitsui
b7c38c7a47bf6ae7971f9ddab70c8a358647dd25
traitsui/qt4/list_str_editor.py
python
_ListStrEditor._selected_changed
(self, selected)
Handles the editor's 'selected' trait being changed.
Handles the editor's 'selected' trait being changed.
[ "Handles", "the", "editor", "s", "selected", "trait", "being", "changed", "." ]
def _selected_changed(self, selected): """Handles the editor's 'selected' trait being changed.""" if not self._no_update: try: selected_index = self.value.index(selected) except ValueError: pass else: self._selected_index_changed(selected_index)
[ "def", "_selected_changed", "(", "self", ",", "selected", ")", ":", "if", "not", "self", ".", "_no_update", ":", "try", ":", "selected_index", "=", "self", ".", "value", ".", "index", "(", "selected", ")", "except", "ValueError", ":", "pass", "else", ":", "self", ".", "_selected_index_changed", "(", "selected_index", ")" ]
https://github.com/enthought/traitsui/blob/b7c38c7a47bf6ae7971f9ddab70c8a358647dd25/traitsui/qt4/list_str_editor.py#L288-L296
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/crawl/wordnet.py
python
wordnet.crawl
(self, fuzzable_request, debugging_id)
:param debugging_id: A unique identifier for this call to discover() :param fuzzable_request: A fuzzable_request instance that contains (among other things) the URL to test.
:param debugging_id: A unique identifier for this call to discover() :param fuzzable_request: A fuzzable_request instance that contains (among other things) the URL to test.
[ ":", "param", "debugging_id", ":", "A", "unique", "identifier", "for", "this", "call", "to", "discover", "()", ":", "param", "fuzzable_request", ":", "A", "fuzzable_request", "instance", "that", "contains", "(", "among", "other", "things", ")", "the", "URL", "to", "test", "." ]
def crawl(self, fuzzable_request, debugging_id): """ :param debugging_id: A unique identifier for this call to discover() :param fuzzable_request: A fuzzable_request instance that contains (among other things) the URL to test. """ original_response = self._uri_opener.send_mutant(fuzzable_request) original_response_repeat = repeat(original_response) mutants = self._generate_mutants(fuzzable_request) args = izip(original_response_repeat, mutants) # Send the requests using threads: self.worker_pool.map_multi_args(self._check_existance, args)
[ "def", "crawl", "(", "self", ",", "fuzzable_request", ",", "debugging_id", ")", ":", "original_response", "=", "self", ".", "_uri_opener", ".", "send_mutant", "(", "fuzzable_request", ")", "original_response_repeat", "=", "repeat", "(", "original_response", ")", "mutants", "=", "self", ".", "_generate_mutants", "(", "fuzzable_request", ")", "args", "=", "izip", "(", "original_response_repeat", ",", "mutants", ")", "# Send the requests using threads:", "self", ".", "worker_pool", ".", "map_multi_args", "(", "self", ".", "_check_existance", ",", "args", ")" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/crawl/wordnet.py#L50-L64
brightmart/multi-label_classification
b5febe17eaf9d937d71cabab56c5da48ee68f7b5
run_classifier.py
python
MnliProcessor._create_examples
(self, lines, set_type)
return examples
Creates examples for the training and dev sets.
Creates examples for the training and dev sets.
[ "Creates", "examples", "for", "the", "training", "and", "dev", "sets", "." ]
def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, tokenization.convert_to_unicode(line[0])) text_a = tokenization.convert_to_unicode(line[8]) text_b = tokenization.convert_to_unicode(line[9]) if set_type == "test": label = "contradiction" else: label = tokenization.convert_to_unicode(line[-1]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples
[ "def", "_create_examples", "(", "self", ",", "lines", ",", "set_type", ")", ":", "examples", "=", "[", "]", "for", "(", "i", ",", "line", ")", "in", "enumerate", "(", "lines", ")", ":", "if", "i", "==", "0", ":", "continue", "guid", "=", "\"%s-%s\"", "%", "(", "set_type", ",", "tokenization", ".", "convert_to_unicode", "(", "line", "[", "0", "]", ")", ")", "text_a", "=", "tokenization", ".", "convert_to_unicode", "(", "line", "[", "8", "]", ")", "text_b", "=", "tokenization", ".", "convert_to_unicode", "(", "line", "[", "9", "]", ")", "if", "set_type", "==", "\"test\"", ":", "label", "=", "\"contradiction\"", "else", ":", "label", "=", "tokenization", ".", "convert_to_unicode", "(", "line", "[", "-", "1", "]", ")", "examples", ".", "append", "(", "InputExample", "(", "guid", "=", "guid", ",", "text_a", "=", "text_a", ",", "text_b", "=", "text_b", ",", "label", "=", "label", ")", ")", "return", "examples" ]
https://github.com/brightmart/multi-label_classification/blob/b5febe17eaf9d937d71cabab56c5da48ee68f7b5/run_classifier.py#L276-L291
gkrizek/bash-lambda-layer
703b0ade8174022d44779d823172ab7ac33a5505
bin/docutils/utils/math/math2html.py
python
ContainerExtractor.extract
(self, container)
return list
Extract a group of selected containers from elyxer.a container.
Extract a group of selected containers from elyxer.a container.
[ "Extract", "a", "group", "of", "selected", "containers", "from", "elyxer", ".", "a", "container", "." ]
def extract(self, container): "Extract a group of selected containers from elyxer.a container." list = [] locate = lambda c: c.__class__.__name__ in self.allowed + self.cloned recursive = lambda c: c.__class__.__name__ in self.extracted process = lambda c: self.process(c, list) container.recursivesearch(locate, recursive, process) return list
[ "def", "extract", "(", "self", ",", "container", ")", ":", "list", "=", "[", "]", "locate", "=", "lambda", "c", ":", "c", ".", "__class__", ".", "__name__", "in", "self", ".", "allowed", "+", "self", ".", "cloned", "recursive", "=", "lambda", "c", ":", "c", ".", "__class__", ".", "__name__", "in", "self", ".", "extracted", "process", "=", "lambda", "c", ":", "self", ".", "process", "(", "c", ",", "list", ")", "container", ".", "recursivesearch", "(", "locate", ",", "recursive", ",", "process", ")", "return", "list" ]
https://github.com/gkrizek/bash-lambda-layer/blob/703b0ade8174022d44779d823172ab7ac33a5505/bin/docutils/utils/math/math2html.py#L1350-L1357
UDST/urbansim
0db75668ada0005352b7c7e0a405265f78ccadd7
urbansim/models/regression.py
python
RegressionModelGroup._iter_groups
(self, data)
Iterate over the groups in `data` after grouping by `segmentation_col`. Skips any groups for which there is no model stored. Yields tuples of (name, df) where name is the group key and df is the group DataFrame. Parameters ---------- data : pandas.DataFrame Must have a column with the same name as `segmentation_col`.
Iterate over the groups in `data` after grouping by `segmentation_col`. Skips any groups for which there is no model stored.
[ "Iterate", "over", "the", "groups", "in", "data", "after", "grouping", "by", "segmentation_col", ".", "Skips", "any", "groups", "for", "which", "there", "is", "no", "model", "stored", "." ]
def _iter_groups(self, data): """ Iterate over the groups in `data` after grouping by `segmentation_col`. Skips any groups for which there is no model stored. Yields tuples of (name, df) where name is the group key and df is the group DataFrame. Parameters ---------- data : pandas.DataFrame Must have a column with the same name as `segmentation_col`. """ groups = data.groupby(self.segmentation_col) for name in self.models: yield name, groups.get_group(name)
[ "def", "_iter_groups", "(", "self", ",", "data", ")", ":", "groups", "=", "data", ".", "groupby", "(", "self", ".", "segmentation_col", ")", "for", "name", "in", "self", ".", "models", ":", "yield", "name", ",", "groups", ".", "get_group", "(", "name", ")" ]
https://github.com/UDST/urbansim/blob/0db75668ada0005352b7c7e0a405265f78ccadd7/urbansim/models/regression.py#L592-L610
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/dockermod.py
python
get_client_args
(limit=None)
return __utils__["docker.get_client_args"](limit=limit)
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0 .. versionchanged:: 2017.7.0 Replaced the container config args with the ones from the API's ``create_container`` function. .. versionchanged:: 2018.3.0 Added ability to limit the input to specific client functions Many functions in Salt have been written to support the full list of arguments for a given function in the `docker-py Low-level API`_. However, depending on the version of docker-py installed on the minion, the available arguments may differ. This function will get the arguments for various functions in the installed version of docker-py, to be used as a reference. limit An optional list of categories for which to limit the return. This is useful if only a specific set of arguments is desired, and also keeps other function's argspecs from needlessly being examined. **AVAILABLE LIMITS** - ``create_container`` - arguments accepted by `create_container()`_ (used by :py:func:`docker.create <salt.modules.dockermod.create>`) - ``host_config`` - arguments accepted by `create_host_config()`_ (used to build the host config for :py:func:`docker.create <salt.modules.dockermod.create>`) - ``connect_container_to_network`` - arguments used by `connect_container_to_network()`_ to construct an endpoint config when connecting to a network (used by :py:func:`docker.connect_container_to_network <salt.modules.dockermod.connect_container_to_network>`) - ``create_network`` - arguments accepted by `create_network()`_ (used by :py:func:`docker.create_network <salt.modules.dockermod.create_network>`) - ``ipam_config`` - arguments used to create an `IPAM pool`_ (used by :py:func:`docker.create_network <salt.modules.dockermod.create_network>` in the process of constructing an IPAM config dictionary) CLI Example: .. code-block:: bash salt myminion docker.get_client_args salt myminion docker.get_client_args logs salt myminion docker.get_client_args create_container,connect_container_to_network
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0 .. versionchanged:: 2017.7.0 Replaced the container config args with the ones from the API's ``create_container`` function. .. versionchanged:: 2018.3.0 Added ability to limit the input to specific client functions
[ "..", "versionadded", "::", "2016", ".", "3", ".", "6", "2016", ".", "11", ".", "4", "2017", ".", "7", ".", "0", "..", "versionchanged", "::", "2017", ".", "7", ".", "0", "Replaced", "the", "container", "config", "args", "with", "the", "ones", "from", "the", "API", "s", "create_container", "function", ".", "..", "versionchanged", "::", "2018", ".", "3", ".", "0", "Added", "ability", "to", "limit", "the", "input", "to", "specific", "client", "functions" ]
def get_client_args(limit=None): """ .. versionadded:: 2016.3.6,2016.11.4,2017.7.0 .. versionchanged:: 2017.7.0 Replaced the container config args with the ones from the API's ``create_container`` function. .. versionchanged:: 2018.3.0 Added ability to limit the input to specific client functions Many functions in Salt have been written to support the full list of arguments for a given function in the `docker-py Low-level API`_. However, depending on the version of docker-py installed on the minion, the available arguments may differ. This function will get the arguments for various functions in the installed version of docker-py, to be used as a reference. limit An optional list of categories for which to limit the return. This is useful if only a specific set of arguments is desired, and also keeps other function's argspecs from needlessly being examined. **AVAILABLE LIMITS** - ``create_container`` - arguments accepted by `create_container()`_ (used by :py:func:`docker.create <salt.modules.dockermod.create>`) - ``host_config`` - arguments accepted by `create_host_config()`_ (used to build the host config for :py:func:`docker.create <salt.modules.dockermod.create>`) - ``connect_container_to_network`` - arguments used by `connect_container_to_network()`_ to construct an endpoint config when connecting to a network (used by :py:func:`docker.connect_container_to_network <salt.modules.dockermod.connect_container_to_network>`) - ``create_network`` - arguments accepted by `create_network()`_ (used by :py:func:`docker.create_network <salt.modules.dockermod.create_network>`) - ``ipam_config`` - arguments used to create an `IPAM pool`_ (used by :py:func:`docker.create_network <salt.modules.dockermod.create_network>` in the process of constructing an IPAM config dictionary) CLI Example: .. code-block:: bash salt myminion docker.get_client_args salt myminion docker.get_client_args logs salt myminion docker.get_client_args create_container,connect_container_to_network """ return __utils__["docker.get_client_args"](limit=limit)
[ "def", "get_client_args", "(", "limit", "=", "None", ")", ":", "return", "__utils__", "[", "\"docker.get_client_args\"", "]", "(", "limit", "=", "limit", ")" ]
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/dockermod.py#L819-L866
KalleHallden/AutoTimer
2d954216700c4930baa154e28dbddc34609af7ce
env/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.py
python
SpecifierSet.filter
(self, iterable, prereleases=None)
[]
def filter(self, iterable, prereleases=None): # Determine if we're forcing a prerelease or not, if we're not forcing # one for this particular filter call, then we'll use whatever the # SpecifierSet thinks for whether or not we should support prereleases. if prereleases is None: prereleases = self.prereleases # If we have any specifiers, then we want to wrap our iterable in the # filter method for each one, this will act as a logical AND amongst # each specifier. if self._specs: for spec in self._specs: iterable = spec.filter(iterable, prereleases=bool(prereleases)) return iterable # If we do not have any specifiers, then we need to have a rough filter # which will filter out any pre-releases, unless there are no final # releases, and which will filter out LegacyVersion in general. else: filtered = [] found_prereleases = [] for item in iterable: # Ensure that we some kind of Version class for this item. if not isinstance(item, (LegacyVersion, Version)): parsed_version = parse(item) else: parsed_version = item # Filter out any item which is parsed as a LegacyVersion if isinstance(parsed_version, LegacyVersion): continue # Store any item which is a pre-release for later unless we've # already found a final version or we are accepting prereleases if parsed_version.is_prerelease and not prereleases: if not filtered: found_prereleases.append(item) else: filtered.append(item) # If we've found no items except for pre-releases, then we'll go # ahead and use the pre-releases if not filtered and found_prereleases and prereleases is None: return found_prereleases return filtered
[ "def", "filter", "(", "self", ",", "iterable", ",", "prereleases", "=", "None", ")", ":", "# Determine if we're forcing a prerelease or not, if we're not forcing", "# one for this particular filter call, then we'll use whatever the", "# SpecifierSet thinks for whether or not we should support prereleases.", "if", "prereleases", "is", "None", ":", "prereleases", "=", "self", ".", "prereleases", "# If we have any specifiers, then we want to wrap our iterable in the", "# filter method for each one, this will act as a logical AND amongst", "# each specifier.", "if", "self", ".", "_specs", ":", "for", "spec", "in", "self", ".", "_specs", ":", "iterable", "=", "spec", ".", "filter", "(", "iterable", ",", "prereleases", "=", "bool", "(", "prereleases", ")", ")", "return", "iterable", "# If we do not have any specifiers, then we need to have a rough filter", "# which will filter out any pre-releases, unless there are no final", "# releases, and which will filter out LegacyVersion in general.", "else", ":", "filtered", "=", "[", "]", "found_prereleases", "=", "[", "]", "for", "item", "in", "iterable", ":", "# Ensure that we some kind of Version class for this item.", "if", "not", "isinstance", "(", "item", ",", "(", "LegacyVersion", ",", "Version", ")", ")", ":", "parsed_version", "=", "parse", "(", "item", ")", "else", ":", "parsed_version", "=", "item", "# Filter out any item which is parsed as a LegacyVersion", "if", "isinstance", "(", "parsed_version", ",", "LegacyVersion", ")", ":", "continue", "# Store any item which is a pre-release for later unless we've", "# already found a final version or we are accepting prereleases", "if", "parsed_version", ".", "is_prerelease", "and", "not", "prereleases", ":", "if", "not", "filtered", ":", "found_prereleases", ".", "append", "(", "item", ")", "else", ":", "filtered", ".", "append", "(", "item", ")", "# If we've found no items except for pre-releases, then we'll go", "# ahead and use the pre-releases", "if", "not", "filtered", "and", "found_prereleases", "and", "prereleases", "is", "None", ":", "return", "found_prereleases", "return", "filtered" ]
https://github.com/KalleHallden/AutoTimer/blob/2d954216700c4930baa154e28dbddc34609af7ce/env/lib/python2.7/site-packages/pip/_vendor/packaging/specifiers.py#L704-L749
kaaedit/kaa
e6a8819a5ecba04b7db8303bd5736b5a7c9b822d
kaa/ui/inputline/inputlinemode.py
python
InputlineMode.init_keybind
(self)
[]
def init_keybind(self): super().init_keybind() self.register_keys(self.keybind, self.KEY_BINDS)
[ "def", "init_keybind", "(", "self", ")", ":", "super", "(", ")", ".", "init_keybind", "(", ")", "self", ".", "register_keys", "(", "self", ".", "keybind", ",", "self", ".", "KEY_BINDS", ")" ]
https://github.com/kaaedit/kaa/blob/e6a8819a5ecba04b7db8303bd5736b5a7c9b822d/kaa/ui/inputline/inputlinemode.py#L47-L49
tobegit3hub/deep_image_model
8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e
java_predict_client/src/main/proto/tensorflow/contrib/learn/python/learn/dataframe/transform.py
python
TensorFlowTransform.build_transitive
(self, input_series, cache=None, **kwargs)
return result
Apply this `Transform` to the provided `Series`, producing 'Tensor's. Args: input_series: None, a `Series`, or a list of input `Series`, acting as positional arguments. cache: a dict from Series reprs to Tensors. **kwargs: Additional keyword arguments, unused here. Returns: A namedtuple of the output Tensors. Raises: ValueError: `input_series` does not have expected length
Apply this `Transform` to the provided `Series`, producing 'Tensor's.
[ "Apply", "this", "Transform", "to", "the", "provided", "Series", "producing", "Tensor", "s", "." ]
def build_transitive(self, input_series, cache=None, **kwargs): """Apply this `Transform` to the provided `Series`, producing 'Tensor's. Args: input_series: None, a `Series`, or a list of input `Series`, acting as positional arguments. cache: a dict from Series reprs to Tensors. **kwargs: Additional keyword arguments, unused here. Returns: A namedtuple of the output Tensors. Raises: ValueError: `input_series` does not have expected length """ # pylint: disable=not-callable if cache is None: cache = {} if len(input_series) != self.input_valency: raise ValueError("Expected %s input Series but received %s." % (self.input_valency, len(input_series))) input_tensors = [series.build(cache, **kwargs) for series in input_series] # Note we cache each output individually, not just the entire output # tuple. This allows using the graph as the cache, since it can sensibly # cache only individual Tensors. output_reprs = [TransformedSeries.make_repr(input_series, self, output_name) for output_name in self.output_names] output_tensors = [cache.get(output_repr) for output_repr in output_reprs] if None in output_tensors: result = self._apply_transform(input_tensors, **kwargs) for output_name, output_repr in zip(self.output_names, output_reprs): cache[output_repr] = getattr(result, output_name) else: result = self.return_type(*output_tensors) self._check_output_tensors(result) return result
[ "def", "build_transitive", "(", "self", ",", "input_series", ",", "cache", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=not-callable", "if", "cache", "is", "None", ":", "cache", "=", "{", "}", "if", "len", "(", "input_series", ")", "!=", "self", ".", "input_valency", ":", "raise", "ValueError", "(", "\"Expected %s input Series but received %s.\"", "%", "(", "self", ".", "input_valency", ",", "len", "(", "input_series", ")", ")", ")", "input_tensors", "=", "[", "series", ".", "build", "(", "cache", ",", "*", "*", "kwargs", ")", "for", "series", "in", "input_series", "]", "# Note we cache each output individually, not just the entire output", "# tuple. This allows using the graph as the cache, since it can sensibly", "# cache only individual Tensors.", "output_reprs", "=", "[", "TransformedSeries", ".", "make_repr", "(", "input_series", ",", "self", ",", "output_name", ")", "for", "output_name", "in", "self", ".", "output_names", "]", "output_tensors", "=", "[", "cache", ".", "get", "(", "output_repr", ")", "for", "output_repr", "in", "output_reprs", "]", "if", "None", "in", "output_tensors", ":", "result", "=", "self", ".", "_apply_transform", "(", "input_tensors", ",", "*", "*", "kwargs", ")", "for", "output_name", ",", "output_repr", "in", "zip", "(", "self", ".", "output_names", ",", "output_reprs", ")", ":", "cache", "[", "output_repr", "]", "=", "getattr", "(", "result", ",", "output_name", ")", "else", ":", "result", "=", "self", ".", "return_type", "(", "*", "output_tensors", ")", "self", ".", "_check_output_tensors", "(", "result", ")", "return", "result" ]
https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/contrib/learn/python/learn/dataframe/transform.py#L271-L310
axnsan12/drf-yasg
d9700dbf8cc80d725a7db485c2d4446c19c29840
src/drf_yasg/codecs.py
python
OpenAPICodecYaml._dump_dict
(self, spec)
return yaml_sane_dump(spec, binary=True)
Dump ``spec`` into YAML. :rtype: bytes
Dump ``spec`` into YAML.
[ "Dump", "spec", "into", "YAML", "." ]
def _dump_dict(self, spec): """Dump ``spec`` into YAML. :rtype: bytes""" return yaml_sane_dump(spec, binary=True)
[ "def", "_dump_dict", "(", "self", ",", "spec", ")", ":", "return", "yaml_sane_dump", "(", "spec", ",", "binary", "=", "True", ")" ]
https://github.com/axnsan12/drf-yasg/blob/d9700dbf8cc80d725a7db485c2d4446c19c29840/src/drf_yasg/codecs.py#L230-L234
tensorflow/lingvo
ce10019243d954c3c3ebe739f7589b5eebfdf907
lingvo/jax/layers/conformers.py
python
Conformer.fprop
(self, theta: NestedMap, inputs: JTensor, paddings: JTensor)
return inputs
Conformer layer. Args: theta: A `.NestedMap` object containing weights' values of this layer and its children layers. inputs: Input sequence JTensor of shape [B, T, H]. paddings: Input paddings JTensor of shape [B, T] (only used in FFN layer). Returns: The conformer output with shape [B, T, D].
Conformer layer.
[ "Conformer", "layer", "." ]
def fprop(self, theta: NestedMap, inputs: JTensor, paddings: JTensor) -> JTensor: """Conformer layer. Args: theta: A `.NestedMap` object containing weights' values of this layer and its children layers. inputs: Input sequence JTensor of shape [B, T, H]. paddings: Input paddings JTensor of shape [B, T] (only used in FFN layer). Returns: The conformer output with shape [B, T, D]. """ p = self.params if self.has_fflayer_start: inputs = self.fflayer_start.fprop(theta.fflayer_start, inputs, paddings) if p.layer_order == 'mhsa': inputs = self.trans_atten.fprop( theta.trans_atten, inputs=inputs, paddings=paddings) elif p.layer_order == 'conv': inputs = self.lconv.fprop(theta.lconv, inputs, paddings) elif p.layer_order == 'mhsa_before_conv': inputs = self.trans_atten.fprop( theta.trans_atten, inputs=inputs, paddings=paddings) inputs = self.lconv.fprop(theta.lconv, inputs, paddings) else: assert p.layer_order == 'conv_before_mhsa' inputs = self.lconv.fprop(theta.lconv, inputs, paddings) inputs = self.trans_atten.fprop( theta.trans_atten, inputs=inputs, paddings=paddings) if self.has_fflayer_end: inputs = self.fflayer_end.fprop(theta.fflayer_end, inputs, paddings) elif p.fflayer_weight_sharing: # With the weight sharing, we apply fflayer_start again inputs = self.fflayer_start.fprop(theta.fflayer_start, inputs, paddings) inputs = self.final_ln.fprop(theta.final_ln, inputs) return inputs
[ "def", "fprop", "(", "self", ",", "theta", ":", "NestedMap", ",", "inputs", ":", "JTensor", ",", "paddings", ":", "JTensor", ")", "->", "JTensor", ":", "p", "=", "self", ".", "params", "if", "self", ".", "has_fflayer_start", ":", "inputs", "=", "self", ".", "fflayer_start", ".", "fprop", "(", "theta", ".", "fflayer_start", ",", "inputs", ",", "paddings", ")", "if", "p", ".", "layer_order", "==", "'mhsa'", ":", "inputs", "=", "self", ".", "trans_atten", ".", "fprop", "(", "theta", ".", "trans_atten", ",", "inputs", "=", "inputs", ",", "paddings", "=", "paddings", ")", "elif", "p", ".", "layer_order", "==", "'conv'", ":", "inputs", "=", "self", ".", "lconv", ".", "fprop", "(", "theta", ".", "lconv", ",", "inputs", ",", "paddings", ")", "elif", "p", ".", "layer_order", "==", "'mhsa_before_conv'", ":", "inputs", "=", "self", ".", "trans_atten", ".", "fprop", "(", "theta", ".", "trans_atten", ",", "inputs", "=", "inputs", ",", "paddings", "=", "paddings", ")", "inputs", "=", "self", ".", "lconv", ".", "fprop", "(", "theta", ".", "lconv", ",", "inputs", ",", "paddings", ")", "else", ":", "assert", "p", ".", "layer_order", "==", "'conv_before_mhsa'", "inputs", "=", "self", ".", "lconv", ".", "fprop", "(", "theta", ".", "lconv", ",", "inputs", ",", "paddings", ")", "inputs", "=", "self", ".", "trans_atten", ".", "fprop", "(", "theta", ".", "trans_atten", ",", "inputs", "=", "inputs", ",", "paddings", "=", "paddings", ")", "if", "self", ".", "has_fflayer_end", ":", "inputs", "=", "self", ".", "fflayer_end", ".", "fprop", "(", "theta", ".", "fflayer_end", ",", "inputs", ",", "paddings", ")", "elif", "p", ".", "fflayer_weight_sharing", ":", "# With the weight sharing, we apply fflayer_start again", "inputs", "=", "self", ".", "fflayer_start", ".", "fprop", "(", "theta", ".", "fflayer_start", ",", "inputs", ",", "paddings", ")", "inputs", "=", "self", ".", "final_ln", ".", "fprop", "(", "theta", ".", "final_ln", ",", "inputs", ")", "return", "inputs" ]
https://github.com/tensorflow/lingvo/blob/ce10019243d954c3c3ebe739f7589b5eebfdf907/lingvo/jax/layers/conformers.py#L247-L287
xonsh/xonsh
b76d6f994f22a4078f602f8b386f4ec280c8461f
xonsh/openpy.py
python
read_py_url
(url, errors="replace", skip_encoding_cookie=True)
return source_to_unicode(buf, errors, skip_encoding_cookie)
Read a Python file from a URL, using the encoding declared inside the file. Parameters ---------- url : str The URL from which to fetch the file. errors : str How to handle decoding errors in the file. Options are the same as for bytes.decode(), but here 'replace' is the default. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in the first two lines, that line will be excluded from the output - compiling a unicode string with an encoding declaration is a SyntaxError in Python 2. Returns ------- A unicode string containing the contents of the file.
Read a Python file from a URL, using the encoding declared inside the file.
[ "Read", "a", "Python", "file", "from", "a", "URL", "using", "the", "encoding", "declared", "inside", "the", "file", "." ]
def read_py_url(url, errors="replace", skip_encoding_cookie=True): """Read a Python file from a URL, using the encoding declared inside the file. Parameters ---------- url : str The URL from which to fetch the file. errors : str How to handle decoding errors in the file. Options are the same as for bytes.decode(), but here 'replace' is the default. skip_encoding_cookie : bool If True (the default), and the encoding declaration is found in the first two lines, that line will be excluded from the output - compiling a unicode string with an encoding declaration is a SyntaxError in Python 2. Returns ------- A unicode string containing the contents of the file. """ # Deferred import for faster start try: from urllib.request import urlopen # Py 3 except ImportError: from urllib import urlopen response = urlopen(url) buf = io.BytesIO(response.read()) return source_to_unicode(buf, errors, skip_encoding_cookie)
[ "def", "read_py_url", "(", "url", ",", "errors", "=", "\"replace\"", ",", "skip_encoding_cookie", "=", "True", ")", ":", "# Deferred import for faster start", "try", ":", "from", "urllib", ".", "request", "import", "urlopen", "# Py 3", "except", "ImportError", ":", "from", "urllib", "import", "urlopen", "response", "=", "urlopen", "(", "url", ")", "buf", "=", "io", ".", "BytesIO", "(", "response", ".", "read", "(", ")", ")", "return", "source_to_unicode", "(", "buf", ",", "errors", ",", "skip_encoding_cookie", ")" ]
https://github.com/xonsh/xonsh/blob/b76d6f994f22a4078f602f8b386f4ec280c8461f/xonsh/openpy.py#L95-L121
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_oa_openshift/library/oc_route.py
python
Route.get_service
(self)
return self.get(Route.service_path)
return service name
return service name
[ "return", "service", "name" ]
def get_service(self): ''' return service name ''' return self.get(Route.service_path)
[ "def", "get_service", "(", "self", ")", ":", "return", "self", ".", "get", "(", "Route", ".", "service_path", ")" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_oa_openshift/library/oc_route.py#L1640-L1642
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/ign_sismologia/geo_location.py
python
IgnSismologiaLocationEvent.longitude
(self)
return self._longitude
Return longitude value of this external event.
Return longitude value of this external event.
[ "Return", "longitude", "value", "of", "this", "external", "event", "." ]
def longitude(self) -> float | None: """Return longitude value of this external event.""" return self._longitude
[ "def", "longitude", "(", "self", ")", "->", "float", "|", "None", ":", "return", "self", ".", "_longitude" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/ign_sismologia/geo_location.py#L241-L243
CellProfiler/CellProfiler
a90e17e4d258c6f3900238be0f828e0b4bd1b293
cellprofiler/gui/editobjectsdlg.py
python
EditObjectsDialog.get_area
(artist)
return area
Get the area inside an artist polygon
Get the area inside an artist polygon
[ "Get", "the", "area", "inside", "an", "artist", "polygon" ]
def get_area(artist): """Get the area inside an artist polygon""" # # Thank you Darel Rex Finley: # # http://alienryderflex.com/polygon_area/ # # Code is public domain # x, y = artist.get_data() area = abs(numpy.sum((x[:-1] + x[1:]) * (y[:-1] - y[1:]))) / 2 return area
[ "def", "get_area", "(", "artist", ")", ":", "#", "# Thank you Darel Rex Finley:", "#", "# http://alienryderflex.com/polygon_area/", "#", "# Code is public domain", "#", "x", ",", "y", "=", "artist", ".", "get_data", "(", ")", "area", "=", "abs", "(", "numpy", ".", "sum", "(", "(", "x", "[", ":", "-", "1", "]", "+", "x", "[", "1", ":", "]", ")", "*", "(", "y", "[", ":", "-", "1", "]", "-", "y", "[", "1", ":", "]", ")", ")", ")", "/", "2", "return", "area" ]
https://github.com/CellProfiler/CellProfiler/blob/a90e17e4d258c6f3900238be0f828e0b4bd1b293/cellprofiler/gui/editobjectsdlg.py#L1762-L1773
square/pylink
a2d9fbd3add62ffd06ba737c5ea82b8491fdc425
pylink/structs.py
python
JLinkSWOStartInfo.__repr__
(self)
return self.__str__()
Returns a representation of this instance. Args: self (JLinkSWOStartInfo): the ``JLinkSWOStartInfo`` instance Returns: The string representation of this instance.
Returns a representation of this instance.
[ "Returns", "a", "representation", "of", "this", "instance", "." ]
def __repr__(self): """Returns a representation of this instance. Args: self (JLinkSWOStartInfo): the ``JLinkSWOStartInfo`` instance Returns: The string representation of this instance. """ return self.__str__()
[ "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "__str__", "(", ")" ]
https://github.com/square/pylink/blob/a2d9fbd3add62ffd06ba737c5ea82b8491fdc425/pylink/structs.py#L455-L464
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/unsupervised/owmanifoldlearning.py
python
TSNEParametersEditor.__init__
(self, parent)
[]
def __init__(self, parent): super().__init__(parent) self._create_combo_parameter("metric", "Metric:") self._create_spin_parameter("perplexity", 1, 100, "Perplexity:") self._create_spin_parameter("early_exaggeration", 1, 100, "Early exaggeration:") self._create_spin_parameter("learning_rate", 1, 1000, "Learning rate:") self._create_spin_parameter("n_iter", 250, 1e5, "Max iterations:") self._create_radio_parameter("initialization", "Initialization:")
[ "def", "__init__", "(", "self", ",", "parent", ")", ":", "super", "(", ")", ".", "__init__", "(", "parent", ")", "self", ".", "_create_combo_parameter", "(", "\"metric\"", ",", "\"Metric:\"", ")", "self", ".", "_create_spin_parameter", "(", "\"perplexity\"", ",", "1", ",", "100", ",", "\"Perplexity:\"", ")", "self", ".", "_create_spin_parameter", "(", "\"early_exaggeration\"", ",", "1", ",", "100", ",", "\"Early exaggeration:\"", ")", "self", ".", "_create_spin_parameter", "(", "\"learning_rate\"", ",", "1", ",", "1000", ",", "\"Learning rate:\"", ")", "self", ".", "_create_spin_parameter", "(", "\"n_iter\"", ",", "250", ",", "1e5", ",", "\"Max iterations:\"", ")", "self", ".", "_create_radio_parameter", "(", "\"initialization\"", ",", "\"Initialization:\"", ")" ]
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/unsupervised/owmanifoldlearning.py#L103-L111
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/evaluate/owliftcurve.py
python
ParameterSetter.update_setters
(self)
[]
def update_setters(self): self.initial_settings = { self.LABELS_BOX: { self.FONT_FAMILY_LABEL: self.FONT_FAMILY_SETTING, self.TITLE_LABEL: self.FONT_SETTING, self.AXIS_TITLE_LABEL: self.FONT_SETTING, self.AXIS_TICKS_LABEL: self.FONT_SETTING, }, self.ANNOT_BOX: { self.TITLE_LABEL: {self.TITLE_LABEL: ("", "")}, }, self.PLOT_BOX: { self.WIDE_LINE_LABEL: { Updater.WIDTH_LABEL: (range(1, 15), self.WIDE_LINE_WIDTH), Updater.STYLE_LABEL: (list(Updater.LINE_STYLES), self.WIDE_LINE_STYLE), }, self.LINE_LABEL: { Updater.WIDTH_LABEL: (range(1, 15), self.LINE_WIDTH), Updater.STYLE_LABEL: (list(Updater.LINE_STYLES), self.LINE_STYLE), }, self.DEFAULT_LINE_LABEL: { Updater.WIDTH_LABEL: (range(1, 15), self.DEFAULT_LINE_WIDTH), Updater.STYLE_LABEL: (list(Updater.LINE_STYLES), self.DEFAULT_LINE_STYLE), }, } } def update_wide_curves(**_settings): self.wide_line_settings.update(**_settings) if self.master.display_convex_hull: Updater.update_lines(self.master.hull_items, **self.wide_line_settings) else: Updater.update_lines(self.master.curve_items, **self.wide_line_settings) def update_thin_curves(**_settings): self.line_settings.update(**_settings) if self.master.display_convex_hull: Updater.update_lines(self.master.curve_items, **self.line_settings) def update_default_line(**_settings): self.default_line_settings.update(**_settings) Updater.update_lines(self.default_line_items, **self.default_line_settings) self._setters[self.PLOT_BOX] = { self.WIDE_LINE_LABEL: update_wide_curves, self.LINE_LABEL: update_thin_curves, self.DEFAULT_LINE_LABEL: update_default_line, }
[ "def", "update_setters", "(", "self", ")", ":", "self", ".", "initial_settings", "=", "{", "self", ".", "LABELS_BOX", ":", "{", "self", ".", "FONT_FAMILY_LABEL", ":", "self", ".", "FONT_FAMILY_SETTING", ",", "self", ".", "TITLE_LABEL", ":", "self", ".", "FONT_SETTING", ",", "self", ".", "AXIS_TITLE_LABEL", ":", "self", ".", "FONT_SETTING", ",", "self", ".", "AXIS_TICKS_LABEL", ":", "self", ".", "FONT_SETTING", ",", "}", ",", "self", ".", "ANNOT_BOX", ":", "{", "self", ".", "TITLE_LABEL", ":", "{", "self", ".", "TITLE_LABEL", ":", "(", "\"\"", ",", "\"\"", ")", "}", ",", "}", ",", "self", ".", "PLOT_BOX", ":", "{", "self", ".", "WIDE_LINE_LABEL", ":", "{", "Updater", ".", "WIDTH_LABEL", ":", "(", "range", "(", "1", ",", "15", ")", ",", "self", ".", "WIDE_LINE_WIDTH", ")", ",", "Updater", ".", "STYLE_LABEL", ":", "(", "list", "(", "Updater", ".", "LINE_STYLES", ")", ",", "self", ".", "WIDE_LINE_STYLE", ")", ",", "}", ",", "self", ".", "LINE_LABEL", ":", "{", "Updater", ".", "WIDTH_LABEL", ":", "(", "range", "(", "1", ",", "15", ")", ",", "self", ".", "LINE_WIDTH", ")", ",", "Updater", ".", "STYLE_LABEL", ":", "(", "list", "(", "Updater", ".", "LINE_STYLES", ")", ",", "self", ".", "LINE_STYLE", ")", ",", "}", ",", "self", ".", "DEFAULT_LINE_LABEL", ":", "{", "Updater", ".", "WIDTH_LABEL", ":", "(", "range", "(", "1", ",", "15", ")", ",", "self", ".", "DEFAULT_LINE_WIDTH", ")", ",", "Updater", ".", "STYLE_LABEL", ":", "(", "list", "(", "Updater", ".", "LINE_STYLES", ")", ",", "self", ".", "DEFAULT_LINE_STYLE", ")", ",", "}", ",", "}", "}", "def", "update_wide_curves", "(", "*", "*", "_settings", ")", ":", "self", ".", "wide_line_settings", ".", "update", "(", "*", "*", "_settings", ")", "if", "self", ".", "master", ".", "display_convex_hull", ":", "Updater", ".", "update_lines", "(", "self", ".", "master", ".", "hull_items", ",", "*", "*", "self", ".", "wide_line_settings", ")", "else", ":", "Updater", ".", "update_lines", "(", "self", ".", "master", ".", "curve_items", ",", "*", "*", "self", ".", "wide_line_settings", ")", "def", "update_thin_curves", "(", "*", "*", "_settings", ")", ":", "self", ".", "line_settings", ".", "update", "(", "*", "*", "_settings", ")", "if", "self", ".", "master", ".", "display_convex_hull", ":", "Updater", ".", "update_lines", "(", "self", ".", "master", ".", "curve_items", ",", "*", "*", "self", ".", "line_settings", ")", "def", "update_default_line", "(", "*", "*", "_settings", ")", ":", "self", ".", "default_line_settings", ".", "update", "(", "*", "*", "_settings", ")", "Updater", ".", "update_lines", "(", "self", ".", "default_line_items", ",", "*", "*", "self", ".", "default_line_settings", ")", "self", ".", "_setters", "[", "self", ".", "PLOT_BOX", "]", "=", "{", "self", ".", "WIDE_LINE_LABEL", ":", "update_wide_curves", ",", "self", ".", "LINE_LABEL", ":", "update_thin_curves", ",", "self", ".", "DEFAULT_LINE_LABEL", ":", "update_default_line", ",", "}" ]
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/evaluate/owliftcurve.py#L79-L134
golemhq/golem
84f51478b169cdeab73fc7e2a22a64d0a2a29263
golem/actions.py
python
assert_element_has_not_focus
(element)
Assert element does not have focus Parameters: element : element
Assert element does not have focus
[ "Assert", "element", "does", "not", "have", "focus" ]
def assert_element_has_not_focus(element): """Assert element does not have focus Parameters: element : element """ element = get_browser().find(element, timeout=0) _add_step(f'Assert element {element.name} does not have focus') _run_wait_hook() error_msg = f'element {element.name} has focus' assert not element.has_focus(), error_msg
[ "def", "assert_element_has_not_focus", "(", "element", ")", ":", "element", "=", "get_browser", "(", ")", ".", "find", "(", "element", ",", "timeout", "=", "0", ")", "_add_step", "(", "f'Assert element {element.name} does not have focus'", ")", "_run_wait_hook", "(", ")", "error_msg", "=", "f'element {element.name} has focus'", "assert", "not", "element", ".", "has_focus", "(", ")", ",", "error_msg" ]
https://github.com/golemhq/golem/blob/84f51478b169cdeab73fc7e2a22a64d0a2a29263/golem/actions.py#L466-L476
PyCQA/isort
c6a41965247a858a0afd848fbebfca18b8983917
isort/wrap.py
python
import_statement
( import_start: str, from_imports: List[str], comments: Sequence[str] = (), line_separator: str = "\n", config: Config = DEFAULT_CONFIG, multi_line_output: Optional[Modes] = None, )
return statement
Returns a multi-line wrapped form of the provided from import statement.
Returns a multi-line wrapped form of the provided from import statement.
[ "Returns", "a", "multi", "-", "line", "wrapped", "form", "of", "the", "provided", "from", "import", "statement", "." ]
def import_statement( import_start: str, from_imports: List[str], comments: Sequence[str] = (), line_separator: str = "\n", config: Config = DEFAULT_CONFIG, multi_line_output: Optional[Modes] = None, ) -> str: """Returns a multi-line wrapped form of the provided from import statement.""" formatter = formatter_from_string((multi_line_output or config.multi_line_output).name) dynamic_indent = " " * (len(import_start) + 1) indent = config.indent line_length = config.wrap_length or config.line_length statement = formatter( statement=import_start, imports=copy.copy(from_imports), white_space=dynamic_indent, indent=indent, line_length=line_length, comments=comments, line_separator=line_separator, comment_prefix=config.comment_prefix, include_trailing_comma=config.include_trailing_comma, remove_comments=config.ignore_comments, ) if config.balanced_wrapping: lines = statement.split(line_separator) line_count = len(lines) if len(lines) > 1: minimum_length = min(len(line) for line in lines[:-1]) else: minimum_length = 0 new_import_statement = statement while len(lines[-1]) < minimum_length and len(lines) == line_count and line_length > 10: statement = new_import_statement line_length -= 1 new_import_statement = formatter( statement=import_start, imports=copy.copy(from_imports), white_space=dynamic_indent, indent=indent, line_length=line_length, comments=comments, line_separator=line_separator, comment_prefix=config.comment_prefix, include_trailing_comma=config.include_trailing_comma, remove_comments=config.ignore_comments, ) lines = new_import_statement.split(line_separator) if statement.count(line_separator) == 0: return _wrap_line(statement, line_separator, config) return statement
[ "def", "import_statement", "(", "import_start", ":", "str", ",", "from_imports", ":", "List", "[", "str", "]", ",", "comments", ":", "Sequence", "[", "str", "]", "=", "(", ")", ",", "line_separator", ":", "str", "=", "\"\\n\"", ",", "config", ":", "Config", "=", "DEFAULT_CONFIG", ",", "multi_line_output", ":", "Optional", "[", "Modes", "]", "=", "None", ",", ")", "->", "str", ":", "formatter", "=", "formatter_from_string", "(", "(", "multi_line_output", "or", "config", ".", "multi_line_output", ")", ".", "name", ")", "dynamic_indent", "=", "\" \"", "*", "(", "len", "(", "import_start", ")", "+", "1", ")", "indent", "=", "config", ".", "indent", "line_length", "=", "config", ".", "wrap_length", "or", "config", ".", "line_length", "statement", "=", "formatter", "(", "statement", "=", "import_start", ",", "imports", "=", "copy", ".", "copy", "(", "from_imports", ")", ",", "white_space", "=", "dynamic_indent", ",", "indent", "=", "indent", ",", "line_length", "=", "line_length", ",", "comments", "=", "comments", ",", "line_separator", "=", "line_separator", ",", "comment_prefix", "=", "config", ".", "comment_prefix", ",", "include_trailing_comma", "=", "config", ".", "include_trailing_comma", ",", "remove_comments", "=", "config", ".", "ignore_comments", ",", ")", "if", "config", ".", "balanced_wrapping", ":", "lines", "=", "statement", ".", "split", "(", "line_separator", ")", "line_count", "=", "len", "(", "lines", ")", "if", "len", "(", "lines", ")", ">", "1", ":", "minimum_length", "=", "min", "(", "len", "(", "line", ")", "for", "line", "in", "lines", "[", ":", "-", "1", "]", ")", "else", ":", "minimum_length", "=", "0", "new_import_statement", "=", "statement", "while", "len", "(", "lines", "[", "-", "1", "]", ")", "<", "minimum_length", "and", "len", "(", "lines", ")", "==", "line_count", "and", "line_length", ">", "10", ":", "statement", "=", "new_import_statement", "line_length", "-=", "1", "new_import_statement", "=", "formatter", "(", "statement", "=", "import_start", ",", "imports", "=", "copy", ".", "copy", "(", "from_imports", ")", ",", "white_space", "=", "dynamic_indent", ",", "indent", "=", "indent", ",", "line_length", "=", "line_length", ",", "comments", "=", "comments", ",", "line_separator", "=", "line_separator", ",", "comment_prefix", "=", "config", ".", "comment_prefix", ",", "include_trailing_comma", "=", "config", ".", "include_trailing_comma", ",", "remove_comments", "=", "config", ".", "ignore_comments", ",", ")", "lines", "=", "new_import_statement", ".", "split", "(", "line_separator", ")", "if", "statement", ".", "count", "(", "line_separator", ")", "==", "0", ":", "return", "_wrap_line", "(", "statement", ",", "line_separator", ",", "config", ")", "return", "statement" ]
https://github.com/PyCQA/isort/blob/c6a41965247a858a0afd848fbebfca18b8983917/isort/wrap.py#L10-L61
EnterpriseDB/barman
487bad92edec72712531ead4746fad72bb310270
barman/retention_policies.py
python
RetentionPolicy.report
(self, source=None, context=None)
Report obsolete/valid objects according to the retention policy
Report obsolete/valid objects according to the retention policy
[ "Report", "obsolete", "/", "valid", "objects", "according", "to", "the", "retention", "policy" ]
def report(self, source=None, context=None): """Report obsolete/valid objects according to the retention policy""" if context is None: context = self.context # Overrides the list of available backups if source is None: source = self.server.available_backups if context == "BASE": return self._backup_report(source) elif context == "WAL": return self._wal_report() else: raise ValueError("Invalid context %s", context)
[ "def", "report", "(", "self", ",", "source", "=", "None", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "self", ".", "context", "# Overrides the list of available backups", "if", "source", "is", "None", ":", "source", "=", "self", ".", "server", ".", "available_backups", "if", "context", "==", "\"BASE\"", ":", "return", "self", ".", "_backup_report", "(", "source", ")", "elif", "context", "==", "\"WAL\"", ":", "return", "self", ".", "_wal_report", "(", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid context %s\"", ",", "context", ")" ]
https://github.com/EnterpriseDB/barman/blob/487bad92edec72712531ead4746fad72bb310270/barman/retention_policies.py#L57-L69
postgres/pgadmin4
374c5e952fa594d749fadf1f88076c1cba8c5f64
web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/__init__.py
python
SynonymView.dependents
(self, gid, sid, did, scid, syid)
return ajax_response( response=dependents_result, status=200 )
This function get the dependents and return ajax response for the Synonym node. Args: gid: Server Group ID sid: Server ID did: Database ID scid: Schema ID syid: Synonym ID
This function get the dependents and return ajax response for the Synonym node.
[ "This", "function", "get", "the", "dependents", "and", "return", "ajax", "response", "for", "the", "Synonym", "node", "." ]
def dependents(self, gid, sid, did, scid, syid): """ This function get the dependents and return ajax response for the Synonym node. Args: gid: Server Group ID sid: Server ID did: Database ID scid: Schema ID syid: Synonym ID """ dependents_result = self.get_dependents(self.conn, syid) return ajax_response( response=dependents_result, status=200 )
[ "def", "dependents", "(", "self", ",", "gid", ",", "sid", ",", "did", ",", "scid", ",", "syid", ")", ":", "dependents_result", "=", "self", ".", "get_dependents", "(", "self", ".", "conn", ",", "syid", ")", "return", "ajax_response", "(", "response", "=", "dependents_result", ",", "status", "=", "200", ")" ]
https://github.com/postgres/pgadmin4/blob/374c5e952fa594d749fadf1f88076c1cba8c5f64/web/pgadmin/browser/server_groups/servers/databases/schemas/synonyms/__init__.py#L706-L723
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
bin/x86/Debug/scripting_engine/Lib/SimpleXMLRPCServer.py
python
SimpleXMLRPCDispatcher.system_methodSignature
(self, method_name)
return 'signatures not supported'
system.methodSignature('add') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.
system.methodSignature('add') => [double, int, int]
[ "system", ".", "methodSignature", "(", "add", ")", "=", ">", "[", "double", "int", "int", "]" ]
def system_methodSignature(self, method_name): """system.methodSignature('add') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.""" # See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html return 'signatures not supported'
[ "def", "system_methodSignature", "(", "self", ",", "method_name", ")", ":", "# See http://xmlrpc.usefulinc.com/doc/sysmethodsig.html", "return", "'signatures not supported'" ]
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/bin/x86/Debug/scripting_engine/Lib/SimpleXMLRPCServer.py#L301-L312
hildogjr/KiCost
227f246d8c0f5dab145390d15c94ee2c3d6c790c
kicost/spreadsheet.py
python
xl_range
(first_row, first_col, last_row=None, last_col=None)
return range1 + ':' + range2
[]
def xl_range(first_row, first_col, last_row=None, last_col=None): if last_row is None: last_row = first_row if last_col is None: last_col = first_col range1 = xl_rowcol_to_cell(first_row, first_col) range2 = xl_rowcol_to_cell(last_row, last_col) if range1 == range2: return range1 return range1 + ':' + range2
[ "def", "xl_range", "(", "first_row", ",", "first_col", ",", "last_row", "=", "None", ",", "last_col", "=", "None", ")", ":", "if", "last_row", "is", "None", ":", "last_row", "=", "first_row", "if", "last_col", "is", "None", ":", "last_col", "=", "first_col", "range1", "=", "xl_rowcol_to_cell", "(", "first_row", ",", "first_col", ")", "range2", "=", "xl_rowcol_to_cell", "(", "last_row", ",", "last_col", ")", "if", "range1", "==", "range2", ":", "return", "range1", "return", "range1", "+", "':'", "+", "range2" ]
https://github.com/hildogjr/KiCost/blob/227f246d8c0f5dab145390d15c94ee2c3d6c790c/kicost/spreadsheet.py#L57-L66
python-pillow/Pillow
fd2b07c454b20e1e9af0cea64923b21250f8f8d6
src/PIL/ImageDraw.py
python
ImageDraw.regular_polygon
( self, bounding_circle, n_sides, rotation=0, fill=None, outline=None )
Draw a regular polygon.
Draw a regular polygon.
[ "Draw", "a", "regular", "polygon", "." ]
def regular_polygon( self, bounding_circle, n_sides, rotation=0, fill=None, outline=None ): """Draw a regular polygon.""" xy = _compute_regular_polygon_vertices(bounding_circle, n_sides, rotation) self.polygon(xy, fill, outline)
[ "def", "regular_polygon", "(", "self", ",", "bounding_circle", ",", "n_sides", ",", "rotation", "=", "0", ",", "fill", "=", "None", ",", "outline", "=", "None", ")", ":", "xy", "=", "_compute_regular_polygon_vertices", "(", "bounding_circle", ",", "n_sides", ",", "rotation", ")", "self", ".", "polygon", "(", "xy", ",", "fill", ",", "outline", ")" ]
https://github.com/python-pillow/Pillow/blob/fd2b07c454b20e1e9af0cea64923b21250f8f8d6/src/PIL/ImageDraw.py#L266-L271
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/scripts/sshbackdoors/backdoors/shell/pupy/pupy/packages/windows/x86/psutil/_pswindows.py
python
Process.name
(self)
Return process name, which on Windows is always the final part of the executable.
Return process name, which on Windows is always the final part of the executable.
[ "Return", "process", "name", "which", "on", "Windows", "is", "always", "the", "final", "part", "of", "the", "executable", "." ]
def name(self): """Return process name, which on Windows is always the final part of the executable. """ # This is how PIDs 0 and 4 are always represented in taskmgr # and process-hacker. if self.pid == 0: return "System Idle Process" elif self.pid == 4: return "System" else: try: # Note: this will fail with AD for most PIDs owned # by another user but it's faster. return py2_strencode(os.path.basename(self.exe())) except AccessDenied: return py2_strencode(cext.proc_name(self.pid))
[ "def", "name", "(", "self", ")", ":", "# This is how PIDs 0 and 4 are always represented in taskmgr", "# and process-hacker.", "if", "self", ".", "pid", "==", "0", ":", "return", "\"System Idle Process\"", "elif", "self", ".", "pid", "==", "4", ":", "return", "\"System\"", "else", ":", "try", ":", "# Note: this will fail with AD for most PIDs owned", "# by another user but it's faster.", "return", "py2_strencode", "(", "os", ".", "path", ".", "basename", "(", "self", ".", "exe", "(", ")", ")", ")", "except", "AccessDenied", ":", "return", "py2_strencode", "(", "cext", ".", "proc_name", "(", "self", ".", "pid", ")", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/scripts/sshbackdoors/backdoors/shell/pupy/pupy/packages/windows/x86/psutil/_pswindows.py#L302-L318
X-DataInitiative/tick
bbc561804eb1fdcb4c71b9e3e2d83a66e7b13a48
tick/hawkes/simulation/hawkes_kernels/hawkes_kernel.py
python
HawkesKernel.get_support
(self)
return self._kernel.get_support()
Returns the upperbound of the support
Returns the upperbound of the support
[ "Returns", "the", "upperbound", "of", "the", "support" ]
def get_support(self): """Returns the upperbound of the support """ return self._kernel.get_support()
[ "def", "get_support", "(", "self", ")", ":", "return", "self", ".", "_kernel", ".", "get_support", "(", ")" ]
https://github.com/X-DataInitiative/tick/blob/bbc561804eb1fdcb4c71b9e3e2d83a66e7b13a48/tick/hawkes/simulation/hawkes_kernels/hawkes_kernel.py#L23-L26
beetbox/beets
2fea53c34dd505ba391cb345424e0613901c8025
beets/ui/commands.py
python
_do_query
(lib, query, album, also_items=True)
return items, albums
For commands that operate on matched items, performs a query and returns a list of matching items and a list of matching albums. (The latter is only nonempty when album is True.) Raises a UserError if no items match. also_items controls whether, when fetching albums, the associated items should be fetched also.
For commands that operate on matched items, performs a query and returns a list of matching items and a list of matching albums. (The latter is only nonempty when album is True.) Raises a UserError if no items match. also_items controls whether, when fetching albums, the associated items should be fetched also.
[ "For", "commands", "that", "operate", "on", "matched", "items", "performs", "a", "query", "and", "returns", "a", "list", "of", "matching", "items", "and", "a", "list", "of", "matching", "albums", ".", "(", "The", "latter", "is", "only", "nonempty", "when", "album", "is", "True", ".", ")", "Raises", "a", "UserError", "if", "no", "items", "match", ".", "also_items", "controls", "whether", "when", "fetching", "albums", "the", "associated", "items", "should", "be", "fetched", "also", "." ]
def _do_query(lib, query, album, also_items=True): """For commands that operate on matched items, performs a query and returns a list of matching items and a list of matching albums. (The latter is only nonempty when album is True.) Raises a UserError if no items match. also_items controls whether, when fetching albums, the associated items should be fetched also. """ if album: albums = list(lib.albums(query)) items = [] if also_items: for al in albums: items += al.items() else: albums = [] items = list(lib.items(query)) if album and not albums: raise ui.UserError('No matching albums found.') elif not album and not items: raise ui.UserError('No matching items found.') return items, albums
[ "def", "_do_query", "(", "lib", ",", "query", ",", "album", ",", "also_items", "=", "True", ")", ":", "if", "album", ":", "albums", "=", "list", "(", "lib", ".", "albums", "(", "query", ")", ")", "items", "=", "[", "]", "if", "also_items", ":", "for", "al", "in", "albums", ":", "items", "+=", "al", ".", "items", "(", ")", "else", ":", "albums", "=", "[", "]", "items", "=", "list", "(", "lib", ".", "items", "(", "query", ")", ")", "if", "album", "and", "not", "albums", ":", "raise", "ui", ".", "UserError", "(", "'No matching albums found.'", ")", "elif", "not", "album", "and", "not", "items", ":", "raise", "ui", ".", "UserError", "(", "'No matching items found.'", ")", "return", "items", ",", "albums" ]
https://github.com/beetbox/beets/blob/2fea53c34dd505ba391cb345424e0613901c8025/beets/ui/commands.py#L56-L79
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/tempfile.py
python
_sanitize_params
(prefix, suffix, dir)
return prefix, suffix, dir, output_type
Common parameter processing for most APIs in this module.
Common parameter processing for most APIs in this module.
[ "Common", "parameter", "processing", "for", "most", "APIs", "in", "this", "module", "." ]
def _sanitize_params(prefix, suffix, dir): """Common parameter processing for most APIs in this module.""" output_type = _infer_return_type(prefix, suffix, dir) if suffix is None: suffix = output_type() if prefix is None: if output_type is str: prefix = template else: prefix = _os.fsencode(template) if dir is None: if output_type is str: dir = gettempdir() else: dir = gettempdirb() return prefix, suffix, dir, output_type
[ "def", "_sanitize_params", "(", "prefix", ",", "suffix", ",", "dir", ")", ":", "output_type", "=", "_infer_return_type", "(", "prefix", ",", "suffix", ",", "dir", ")", "if", "suffix", "is", "None", ":", "suffix", "=", "output_type", "(", ")", "if", "prefix", "is", "None", ":", "if", "output_type", "is", "str", ":", "prefix", "=", "template", "else", ":", "prefix", "=", "_os", ".", "fsencode", "(", "template", ")", "if", "dir", "is", "None", ":", "if", "output_type", "is", "str", ":", "dir", "=", "gettempdir", "(", ")", "else", ":", "dir", "=", "gettempdirb", "(", ")", "return", "prefix", ",", "suffix", ",", "dir", ",", "output_type" ]
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/tempfile.py#L118-L133
facebookresearch/pytorch3d
fddd6a700fa9685c1ce2d4b266c111d7db424ecc
pytorch3d/io/pluggable.py
python
IO.register_meshes_format
(self, interpreter: MeshFormatInterpreter)
Register a new interpreter for a new mesh file format. Args: interpreter: the new interpreter to use, which must be an instance of a class which inherits MeshFormatInterpreter.
Register a new interpreter for a new mesh file format.
[ "Register", "a", "new", "interpreter", "for", "a", "new", "mesh", "file", "format", "." ]
def register_meshes_format(self, interpreter: MeshFormatInterpreter) -> None: """ Register a new interpreter for a new mesh file format. Args: interpreter: the new interpreter to use, which must be an instance of a class which inherits MeshFormatInterpreter. """ if not isinstance(interpreter, MeshFormatInterpreter): raise ValueError("Invalid interpreter") self.mesh_interpreters.appendleft(interpreter)
[ "def", "register_meshes_format", "(", "self", ",", "interpreter", ":", "MeshFormatInterpreter", ")", "->", "None", ":", "if", "not", "isinstance", "(", "interpreter", ",", "MeshFormatInterpreter", ")", ":", "raise", "ValueError", "(", "\"Invalid interpreter\"", ")", "self", ".", "mesh_interpreters", ".", "appendleft", "(", "interpreter", ")" ]
https://github.com/facebookresearch/pytorch3d/blob/fddd6a700fa9685c1ce2d4b266c111d7db424ecc/pytorch3d/io/pluggable.py#L84-L94
scikit-hep/scikit-hep
506149b352eeb2291f24aef3f40691b5f6be2da7
skhep/math/vectors.py
python
LorentzVector.rotatez
(self, angle)
return self.rotate(angle, 0, 0, 1)
Rotate vector by a given angle (in radians) around the z axis.
Rotate vector by a given angle (in radians) around the z axis.
[ "Rotate", "vector", "by", "a", "given", "angle", "(", "in", "radians", ")", "around", "the", "z", "axis", "." ]
def rotatez(self, angle): """Rotate vector by a given angle (in radians) around the z axis.""" return self.rotate(angle, 0, 0, 1)
[ "def", "rotatez", "(", "self", ",", "angle", ")", ":", "return", "self", ".", "rotate", "(", "angle", ",", "0", ",", "0", ",", "1", ")" ]
https://github.com/scikit-hep/scikit-hep/blob/506149b352eeb2291f24aef3f40691b5f6be2da7/skhep/math/vectors.py#L1113-L1115
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pip/_vendor/requests/cookies.py
python
RequestsCookieJar.copy
(self)
return new_cj
Return a copy of this RequestsCookieJar.
Return a copy of this RequestsCookieJar.
[ "Return", "a", "copy", "of", "this", "RequestsCookieJar", "." ]
def copy(self): """Return a copy of this RequestsCookieJar.""" new_cj = RequestsCookieJar() new_cj.set_policy(self.get_policy()) new_cj.update(self) return new_cj
[ "def", "copy", "(", "self", ")", ":", "new_cj", "=", "RequestsCookieJar", "(", ")", "new_cj", ".", "set_policy", "(", "self", ".", "get_policy", "(", ")", ")", "new_cj", ".", "update", "(", "self", ")", "return", "new_cj" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pip/_vendor/requests/cookies.py#L414-L419
home-assistant-libs/pychromecast
d7acb9f5ae2c0daa797d78da1a1e8090b4181d21
pychromecast/controllers/media.py
python
MediaStatus.supports_stream_volume
(self)
return bool(self.supported_media_commands & CMD_SUPPORT_STREAM_VOLUME)
True if STREAM_VOLUME is supported.
True if STREAM_VOLUME is supported.
[ "True", "if", "STREAM_VOLUME", "is", "supported", "." ]
def supports_stream_volume(self): """True if STREAM_VOLUME is supported.""" return bool(self.supported_media_commands & CMD_SUPPORT_STREAM_VOLUME)
[ "def", "supports_stream_volume", "(", "self", ")", ":", "return", "bool", "(", "self", ".", "supported_media_commands", "&", "CMD_SUPPORT_STREAM_VOLUME", ")" ]
https://github.com/home-assistant-libs/pychromecast/blob/d7acb9f5ae2c0daa797d78da1a1e8090b4181d21/pychromecast/controllers/media.py#L229-L231
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py-rest/gluon/contrib/memdb.py
python
Rows.__str__
(self)
return s.getvalue()
serializes the table into a csv file
serializes the table into a csv file
[ "serializes", "the", "table", "into", "a", "csv", "file" ]
def __str__(self): """ serializes the table into a csv file """ s = cStringIO.StringIO() writer = csv.writer(s) writer.writerow(self.colnames) c = len(self.colnames) for i in xrange(len(self)): row = [self.response[i][j] for j in xrange(c)] for k in xrange(c): if isinstance(row[k], unicode): row[k] = row[k].encode('utf-8') writer.writerow(row) return s.getvalue()
[ "def", "__str__", "(", "self", ")", ":", "s", "=", "cStringIO", ".", "StringIO", "(", ")", "writer", "=", "csv", ".", "writer", "(", "s", ")", "writer", ".", "writerow", "(", "self", ".", "colnames", ")", "c", "=", "len", "(", "self", ".", "colnames", ")", "for", "i", "in", "xrange", "(", "len", "(", "self", ")", ")", ":", "row", "=", "[", "self", ".", "response", "[", "i", "]", "[", "j", "]", "for", "j", "in", "xrange", "(", "c", ")", "]", "for", "k", "in", "xrange", "(", "c", ")", ":", "if", "isinstance", "(", "row", "[", "k", "]", ",", "unicode", ")", ":", "row", "[", "k", "]", "=", "row", "[", "k", "]", ".", "encode", "(", "'utf-8'", ")", "writer", ".", "writerow", "(", "row", ")", "return", "s", ".", "getvalue", "(", ")" ]
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py-rest/gluon/contrib/memdb.py#L749-L764
newfies-dialer/newfies-dialer
8168b3dd43e9f5ce73a2645b3229def1b2815d47
newfies/survey/templatetags/survey_tags.py
python
section_type_name
(value)
return get_status_value(value, SECTION_TYPE)
survey section type name >>> section_type_name(1) 'Play message' >>> section_type_name(2) 'Multi-choice' >>> section_type_name(0) ''
survey section type name
[ "survey", "section", "type", "name" ]
def section_type_name(value): """survey section type name >>> section_type_name(1) 'Play message' >>> section_type_name(2) 'Multi-choice' >>> section_type_name(0) '' """ return get_status_value(value, SECTION_TYPE)
[ "def", "section_type_name", "(", "value", ")", ":", "return", "get_status_value", "(", "value", ",", "SECTION_TYPE", ")" ]
https://github.com/newfies-dialer/newfies-dialer/blob/8168b3dd43e9f5ce73a2645b3229def1b2815d47/newfies/survey/templatetags/survey_tags.py#L24-L36
MontrealCorpusTools/Montreal-Forced-Aligner
63473f9a4fabd31eec14e1e5022882f85cfdaf31
montreal_forced_aligner/alignment/pretrained.py
python
PretrainedAligner.workflow_identifier
(self)
return "pretrained_aligner"
Aligner identifier
Aligner identifier
[ "Aligner", "identifier" ]
def workflow_identifier(self) -> str: """Aligner identifier""" return "pretrained_aligner"
[ "def", "workflow_identifier", "(", "self", ")", "->", "str", ":", "return", "\"pretrained_aligner\"" ]
https://github.com/MontrealCorpusTools/Montreal-Forced-Aligner/blob/63473f9a4fabd31eec14e1e5022882f85cfdaf31/montreal_forced_aligner/alignment/pretrained.py#L248-L250
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/ultimatelistctrl.py
python
UltimateListCtrl.OnGetItemKind
(self, item)
return 0
This function **must** be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the item kind for the input item. :param `item`: an integer specifying the item index. :note: The base class version always returns 0 (a standard item). :see: :meth:`~UltimateListCtrl.SetItemKind` for a list of valid item kinds.
This function **must** be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the item kind for the input item.
[ "This", "function", "**", "must", "**", "be", "overloaded", "in", "the", "derived", "class", "for", "a", "control", "with", "ULC_VIRTUAL", "style", ".", "It", "should", "return", "the", "item", "kind", "for", "the", "input", "item", "." ]
def OnGetItemKind(self, item): """ This function **must** be overloaded in the derived class for a control with ``ULC_VIRTUAL`` style. It should return the item kind for the input item. :param `item`: an integer specifying the item index. :note: The base class version always returns 0 (a standard item). :see: :meth:`~UltimateListCtrl.SetItemKind` for a list of valid item kinds. """ return 0
[ "def", "OnGetItemKind", "(", "self", ",", "item", ")", ":", "return", "0" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/ultimatelistctrl.py#L12730-L12742
IOActive/XDiFF
552d3394e119ca4ced8115f9fd2d7e26760e40b1
classes/settings.py
python
set_logger
(settings)
return logger
Insantiate the logging functionality
Insantiate the logging functionality
[ "Insantiate", "the", "logging", "functionality" ]
def set_logger(settings): """Insantiate the logging functionality""" logging.basicConfig(filename='fuzz.log', level=logging.INFO, format='%(asctime)s %(levelname)s %(module)s: %(message)s', datefmt='%Y-%m-%d %H.%M.%S') console = logging.StreamHandler() console.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(module)s: %(message)s')) logger = logging.getLogger('fuzzer') logger.addHandler(console) if 'loglevel' in settings and settings['loglevel'] == 'debug': logger.setLevel(logging.DEBUG) elif 'loglevel' in settings and settings['loglevel'] == 'critical': logger.setLevel(logging.CRITICAL) return logger
[ "def", "set_logger", "(", "settings", ")", ":", "logging", ".", "basicConfig", "(", "filename", "=", "'fuzz.log'", ",", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(asctime)s %(levelname)s %(module)s: %(message)s'", ",", "datefmt", "=", "'%Y-%m-%d %H.%M.%S'", ")", "console", "=", "logging", ".", "StreamHandler", "(", ")", "console", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "'%(asctime)s %(levelname)s %(module)s: %(message)s'", ")", ")", "logger", "=", "logging", ".", "getLogger", "(", "'fuzzer'", ")", "logger", ".", "addHandler", "(", "console", ")", "if", "'loglevel'", "in", "settings", "and", "settings", "[", "'loglevel'", "]", "==", "'debug'", ":", "logger", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "elif", "'loglevel'", "in", "settings", "and", "settings", "[", "'loglevel'", "]", "==", "'critical'", ":", "logger", ".", "setLevel", "(", "logging", ".", "CRITICAL", ")", "return", "logger" ]
https://github.com/IOActive/XDiFF/blob/552d3394e119ca4ced8115f9fd2d7e26760e40b1/classes/settings.py#L79-L90
openstack/swift
b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100
swift/common/middleware/tempurl.py
python
TempURL.__call__
(self, env, start_response)
return self.app(env, _start_response)
Main hook into the WSGI paste.deploy filter/app pipeline. :param env: The WSGI environment dict. :param start_response: The WSGI start_response hook. :returns: Response as per WSGI.
Main hook into the WSGI paste.deploy filter/app pipeline.
[ "Main", "hook", "into", "the", "WSGI", "paste", ".", "deploy", "filter", "/", "app", "pipeline", "." ]
def __call__(self, env, start_response): """ Main hook into the WSGI paste.deploy filter/app pipeline. :param env: The WSGI environment dict. :param start_response: The WSGI start_response hook. :returns: Response as per WSGI. """ if env['REQUEST_METHOD'] == 'OPTIONS': return self.app(env, start_response) info = self._get_temp_url_info(env) temp_url_sig, temp_url_expires, temp_url_prefix, filename,\ inline_disposition, temp_url_ip_range = info if temp_url_sig is None and temp_url_expires is None: return self.app(env, start_response) if not temp_url_sig or not temp_url_expires: return self._invalid(env, start_response) if ':' in temp_url_sig: hash_algorithm, temp_url_sig = temp_url_sig.split(':', 1) if ('-' in temp_url_sig or '_' in temp_url_sig) and not ( '+' in temp_url_sig or '/' in temp_url_sig): temp_url_sig = temp_url_sig.replace('-', '+').replace('_', '/') try: temp_url_sig = binascii.hexlify(strict_b64decode( temp_url_sig + '==')) if not six.PY2: temp_url_sig = temp_url_sig.decode('ascii') except ValueError: return self._invalid(env, start_response) elif len(temp_url_sig) == 40: hash_algorithm = 'sha1' elif len(temp_url_sig) == 64: hash_algorithm = 'sha256' else: return self._invalid(env, start_response) if hash_algorithm not in self.allowed_digests: return self._invalid(env, start_response) account, container, obj = self._get_path_parts(env) if not account: return self._invalid(env, start_response) if temp_url_ip_range: client_address = env.get('REMOTE_ADDR') if client_address is None: return self._invalid(env, start_response) try: allowed_ip_ranges = ip_network(six.u(temp_url_ip_range)) if ip_address(six.u(client_address)) not in allowed_ip_ranges: return self._invalid(env, start_response) except ValueError: return self._invalid(env, start_response) keys = self._get_keys(env) if not keys: return self._invalid(env, start_response) if temp_url_prefix is None: path = '/v1/%s/%s/%s' % (account, container, obj) else: if not obj.startswith(temp_url_prefix): return self._invalid(env, start_response) path = 'prefix:/v1/%s/%s/%s' % (account, container, temp_url_prefix) if env['REQUEST_METHOD'] == 'HEAD': hmac_vals = [ hmac for method in ('HEAD', 'GET', 'POST', 'PUT') for hmac in self._get_hmacs( env, temp_url_expires, path, keys, hash_algorithm, request_method=method, ip_range=temp_url_ip_range)] else: hmac_vals = self._get_hmacs( env, temp_url_expires, path, keys, hash_algorithm, ip_range=temp_url_ip_range) is_valid_hmac = False hmac_scope = None for hmac, scope in hmac_vals: # While it's true that we short-circuit, this doesn't affect the # timing-attack resistance since the only way this will # short-circuit is when a valid signature is passed in. if streq_const_time(temp_url_sig, hmac): is_valid_hmac = True hmac_scope = scope break if not is_valid_hmac: return self._invalid(env, start_response) # disallowed headers prevent accidentally allowing upload of a pointer # to data that the PUT tempurl would not otherwise allow access for. # It should be safe to provide a GET tempurl for data that an # untrusted client just uploaded with a PUT tempurl. resp = self._clean_disallowed_headers(env, start_response) if resp: return resp self._clean_incoming_headers(env) if hmac_scope == ACCOUNT_SCOPE: env['swift.authorize'] = authorize_same_account(account) else: env['swift.authorize'] = authorize_same_container(account, container) env['swift.authorize_override'] = True env['REMOTE_USER'] = '.wsgi.tempurl' qs = {'temp_url_sig': temp_url_sig, 'temp_url_expires': temp_url_expires} if temp_url_prefix is not None: qs['temp_url_prefix'] = temp_url_prefix if filename: qs['filename'] = filename env['QUERY_STRING'] = urlencode(qs) def _start_response(status, headers, exc_info=None): headers = self._clean_outgoing_headers(headers) if env['REQUEST_METHOD'] in ('GET', 'HEAD') and status[0] == '2': # figure out the right value for content-disposition # 1) use the value from the query string # 2) use the value from the object metadata # 3) use the object name (default) out_headers = [] existing_disposition = None for h, v in headers: if h.lower() != 'content-disposition': out_headers.append((h, v)) else: existing_disposition = v if inline_disposition: if filename: disposition_value = disposition_format('inline', filename) else: disposition_value = 'inline' elif filename: disposition_value = disposition_format('attachment', filename) elif existing_disposition: disposition_value = existing_disposition else: name = basename(wsgi_to_str(env['PATH_INFO']).rstrip('/')) disposition_value = disposition_format('attachment', name) # this is probably just paranoia, I couldn't actually get a # newline into existing_disposition value = disposition_value.replace('\n', '%0A') out_headers.append(('Content-Disposition', value)) # include Expires header for better cache-control out_headers.append(('Expires', strftime( "%a, %d %b %Y %H:%M:%S GMT", gmtime(temp_url_expires)))) headers = out_headers return start_response(status, headers, exc_info) return self.app(env, _start_response)
[ "def", "__call__", "(", "self", ",", "env", ",", "start_response", ")", ":", "if", "env", "[", "'REQUEST_METHOD'", "]", "==", "'OPTIONS'", ":", "return", "self", ".", "app", "(", "env", ",", "start_response", ")", "info", "=", "self", ".", "_get_temp_url_info", "(", "env", ")", "temp_url_sig", ",", "temp_url_expires", ",", "temp_url_prefix", ",", "filename", ",", "inline_disposition", ",", "temp_url_ip_range", "=", "info", "if", "temp_url_sig", "is", "None", "and", "temp_url_expires", "is", "None", ":", "return", "self", ".", "app", "(", "env", ",", "start_response", ")", "if", "not", "temp_url_sig", "or", "not", "temp_url_expires", ":", "return", "self", ".", "_invalid", "(", "env", ",", "start_response", ")", "if", "':'", "in", "temp_url_sig", ":", "hash_algorithm", ",", "temp_url_sig", "=", "temp_url_sig", ".", "split", "(", "':'", ",", "1", ")", "if", "(", "'-'", "in", "temp_url_sig", "or", "'_'", "in", "temp_url_sig", ")", "and", "not", "(", "'+'", "in", "temp_url_sig", "or", "'/'", "in", "temp_url_sig", ")", ":", "temp_url_sig", "=", "temp_url_sig", ".", "replace", "(", "'-'", ",", "'+'", ")", ".", "replace", "(", "'_'", ",", "'/'", ")", "try", ":", "temp_url_sig", "=", "binascii", ".", "hexlify", "(", "strict_b64decode", "(", "temp_url_sig", "+", "'=='", ")", ")", "if", "not", "six", ".", "PY2", ":", "temp_url_sig", "=", "temp_url_sig", ".", "decode", "(", "'ascii'", ")", "except", "ValueError", ":", "return", "self", ".", "_invalid", "(", "env", ",", "start_response", ")", "elif", "len", "(", "temp_url_sig", ")", "==", "40", ":", "hash_algorithm", "=", "'sha1'", "elif", "len", "(", "temp_url_sig", ")", "==", "64", ":", "hash_algorithm", "=", "'sha256'", "else", ":", "return", "self", ".", "_invalid", "(", "env", ",", "start_response", ")", "if", "hash_algorithm", "not", "in", "self", ".", "allowed_digests", ":", "return", "self", ".", "_invalid", "(", "env", ",", "start_response", ")", "account", ",", "container", ",", "obj", "=", "self", ".", "_get_path_parts", "(", "env", ")", "if", "not", "account", ":", "return", "self", ".", "_invalid", "(", "env", ",", "start_response", ")", "if", "temp_url_ip_range", ":", "client_address", "=", "env", ".", "get", "(", "'REMOTE_ADDR'", ")", "if", "client_address", "is", "None", ":", "return", "self", ".", "_invalid", "(", "env", ",", "start_response", ")", "try", ":", "allowed_ip_ranges", "=", "ip_network", "(", "six", ".", "u", "(", "temp_url_ip_range", ")", ")", "if", "ip_address", "(", "six", ".", "u", "(", "client_address", ")", ")", "not", "in", "allowed_ip_ranges", ":", "return", "self", ".", "_invalid", "(", "env", ",", "start_response", ")", "except", "ValueError", ":", "return", "self", ".", "_invalid", "(", "env", ",", "start_response", ")", "keys", "=", "self", ".", "_get_keys", "(", "env", ")", "if", "not", "keys", ":", "return", "self", ".", "_invalid", "(", "env", ",", "start_response", ")", "if", "temp_url_prefix", "is", "None", ":", "path", "=", "'/v1/%s/%s/%s'", "%", "(", "account", ",", "container", ",", "obj", ")", "else", ":", "if", "not", "obj", ".", "startswith", "(", "temp_url_prefix", ")", ":", "return", "self", ".", "_invalid", "(", "env", ",", "start_response", ")", "path", "=", "'prefix:/v1/%s/%s/%s'", "%", "(", "account", ",", "container", ",", "temp_url_prefix", ")", "if", "env", "[", "'REQUEST_METHOD'", "]", "==", "'HEAD'", ":", "hmac_vals", "=", "[", "hmac", "for", "method", "in", "(", "'HEAD'", ",", "'GET'", ",", "'POST'", ",", "'PUT'", ")", "for", "hmac", "in", "self", ".", "_get_hmacs", "(", "env", ",", "temp_url_expires", ",", "path", ",", "keys", ",", "hash_algorithm", ",", "request_method", "=", "method", ",", "ip_range", "=", "temp_url_ip_range", ")", "]", "else", ":", "hmac_vals", "=", "self", ".", "_get_hmacs", "(", "env", ",", "temp_url_expires", ",", "path", ",", "keys", ",", "hash_algorithm", ",", "ip_range", "=", "temp_url_ip_range", ")", "is_valid_hmac", "=", "False", "hmac_scope", "=", "None", "for", "hmac", ",", "scope", "in", "hmac_vals", ":", "# While it's true that we short-circuit, this doesn't affect the", "# timing-attack resistance since the only way this will", "# short-circuit is when a valid signature is passed in.", "if", "streq_const_time", "(", "temp_url_sig", ",", "hmac", ")", ":", "is_valid_hmac", "=", "True", "hmac_scope", "=", "scope", "break", "if", "not", "is_valid_hmac", ":", "return", "self", ".", "_invalid", "(", "env", ",", "start_response", ")", "# disallowed headers prevent accidentally allowing upload of a pointer", "# to data that the PUT tempurl would not otherwise allow access for.", "# It should be safe to provide a GET tempurl for data that an", "# untrusted client just uploaded with a PUT tempurl.", "resp", "=", "self", ".", "_clean_disallowed_headers", "(", "env", ",", "start_response", ")", "if", "resp", ":", "return", "resp", "self", ".", "_clean_incoming_headers", "(", "env", ")", "if", "hmac_scope", "==", "ACCOUNT_SCOPE", ":", "env", "[", "'swift.authorize'", "]", "=", "authorize_same_account", "(", "account", ")", "else", ":", "env", "[", "'swift.authorize'", "]", "=", "authorize_same_container", "(", "account", ",", "container", ")", "env", "[", "'swift.authorize_override'", "]", "=", "True", "env", "[", "'REMOTE_USER'", "]", "=", "'.wsgi.tempurl'", "qs", "=", "{", "'temp_url_sig'", ":", "temp_url_sig", ",", "'temp_url_expires'", ":", "temp_url_expires", "}", "if", "temp_url_prefix", "is", "not", "None", ":", "qs", "[", "'temp_url_prefix'", "]", "=", "temp_url_prefix", "if", "filename", ":", "qs", "[", "'filename'", "]", "=", "filename", "env", "[", "'QUERY_STRING'", "]", "=", "urlencode", "(", "qs", ")", "def", "_start_response", "(", "status", ",", "headers", ",", "exc_info", "=", "None", ")", ":", "headers", "=", "self", ".", "_clean_outgoing_headers", "(", "headers", ")", "if", "env", "[", "'REQUEST_METHOD'", "]", "in", "(", "'GET'", ",", "'HEAD'", ")", "and", "status", "[", "0", "]", "==", "'2'", ":", "# figure out the right value for content-disposition", "# 1) use the value from the query string", "# 2) use the value from the object metadata", "# 3) use the object name (default)", "out_headers", "=", "[", "]", "existing_disposition", "=", "None", "for", "h", ",", "v", "in", "headers", ":", "if", "h", ".", "lower", "(", ")", "!=", "'content-disposition'", ":", "out_headers", ".", "append", "(", "(", "h", ",", "v", ")", ")", "else", ":", "existing_disposition", "=", "v", "if", "inline_disposition", ":", "if", "filename", ":", "disposition_value", "=", "disposition_format", "(", "'inline'", ",", "filename", ")", "else", ":", "disposition_value", "=", "'inline'", "elif", "filename", ":", "disposition_value", "=", "disposition_format", "(", "'attachment'", ",", "filename", ")", "elif", "existing_disposition", ":", "disposition_value", "=", "existing_disposition", "else", ":", "name", "=", "basename", "(", "wsgi_to_str", "(", "env", "[", "'PATH_INFO'", "]", ")", ".", "rstrip", "(", "'/'", ")", ")", "disposition_value", "=", "disposition_format", "(", "'attachment'", ",", "name", ")", "# this is probably just paranoia, I couldn't actually get a", "# newline into existing_disposition", "value", "=", "disposition_value", ".", "replace", "(", "'\\n'", ",", "'%0A'", ")", "out_headers", ".", "append", "(", "(", "'Content-Disposition'", ",", "value", ")", ")", "# include Expires header for better cache-control", "out_headers", ".", "append", "(", "(", "'Expires'", ",", "strftime", "(", "\"%a, %d %b %Y %H:%M:%S GMT\"", ",", "gmtime", "(", "temp_url_expires", ")", ")", ")", ")", "headers", "=", "out_headers", "return", "start_response", "(", "status", ",", "headers", ",", "exc_info", ")", "return", "self", ".", "app", "(", "env", ",", "_start_response", ")" ]
https://github.com/openstack/swift/blob/b8d7c3dcb817504dcc0959ba52cc4ed2cf66c100/swift/common/middleware/tempurl.py#L490-L642
twopirllc/pandas-ta
b92e45c0b8f035ac76292f8f130be32ec49b2ef4
pandas_ta/overlap/sma.py
python
sma
(close, length=None, talib=None, offset=None, **kwargs)
return sma
Indicator: Simple Moving Average (SMA)
Indicator: Simple Moving Average (SMA)
[ "Indicator", ":", "Simple", "Moving", "Average", "(", "SMA", ")" ]
def sma(close, length=None, talib=None, offset=None, **kwargs): """Indicator: Simple Moving Average (SMA)""" # Validate Arguments length = int(length) if length and length > 0 else 10 min_periods = int(kwargs["min_periods"]) if "min_periods" in kwargs and kwargs["min_periods"] is not None else length close = verify_series(close, max(length, min_periods)) offset = get_offset(offset) mode_tal = bool(talib) if isinstance(talib, bool) else True if close is None: return # Calculate Result if Imports["talib"] and mode_tal: from talib import SMA sma = SMA(close, length) else: sma = close.rolling(length, min_periods=min_periods).mean() # Offset if offset != 0: sma = sma.shift(offset) # Handle fills if "fillna" in kwargs: sma.fillna(kwargs["fillna"], inplace=True) if "fill_method" in kwargs: sma.fillna(method=kwargs["fill_method"], inplace=True) # Name & Category sma.name = f"SMA_{length}" sma.category = "overlap" return sma
[ "def", "sma", "(", "close", ",", "length", "=", "None", ",", "talib", "=", "None", ",", "offset", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Validate Arguments", "length", "=", "int", "(", "length", ")", "if", "length", "and", "length", ">", "0", "else", "10", "min_periods", "=", "int", "(", "kwargs", "[", "\"min_periods\"", "]", ")", "if", "\"min_periods\"", "in", "kwargs", "and", "kwargs", "[", "\"min_periods\"", "]", "is", "not", "None", "else", "length", "close", "=", "verify_series", "(", "close", ",", "max", "(", "length", ",", "min_periods", ")", ")", "offset", "=", "get_offset", "(", "offset", ")", "mode_tal", "=", "bool", "(", "talib", ")", "if", "isinstance", "(", "talib", ",", "bool", ")", "else", "True", "if", "close", "is", "None", ":", "return", "# Calculate Result", "if", "Imports", "[", "\"talib\"", "]", "and", "mode_tal", ":", "from", "talib", "import", "SMA", "sma", "=", "SMA", "(", "close", ",", "length", ")", "else", ":", "sma", "=", "close", ".", "rolling", "(", "length", ",", "min_periods", "=", "min_periods", ")", ".", "mean", "(", ")", "# Offset", "if", "offset", "!=", "0", ":", "sma", "=", "sma", ".", "shift", "(", "offset", ")", "# Handle fills", "if", "\"fillna\"", "in", "kwargs", ":", "sma", ".", "fillna", "(", "kwargs", "[", "\"fillna\"", "]", ",", "inplace", "=", "True", ")", "if", "\"fill_method\"", "in", "kwargs", ":", "sma", ".", "fillna", "(", "method", "=", "kwargs", "[", "\"fill_method\"", "]", ",", "inplace", "=", "True", ")", "# Name & Category", "sma", ".", "name", "=", "f\"SMA_{length}\"", "sma", ".", "category", "=", "\"overlap\"", "return", "sma" ]
https://github.com/twopirllc/pandas-ta/blob/b92e45c0b8f035ac76292f8f130be32ec49b2ef4/pandas_ta/overlap/sma.py#L6-L38
cloudinary/pycloudinary
a61a9687c8933f23574c38e27f201358e540ee64
cloudinary/utils.py
python
build_list_of_dicts
(val)
return val
Converts a value that can be presented as a list of dict. In case top level item is not a list, it is wrapped with a list Valid values examples: - Valid dict: {"k": "v", "k2","v2"} - List of dict: [{"k": "v"}, {"k2","v2"}] - JSON decodable string: '{"k": "v"}', or '[{"k": "v"}]' - List of JSON decodable strings: ['{"k": "v"}', '{"k2","v2"}'] Invalid values examples: - ["not", "a", "dict"] - [123, None], - [["another", "list"]] :param val: Input value :type val: Union[list, dict, str] :return: Converted(or original) list of dict :raises: ValueError in case value cannot be converted to a list of dict
Converts a value that can be presented as a list of dict.
[ "Converts", "a", "value", "that", "can", "be", "presented", "as", "a", "list", "of", "dict", "." ]
def build_list_of_dicts(val): """ Converts a value that can be presented as a list of dict. In case top level item is not a list, it is wrapped with a list Valid values examples: - Valid dict: {"k": "v", "k2","v2"} - List of dict: [{"k": "v"}, {"k2","v2"}] - JSON decodable string: '{"k": "v"}', or '[{"k": "v"}]' - List of JSON decodable strings: ['{"k": "v"}', '{"k2","v2"}'] Invalid values examples: - ["not", "a", "dict"] - [123, None], - [["another", "list"]] :param val: Input value :type val: Union[list, dict, str] :return: Converted(or original) list of dict :raises: ValueError in case value cannot be converted to a list of dict """ if val is None: return [] if isinstance(val, str): # use OrderedDict to preserve order val = json.loads(val, object_pairs_hook=OrderedDict) if isinstance(val, dict): val = [val] for index, item in enumerate(val): if isinstance(item, str): # use OrderedDict to preserve order val[index] = json.loads(item, object_pairs_hook=OrderedDict) if not isinstance(val[index], dict): raise ValueError("Expected a list of dicts") return val
[ "def", "build_list_of_dicts", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "[", "]", "if", "isinstance", "(", "val", ",", "str", ")", ":", "# use OrderedDict to preserve order", "val", "=", "json", ".", "loads", "(", "val", ",", "object_pairs_hook", "=", "OrderedDict", ")", "if", "isinstance", "(", "val", ",", "dict", ")", ":", "val", "=", "[", "val", "]", "for", "index", ",", "item", "in", "enumerate", "(", "val", ")", ":", "if", "isinstance", "(", "item", ",", "str", ")", ":", "# use OrderedDict to preserve order", "val", "[", "index", "]", "=", "json", ".", "loads", "(", "item", ",", "object_pairs_hook", "=", "OrderedDict", ")", "if", "not", "isinstance", "(", "val", "[", "index", "]", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"Expected a list of dicts\"", ")", "return", "val" ]
https://github.com/cloudinary/pycloudinary/blob/a61a9687c8933f23574c38e27f201358e540ee64/cloudinary/utils.py#L170-L209
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/cinder/cinder/volume/drivers/scality.py
python
ScalityDriver._check_prerequisites
(self)
Sanity checks before attempting to mount SOFS.
Sanity checks before attempting to mount SOFS.
[ "Sanity", "checks", "before", "attempting", "to", "mount", "SOFS", "." ]
def _check_prerequisites(self): """Sanity checks before attempting to mount SOFS.""" # config is mandatory config = FLAGS.scality_sofs_config if not config: msg = _("Value required for 'scality_sofs_config'") LOG.warn(msg) raise exception.VolumeBackendAPIException(data=msg) # config can be a file path or a URL, check it if urlparse.urlparse(config).scheme == '': # turn local path into URL config = 'file://%s' % config try: urllib2.urlopen(config, timeout=5).close() except urllib2.URLError as e: msg = _("Cannot access 'scality_sofs_config': %s") % e LOG.warn(msg) raise exception.VolumeBackendAPIException(data=msg) # mount.sofs must be installed if not os.access('/sbin/mount.sofs', os.X_OK): msg = _("Cannot execute /sbin/mount.sofs") LOG.warn(msg) raise exception.VolumeBackendAPIException(data=msg)
[ "def", "_check_prerequisites", "(", "self", ")", ":", "# config is mandatory", "config", "=", "FLAGS", ".", "scality_sofs_config", "if", "not", "config", ":", "msg", "=", "_", "(", "\"Value required for 'scality_sofs_config'\"", ")", "LOG", ".", "warn", "(", "msg", ")", "raise", "exception", ".", "VolumeBackendAPIException", "(", "data", "=", "msg", ")", "# config can be a file path or a URL, check it", "if", "urlparse", ".", "urlparse", "(", "config", ")", ".", "scheme", "==", "''", ":", "# turn local path into URL", "config", "=", "'file://%s'", "%", "config", "try", ":", "urllib2", ".", "urlopen", "(", "config", ",", "timeout", "=", "5", ")", ".", "close", "(", ")", "except", "urllib2", ".", "URLError", "as", "e", ":", "msg", "=", "_", "(", "\"Cannot access 'scality_sofs_config': %s\"", ")", "%", "e", "LOG", ".", "warn", "(", "msg", ")", "raise", "exception", ".", "VolumeBackendAPIException", "(", "data", "=", "msg", ")", "# mount.sofs must be installed", "if", "not", "os", ".", "access", "(", "'/sbin/mount.sofs'", ",", "os", ".", "X_OK", ")", ":", "msg", "=", "_", "(", "\"Cannot execute /sbin/mount.sofs\"", ")", "LOG", ".", "warn", "(", "msg", ")", "raise", "exception", ".", "VolumeBackendAPIException", "(", "data", "=", "msg", ")" ]
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/cinder/cinder/volume/drivers/scality.py#L57-L82
OCA/account-financial-tools
98d07b6448530d44bec195ff528b7a9452da1eae
account_chart_update/wizard/wizard_chart_update.py
python
WizardUpdateChartsAccounts._update_fiscal_positions
(self)
Process fiscal position templates to create/update.
Process fiscal position templates to create/update.
[ "Process", "fiscal", "position", "templates", "to", "create", "/", "update", "." ]
def _update_fiscal_positions(self): """Process fiscal position templates to create/update.""" for wiz_fp in self.fiscal_position_ids: fp, template = (wiz_fp.update_fiscal_position_id, wiz_fp.fiscal_position_id) if wiz_fp.type == "new": # Create a new fiscal position self.chart_template_id.create_record_with_xmlid( self.company_id, template, "account.fiscal.position", self._prepare_fp_vals(template), ) _logger.info(_("Created fiscal position %s."), "'%s'" % template.name) else: for key, value in self.diff_fields(template, fp).items(): fp[key] = value _logger.info( _("Updated fiscal position %s."), "'%s'" % template.name ) if self.recreate_xml_ids and self.missing_xml_id(template, fp): self.recreate_xml_id(template, fp) _logger.info( _("Updated fiscal position %s. (Recreated XML-ID)"), "'%s'" % template.name, )
[ "def", "_update_fiscal_positions", "(", "self", ")", ":", "for", "wiz_fp", "in", "self", ".", "fiscal_position_ids", ":", "fp", ",", "template", "=", "(", "wiz_fp", ".", "update_fiscal_position_id", ",", "wiz_fp", ".", "fiscal_position_id", ")", "if", "wiz_fp", ".", "type", "==", "\"new\"", ":", "# Create a new fiscal position", "self", ".", "chart_template_id", ".", "create_record_with_xmlid", "(", "self", ".", "company_id", ",", "template", ",", "\"account.fiscal.position\"", ",", "self", ".", "_prepare_fp_vals", "(", "template", ")", ",", ")", "_logger", ".", "info", "(", "_", "(", "\"Created fiscal position %s.\"", ")", ",", "\"'%s'\"", "%", "template", ".", "name", ")", "else", ":", "for", "key", ",", "value", "in", "self", ".", "diff_fields", "(", "template", ",", "fp", ")", ".", "items", "(", ")", ":", "fp", "[", "key", "]", "=", "value", "_logger", ".", "info", "(", "_", "(", "\"Updated fiscal position %s.\"", ")", ",", "\"'%s'\"", "%", "template", ".", "name", ")", "if", "self", ".", "recreate_xml_ids", "and", "self", ".", "missing_xml_id", "(", "template", ",", "fp", ")", ":", "self", ".", "recreate_xml_id", "(", "template", ",", "fp", ")", "_logger", ".", "info", "(", "_", "(", "\"Updated fiscal position %s. (Recreated XML-ID)\"", ")", ",", "\"'%s'\"", "%", "template", ".", "name", ",", ")" ]
https://github.com/OCA/account-financial-tools/blob/98d07b6448530d44bec195ff528b7a9452da1eae/account_chart_update/wizard/wizard_chart_update.py#L1052-L1077
hacktoolkit/django-htk
902f3780630f1308aa97a70b9b62a5682239ff2d
apps/accounts/api/views.py
python
username
(request)
return response
Update a User's username
Update a User's username
[ "Update", "a", "User", "s", "username" ]
def username(request): """Update a User's username """ user = request.user username_form = ChangeUsernameForm(user, request.POST) if username_form.is_valid(): username_form.save(user) response = json_response_okay() else: obj = { HTK_API_JSON_KEY_STATUS: HTK_API_JSON_VALUE_ERROR, 'error' : get_form_error(username_form) } response = json_response(obj) return response
[ "def", "username", "(", "request", ")", ":", "user", "=", "request", ".", "user", "username_form", "=", "ChangeUsernameForm", "(", "user", ",", "request", ".", "POST", ")", "if", "username_form", ".", "is_valid", "(", ")", ":", "username_form", ".", "save", "(", "user", ")", "response", "=", "json_response_okay", "(", ")", "else", ":", "obj", "=", "{", "HTK_API_JSON_KEY_STATUS", ":", "HTK_API_JSON_VALUE_ERROR", ",", "'error'", ":", "get_form_error", "(", "username_form", ")", "}", "response", "=", "json_response", "(", "obj", ")", "return", "response" ]
https://github.com/hacktoolkit/django-htk/blob/902f3780630f1308aa97a70b9b62a5682239ff2d/apps/accounts/api/views.py#L104-L118
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/OpenSSL/crypto.py
python
dump_certificate_request
(type, req)
return _bio_to_string(bio)
Dump a certificate request to a buffer :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param req: The certificate request to dump :return: The buffer with the dumped certificate request in
Dump a certificate request to a buffer
[ "Dump", "a", "certificate", "request", "to", "a", "buffer" ]
def dump_certificate_request(type, req): """ Dump a certificate request to a buffer :param type: The file type (one of FILETYPE_PEM, FILETYPE_ASN1) :param req: The certificate request to dump :return: The buffer with the dumped certificate request in """ bio = _new_mem_buf() if type == FILETYPE_PEM: result_code = _lib.PEM_write_bio_X509_REQ(bio, req._req) elif type == FILETYPE_ASN1: result_code = _lib.i2d_X509_REQ_bio(bio, req._req) elif type == FILETYPE_TEXT: result_code = _lib.X509_REQ_print_ex(bio, req._req, 0, 0) else: raise ValueError("type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT") if result_code == 0: # TODO: This is untested. _raise_current_error() return _bio_to_string(bio)
[ "def", "dump_certificate_request", "(", "type", ",", "req", ")", ":", "bio", "=", "_new_mem_buf", "(", ")", "if", "type", "==", "FILETYPE_PEM", ":", "result_code", "=", "_lib", ".", "PEM_write_bio_X509_REQ", "(", "bio", ",", "req", ".", "_req", ")", "elif", "type", "==", "FILETYPE_ASN1", ":", "result_code", "=", "_lib", ".", "i2d_X509_REQ_bio", "(", "bio", ",", "req", ".", "_req", ")", "elif", "type", "==", "FILETYPE_TEXT", ":", "result_code", "=", "_lib", ".", "X509_REQ_print_ex", "(", "bio", ",", "req", ".", "_req", ",", "0", ",", "0", ")", "else", ":", "raise", "ValueError", "(", "\"type argument must be FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT\"", ")", "if", "result_code", "==", "0", ":", "# TODO: This is untested.", "_raise_current_error", "(", ")", "return", "_bio_to_string", "(", "bio", ")" ]
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/OpenSSL/crypto.py#L2331-L2354
OpenAgricultureFoundation/openag-device-software
a51d2de399c0a6781ae51d0dcfaae1583d75f346
device/peripherals/modules/atlas_co2/scripts/run_driver.py
python
DriverRunner.run
(self, *args: Any, **kwargs: Any)
Runs driver.
Runs driver.
[ "Runs", "driver", "." ]
def run(self, *args: Any, **kwargs: Any): """Runs driver.""" # Run parent class super().run(*args, **kwargs) # Check if reading pH if self.args.co2: print("CO2: {} ppm".format(self.driver.read_co2())) elif self.args.enable_temp: self.driver.enable_internal_temperature() elif self.args.disable_temp: self.driver.disable_internal_temperature() elif self.args.temp: print("Internal Temp: {} C".format(self.driver.read_internal_temperature()))
[ "def", "run", "(", "self", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", ":", "# Run parent class", "super", "(", ")", ".", "run", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Check if reading pH", "if", "self", ".", "args", ".", "co2", ":", "print", "(", "\"CO2: {} ppm\"", ".", "format", "(", "self", ".", "driver", ".", "read_co2", "(", ")", ")", ")", "elif", "self", ".", "args", ".", "enable_temp", ":", "self", ".", "driver", ".", "enable_internal_temperature", "(", ")", "elif", "self", ".", "args", ".", "disable_temp", ":", "self", ".", "driver", ".", "disable_internal_temperature", "(", ")", "elif", "self", ".", "args", ".", "temp", ":", "print", "(", "\"Internal Temp: {} C\"", ".", "format", "(", "self", ".", "driver", ".", "read_internal_temperature", "(", ")", ")", ")" ]
https://github.com/OpenAgricultureFoundation/openag-device-software/blob/a51d2de399c0a6781ae51d0dcfaae1583d75f346/device/peripherals/modules/atlas_co2/scripts/run_driver.py#L48-L62
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/PIL/PngImagePlugin.py
python
_safe_zlib_decompress
(s)
return plaintext
[]
def _safe_zlib_decompress(s): dobj = zlib.decompressobj() plaintext = dobj.decompress(s, MAX_TEXT_CHUNK) if dobj.unconsumed_tail: raise ValueError("Decompressed Data Too Large") return plaintext
[ "def", "_safe_zlib_decompress", "(", "s", ")", ":", "dobj", "=", "zlib", ".", "decompressobj", "(", ")", "plaintext", "=", "dobj", ".", "decompress", "(", "s", ",", "MAX_TEXT_CHUNK", ")", "if", "dobj", ".", "unconsumed_tail", ":", "raise", "ValueError", "(", "\"Decompressed Data Too Large\"", ")", "return", "plaintext" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/PIL/PngImagePlugin.py#L81-L86
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/cisco-ise/Integrations/cisco-ise/cisco-ise.py
python
get_all_nodes_command
()
Returns all nodes in the Cisco ISE Deployment Also sets isLocalIstance in the output
Returns all nodes in the Cisco ISE Deployment Also sets isLocalIstance in the output
[ "Returns", "all", "nodes", "in", "the", "Cisco", "ISE", "Deployment", "Also", "sets", "isLocalIstance", "in", "the", "output" ]
def get_all_nodes_command(): """ Returns all nodes in the Cisco ISE Deployment Also sets isLocalIstance in the output """ instance_ip = urlparse(BASE_URL).netloc try: instance_ip = socket.gethostbyname(instance_ip) except Exception as e: err_msg = (f'Failed to get ip address of configured Cisco ISE instance - {e}') raise Exception(err_msg) data = [] api_endpoint = '/ers/config/node' response = http_request('GET', api_endpoint) results = response.get('SearchResult', {}) if results.get('total', 0) < 1: demisto.results("No Nodes were found") node_data = results.get('resources', []) for node in node_data: is_local_istance = False name = node.get('name') node_details = get_node_details(name).get('Node', {}) ip = node_details.get('ipAddress') if ip == instance_ip: is_local_istance = True data.append({ 'Name': name, 'ip': ip, 'isLocalIstance': is_local_istance, # if false then standalone mode.. ie single node 'inDeployment': node_details.get('inDeployment'), # primary means active node 'primaryPapNode': node_details.get('primaryPapNode'), }) context = { 'CiscoISE.NodesData': data } return_outputs(tableToMarkdown('CiscoISE deployment nodes', data, removeNull=True), context)
[ "def", "get_all_nodes_command", "(", ")", ":", "instance_ip", "=", "urlparse", "(", "BASE_URL", ")", ".", "netloc", "try", ":", "instance_ip", "=", "socket", ".", "gethostbyname", "(", "instance_ip", ")", "except", "Exception", "as", "e", ":", "err_msg", "=", "(", "f'Failed to get ip address of configured Cisco ISE instance - {e}'", ")", "raise", "Exception", "(", "err_msg", ")", "data", "=", "[", "]", "api_endpoint", "=", "'/ers/config/node'", "response", "=", "http_request", "(", "'GET'", ",", "api_endpoint", ")", "results", "=", "response", ".", "get", "(", "'SearchResult'", ",", "{", "}", ")", "if", "results", ".", "get", "(", "'total'", ",", "0", ")", "<", "1", ":", "demisto", ".", "results", "(", "\"No Nodes were found\"", ")", "node_data", "=", "results", ".", "get", "(", "'resources'", ",", "[", "]", ")", "for", "node", "in", "node_data", ":", "is_local_istance", "=", "False", "name", "=", "node", ".", "get", "(", "'name'", ")", "node_details", "=", "get_node_details", "(", "name", ")", ".", "get", "(", "'Node'", ",", "{", "}", ")", "ip", "=", "node_details", ".", "get", "(", "'ipAddress'", ")", "if", "ip", "==", "instance_ip", ":", "is_local_istance", "=", "True", "data", ".", "append", "(", "{", "'Name'", ":", "name", ",", "'ip'", ":", "ip", ",", "'isLocalIstance'", ":", "is_local_istance", ",", "# if false then standalone mode.. ie single node", "'inDeployment'", ":", "node_details", ".", "get", "(", "'inDeployment'", ")", ",", "# primary means active node", "'primaryPapNode'", ":", "node_details", ".", "get", "(", "'primaryPapNode'", ")", ",", "}", ")", "context", "=", "{", "'CiscoISE.NodesData'", ":", "data", "}", "return_outputs", "(", "tableToMarkdown", "(", "'CiscoISE deployment nodes'", ",", "data", ",", "removeNull", "=", "True", ")", ",", "context", ")" ]
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/cisco-ise/Integrations/cisco-ise/cisco-ise.py#L769-L813
roclark/sportsipy
c19f545d3376d62ded6304b137dc69238ac620a9
sportsipy/nba/roster.py
python
Roster._pull_team_page
(self, url)
Download the team page. Download the requested team's season page and create a PyQuery object. Parameters ---------- url : string A string of the built URL for the requested team and season. Returns ------- PyQuery object Returns a PyQuery object of the team's HTML page.
Download the team page.
[ "Download", "the", "team", "page", "." ]
def _pull_team_page(self, url): """ Download the team page. Download the requested team's season page and create a PyQuery object. Parameters ---------- url : string A string of the built URL for the requested team and season. Returns ------- PyQuery object Returns a PyQuery object of the team's HTML page. """ try: return pq(url) except HTTPError: return None
[ "def", "_pull_team_page", "(", "self", ",", "url", ")", ":", "try", ":", "return", "pq", "(", "url", ")", "except", "HTTPError", ":", "return", "None" ]
https://github.com/roclark/sportsipy/blob/c19f545d3376d62ded6304b137dc69238ac620a9/sportsipy/nba/roster.py#L1408-L1427
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/datasets/lm.py
python
_expand_number_with_spacing
(m)
return " %s " % _expand_number(m)
:param typing.Match m: :rtype: str
:param typing.Match m: :rtype: str
[ ":", "param", "typing", ".", "Match", "m", ":", ":", "rtype", ":", "str" ]
def _expand_number_with_spacing(m): """ :param typing.Match m: :rtype: str """ return " %s " % _expand_number(m)
[ "def", "_expand_number_with_spacing", "(", "m", ")", ":", "return", "\" %s \"", "%", "_expand_number", "(", "m", ")" ]
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/datasets/lm.py#L1993-L1998
Ha0Tang/SelectionGAN
80aa7ad9f79f643c28633c40c621f208f3fb0121
semantic_synthesis/util/visualizer.py
python
Visualizer.save_images
(self, webpage, visuals, image_path)
[]
def save_images(self, webpage, visuals, image_path): visuals = self.convert_visuals_to_numpy(visuals) image_dir = webpage.get_image_dir() short_path = ntpath.basename(image_path[0]) name = os.path.splitext(short_path)[0] webpage.add_header(name) ims = [] txts = [] links = [] for label, image_numpy in visuals.items(): image_name = os.path.join(label, '%s.png' % (name)) save_path = os.path.join(image_dir, image_name) util.save_image(image_numpy, save_path, create_dir=True) ims.append(image_name) txts.append(label) links.append(image_name) webpage.add_images(ims, txts, links, width=self.win_size)
[ "def", "save_images", "(", "self", ",", "webpage", ",", "visuals", ",", "image_path", ")", ":", "visuals", "=", "self", ".", "convert_visuals_to_numpy", "(", "visuals", ")", "image_dir", "=", "webpage", ".", "get_image_dir", "(", ")", "short_path", "=", "ntpath", ".", "basename", "(", "image_path", "[", "0", "]", ")", "name", "=", "os", ".", "path", ".", "splitext", "(", "short_path", ")", "[", "0", "]", "webpage", ".", "add_header", "(", "name", ")", "ims", "=", "[", "]", "txts", "=", "[", "]", "links", "=", "[", "]", "for", "label", ",", "image_numpy", "in", "visuals", ".", "items", "(", ")", ":", "image_name", "=", "os", ".", "path", ".", "join", "(", "label", ",", "'%s.png'", "%", "(", "name", ")", ")", "save_path", "=", "os", ".", "path", ".", "join", "(", "image_dir", ",", "image_name", ")", "util", ".", "save_image", "(", "image_numpy", ",", "save_path", ",", "create_dir", "=", "True", ")", "ims", ".", "append", "(", "image_name", ")", "txts", ".", "append", "(", "label", ")", "links", ".", "append", "(", "image_name", ")", "webpage", ".", "add_images", "(", "ims", ",", "txts", ",", "links", ",", "width", "=", "self", ".", "win_size", ")" ]
https://github.com/Ha0Tang/SelectionGAN/blob/80aa7ad9f79f643c28633c40c621f208f3fb0121/semantic_synthesis/util/visualizer.py#L139-L159
openbmc/openbmc
5f4109adae05f4d6925bfe960007d52f98c61086
poky/scripts/lib/devtool/__init__.py
python
replace_from_file
(path, old, new)
Replace strings on a file
Replace strings on a file
[ "Replace", "strings", "on", "a", "file" ]
def replace_from_file(path, old, new): """Replace strings on a file""" def read_file(path): data = None with open(path) as f: data = f.read() return data def write_file(path, data): if data is None: return wdata = data.rstrip() + "\n" with open(path, "w") as f: f.write(wdata) # In case old is None, return immediately if old is None: return try: rdata = read_file(path) except IOError as e: # if file does not exit, just quit, otherwise raise an exception if e.errno == errno.ENOENT: return else: raise old_contents = rdata.splitlines() new_contents = [] for old_content in old_contents: try: new_contents.append(old_content.replace(old, new)) except ValueError: pass write_file(path, "\n".join(new_contents))
[ "def", "replace_from_file", "(", "path", ",", "old", ",", "new", ")", ":", "def", "read_file", "(", "path", ")", ":", "data", "=", "None", "with", "open", "(", "path", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "return", "data", "def", "write_file", "(", "path", ",", "data", ")", ":", "if", "data", "is", "None", ":", "return", "wdata", "=", "data", ".", "rstrip", "(", ")", "+", "\"\\n\"", "with", "open", "(", "path", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "wdata", ")", "# In case old is None, return immediately", "if", "old", "is", "None", ":", "return", "try", ":", "rdata", "=", "read_file", "(", "path", ")", "except", "IOError", "as", "e", ":", "# if file does not exit, just quit, otherwise raise an exception", "if", "e", ".", "errno", "==", "errno", ".", "ENOENT", ":", "return", "else", ":", "raise", "old_contents", "=", "rdata", ".", "splitlines", "(", ")", "new_contents", "=", "[", "]", "for", "old_content", "in", "old_contents", ":", "try", ":", "new_contents", ".", "append", "(", "old_content", ".", "replace", "(", "old", ",", "new", ")", ")", "except", "ValueError", ":", "pass", "write_file", "(", "path", ",", "\"\\n\"", ".", "join", "(", "new_contents", ")", ")" ]
https://github.com/openbmc/openbmc/blob/5f4109adae05f4d6925bfe960007d52f98c61086/poky/scripts/lib/devtool/__init__.py#L274-L309
dbt-labs/dbt-core
e943b9fc842535e958ef4fd0b8703adc91556bc6
core/dbt/contracts/graph/unparsed.py
python
Maturity.__ge__
(self, other)
return self == other or not (self < other)
[]
def __ge__(self, other): if not isinstance(other, Maturity): return NotImplemented return self == other or not (self < other)
[ "def", "__ge__", "(", "self", ",", "other", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Maturity", ")", ":", "return", "NotImplemented", "return", "self", "==", "other", "or", "not", "(", "self", "<", "other", ")" ]
https://github.com/dbt-labs/dbt-core/blob/e943b9fc842535e958ef4fd0b8703adc91556bc6/core/dbt/contracts/graph/unparsed.py#L407-L410
tracim/tracim
a0e9746fde5a4c45b4e0f0bfa2caf9522b8c4e21
backend/tracim_backend/lib/webdav/resources.py
python
ContentOnlyContainer.createCollection
(self, label: str)
return FolderResource( folder_path, self.environ, content=folder, tracim_context=self.tracim_context, workspace=self.workspace, )
Create a new folder for the current workspace/folder. As it's not possible for the user to choose which types of content are allowed in this folder, we allow allow all of them. This method return the DAVCollection created.
Create a new folder for the current workspace/folder. As it's not possible for the user to choose which types of content are allowed in this folder, we allow allow all of them.
[ "Create", "a", "new", "folder", "for", "the", "current", "workspace", "/", "folder", ".", "As", "it", "s", "not", "possible", "for", "the", "user", "to", "choose", "which", "types", "of", "content", "are", "allowed", "in", "this", "folder", "we", "allow", "allow", "all", "of", "them", "." ]
def createCollection(self, label: str) -> "FolderResource": """ Create a new folder for the current workspace/folder. As it's not possible for the user to choose which types of content are allowed in this folder, we allow allow all of them. This method return the DAVCollection created. """ folder_label = webdav_convert_file_name_to_bdd(label) try: folder = self.content_api.create( content_type_slug=content_type_list.Folder.slug, workspace=self.workspace, label=folder_label, parent=self.content, ) except TracimException as exc: raise DAVError(HTTP_FORBIDDEN, contextinfo=str(exc)) from exc self.content_api.save(folder) transaction.commit() # fixed_path folder_path = "%s/%s" % (self.path, webdav_convert_file_name_to_display(label)) # return item return FolderResource( folder_path, self.environ, content=folder, tracim_context=self.tracim_context, workspace=self.workspace, )
[ "def", "createCollection", "(", "self", ",", "label", ":", "str", ")", "->", "\"FolderResource\"", ":", "folder_label", "=", "webdav_convert_file_name_to_bdd", "(", "label", ")", "try", ":", "folder", "=", "self", ".", "content_api", ".", "create", "(", "content_type_slug", "=", "content_type_list", ".", "Folder", ".", "slug", ",", "workspace", "=", "self", ".", "workspace", ",", "label", "=", "folder_label", ",", "parent", "=", "self", ".", "content", ",", ")", "except", "TracimException", "as", "exc", ":", "raise", "DAVError", "(", "HTTP_FORBIDDEN", ",", "contextinfo", "=", "str", "(", "exc", ")", ")", "from", "exc", "self", ".", "content_api", ".", "save", "(", "folder", ")", "transaction", ".", "commit", "(", ")", "# fixed_path", "folder_path", "=", "\"%s/%s\"", "%", "(", "self", ".", "path", ",", "webdav_convert_file_name_to_display", "(", "label", ")", ")", "# return item", "return", "FolderResource", "(", "folder_path", ",", "self", ".", "environ", ",", "content", "=", "folder", ",", "tracim_context", "=", "self", ".", "tracim_context", ",", "workspace", "=", "self", ".", "workspace", ",", ")" ]
https://github.com/tracim/tracim/blob/a0e9746fde5a4c45b4e0f0bfa2caf9522b8c4e21/backend/tracim_backend/lib/webdav/resources.py#L377-L407
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/fimap/xgoogle/BeautifulSoup.py
python
SoupStrainer.__str__
(self)
[]
def __str__(self): if self.text: return self.text else: return "%s|%s" % (self.name, self.attrs)
[ "def", "__str__", "(", "self", ")", ":", "if", "self", ".", "text", ":", "return", "self", ".", "text", "else", ":", "return", "\"%s|%s\"", "%", "(", "self", ".", "name", ",", "self", ".", "attrs", ")" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/fimap/xgoogle/BeautifulSoup.py#L818-L822
Sekunde/3D-SIS
b90018a68df1fd14c4ad6f16702e9c74f309f11f
lib/utils/logger.py
python
Logger.__init__
(self, log_dir)
Create a summary writer logging to log_dir.
Create a summary writer logging to log_dir.
[ "Create", "a", "summary", "writer", "logging", "to", "log_dir", "." ]
def __init__(self, log_dir): """Create a summary writer logging to log_dir.""" self.writer = tf.summary.FileWriter(log_dir)
[ "def", "__init__", "(", "self", ",", "log_dir", ")", ":", "self", ".", "writer", "=", "tf", ".", "summary", ".", "FileWriter", "(", "log_dir", ")" ]
https://github.com/Sekunde/3D-SIS/blob/b90018a68df1fd14c4ad6f16702e9c74f309f11f/lib/utils/logger.py#L13-L15
roclark/sportsipy
c19f545d3376d62ded6304b137dc69238ac620a9
sportsipy/nhl/player.py
python
AbstractPlayer.corsi_for_percentage
(self)
return self._corsi_for_percentage
Returns a ``float`` of the 'Corsi For' percentage, equal to corsi_for / (corsi_for + corsi_against). Percentage ranges from 0-100.
Returns a ``float`` of the 'Corsi For' percentage, equal to corsi_for / (corsi_for + corsi_against). Percentage ranges from 0-100.
[ "Returns", "a", "float", "of", "the", "Corsi", "For", "percentage", "equal", "to", "corsi_for", "/", "(", "corsi_for", "+", "corsi_against", ")", ".", "Percentage", "ranges", "from", "0", "-", "100", "." ]
def corsi_for_percentage(self): """ Returns a ``float`` of the 'Corsi For' percentage, equal to corsi_for / (corsi_for + corsi_against). Percentage ranges from 0-100. """ return self._corsi_for_percentage
[ "def", "corsi_for_percentage", "(", "self", ")", ":", "return", "self", ".", "_corsi_for_percentage" ]
https://github.com/roclark/sportsipy/blob/c19f545d3376d62ded6304b137dc69238ac620a9/sportsipy/nhl/player.py#L306-L311
gcollazo/BrowserRefresh-Sublime
daee0eda6480c07f8636ed24e5c555d24e088886
win/pywinauto/controls/HwndWrapper.py
python
HwndWrapper.SendMessageTimeout
( self, message, wparam = 0 , lparam = 0, timeout = None, timeoutflags = win32defines.SMTO_NORMAL)
return result.value
Send a message to the control and wait for it to return or to timeout If no timeout is given then a default timeout of .4 of a second will be used.
Send a message to the control and wait for it to return or to timeout
[ "Send", "a", "message", "to", "the", "control", "and", "wait", "for", "it", "to", "return", "or", "to", "timeout" ]
def SendMessageTimeout( self, message, wparam = 0 , lparam = 0, timeout = None, timeoutflags = win32defines.SMTO_NORMAL): """Send a message to the control and wait for it to return or to timeout If no timeout is given then a default timeout of .4 of a second will be used. """ if timeout is None: timeout = Timings.sendmessagetimeout_timeout result = ctypes.c_long() win32functions.SendMessageTimeout(self, message, wparam, lparam, timeoutflags, int(timeout * 1000), ctypes.byref(result)) return result.value
[ "def", "SendMessageTimeout", "(", "self", ",", "message", ",", "wparam", "=", "0", ",", "lparam", "=", "0", ",", "timeout", "=", "None", ",", "timeoutflags", "=", "win32defines", ".", "SMTO_NORMAL", ")", ":", "if", "timeout", "is", "None", ":", "timeout", "=", "Timings", ".", "sendmessagetimeout_timeout", "result", "=", "ctypes", ".", "c_long", "(", ")", "win32functions", ".", "SendMessageTimeout", "(", "self", ",", "message", ",", "wparam", ",", "lparam", ",", "timeoutflags", ",", "int", "(", "timeout", "*", "1000", ")", ",", "ctypes", ".", "byref", "(", "result", ")", ")", "return", "result", ".", "value" ]
https://github.com/gcollazo/BrowserRefresh-Sublime/blob/daee0eda6480c07f8636ed24e5c555d24e088886/win/pywinauto/controls/HwndWrapper.py#L578-L600
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py
python
Node.is_derived
(self)
return self.has_builder() or self.side_effect
Returns true if this node is derived (i.e. built). This should return true only for nodes whose path should be in the variant directory when duplicate=0 and should contribute their build signatures when they are used as source files to other derived files. For example: source with source builders are not derived in this sense, and hence should not return true.
Returns true if this node is derived (i.e. built).
[ "Returns", "true", "if", "this", "node", "is", "derived", "(", "i", ".", "e", ".", "built", ")", "." ]
def is_derived(self): """ Returns true if this node is derived (i.e. built). This should return true only for nodes whose path should be in the variant directory when duplicate=0 and should contribute their build signatures when they are used as source files to other derived files. For example: source with source builders are not derived in this sense, and hence should not return true. """ return self.has_builder() or self.side_effect
[ "def", "is_derived", "(", "self", ")", ":", "return", "self", ".", "has_builder", "(", ")", "or", "self", ".", "side_effect" ]
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py#L539-L549
openstack/manila
142990edc027e14839d5deaf4954dd6fc88de15e
manila/share/drivers/netapp/dataontap/cluster_mode/lib_base.py
python
NetAppCmodeFileStorageLibrary._sort_export_locations_by_preferred_paths
(self, export_locations)
return sorted(export_locations, key=sort_key)
Sort the export locations to report preferred paths first.
Sort the export locations to report preferred paths first.
[ "Sort", "the", "export", "locations", "to", "report", "preferred", "paths", "first", "." ]
def _sort_export_locations_by_preferred_paths(self, export_locations): """Sort the export locations to report preferred paths first.""" sort_key = lambda location: location.get( # noqa: E731 'metadata', {}).get('preferred') is not True return sorted(export_locations, key=sort_key)
[ "def", "_sort_export_locations_by_preferred_paths", "(", "self", ",", "export_locations", ")", ":", "sort_key", "=", "lambda", "location", ":", "location", ".", "get", "(", "# noqa: E731", "'metadata'", ",", "{", "}", ")", ".", "get", "(", "'preferred'", ")", "is", "not", "True", "return", "sorted", "(", "export_locations", ",", "key", "=", "sort_key", ")" ]
https://github.com/openstack/manila/blob/142990edc027e14839d5deaf4954dd6fc88de15e/manila/share/drivers/netapp/dataontap/cluster_mode/lib_base.py#L1722-L1728
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/accounting/utils/__init__.py
python
months_from_date
(reference_date, months_from_date)
return datetime.date(year, month, 1)
[]
def months_from_date(reference_date, months_from_date): year, month = add_months(reference_date.year, reference_date.month, months_from_date) return datetime.date(year, month, 1)
[ "def", "months_from_date", "(", "reference_date", ",", "months_from_date", ")", ":", "year", ",", "month", "=", "add_months", "(", "reference_date", ".", "year", ",", "reference_date", ".", "month", ",", "months_from_date", ")", "return", "datetime", ".", "date", "(", "year", ",", "month", ",", "1", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/accounting/utils/__init__.py#L38-L40
ikalchev/HAP-python
6c2b95cc6457ea9c8dbee1759455a6954bb14092
pyhap/loader.py
python
Loader.__init__
(self, path_char=CHARACTERISTICS_FILE, path_service=SERVICES_FILE)
Initialize a new Loader instance.
Initialize a new Loader instance.
[ "Initialize", "a", "new", "Loader", "instance", "." ]
def __init__(self, path_char=CHARACTERISTICS_FILE, path_service=SERVICES_FILE): """Initialize a new Loader instance.""" self.char_types = self._read_file(path_char) self.serv_types = self._read_file(path_service)
[ "def", "__init__", "(", "self", ",", "path_char", "=", "CHARACTERISTICS_FILE", ",", "path_service", "=", "SERVICES_FILE", ")", ":", "self", ".", "char_types", "=", "self", ".", "_read_file", "(", "path_char", ")", "self", ".", "serv_types", "=", "self", ".", "_read_file", "(", "path_service", ")" ]
https://github.com/ikalchev/HAP-python/blob/6c2b95cc6457ea9c8dbee1759455a6954bb14092/pyhap/loader.py#L28-L31
carnal0wnage/weirdAAL
c14e36d7bb82447f38a43da203f4bc29429f4cf4
modules/aws/ec2.py
python
module_ec2_get_console_screenshot_all_region_list
(*text)
This function gets a screenshot for all EC2 instances in the specified list & region useful if for some reason one instance-id wont screenshot, pass it a list of instance-ids for a region -See module_ec2_write_instances_to_file to create the list python3 weirdAAL.py -m ec2_get_console_screenshot_all_region_list -a 'ASIAJEXAMPLEKEY-us-west-2.txt','us-west-2' -t yolo
This function gets a screenshot for all EC2 instances in the specified list & region useful if for some reason one instance-id wont screenshot, pass it a list of instance-ids for a region -See module_ec2_write_instances_to_file to create the list python3 weirdAAL.py -m ec2_get_console_screenshot_all_region_list -a 'ASIAJEXAMPLEKEY-us-west-2.txt','us-west-2' -t yolo
[ "This", "function", "gets", "a", "screenshot", "for", "all", "EC2", "instances", "in", "the", "specified", "list", "&", "region", "useful", "if", "for", "some", "reason", "one", "instance", "-", "id", "wont", "screenshot", "pass", "it", "a", "list", "of", "instance", "-", "ids", "for", "a", "region", "-", "See", "module_ec2_write_instances_to_file", "to", "create", "the", "list", "python3", "weirdAAL", ".", "py", "-", "m", "ec2_get_console_screenshot_all_region_list", "-", "a", "ASIAJEXAMPLEKEY", "-", "us", "-", "west", "-", "2", ".", "txt", "us", "-", "west", "-", "2", "-", "t", "yolo" ]
def module_ec2_get_console_screenshot_all_region_list(*text): ''' This function gets a screenshot for all EC2 instances in the specified list & region useful if for some reason one instance-id wont screenshot, pass it a list of instance-ids for a region -See module_ec2_write_instances_to_file to create the list python3 weirdAAL.py -m ec2_get_console_screenshot_all_region_list -a 'ASIAJEXAMPLEKEY-us-west-2.txt','us-west-2' -t yolo ''' get_console_screenshot_all_region_list(text[0][0], text[0][1])
[ "def", "module_ec2_get_console_screenshot_all_region_list", "(", "*", "text", ")", ":", "get_console_screenshot_all_region_list", "(", "text", "[", "0", "]", "[", "0", "]", ",", "text", "[", "0", "]", "[", "1", "]", ")" ]
https://github.com/carnal0wnage/weirdAAL/blob/c14e36d7bb82447f38a43da203f4bc29429f4cf4/modules/aws/ec2.py#L154-L161
bamtercelboo/pytorch_word2vec
6868ecac64c2801df520b7f9ed63ba79ed100c82
torch_CBOW.py
python
context_to_tensor
(context, idx_dict)
return Variable(torch.LongTensor(context_idx))
Converts context list to tensor.
Converts context list to tensor.
[ "Converts", "context", "list", "to", "tensor", "." ]
def context_to_tensor(context, idx_dict): """ Converts context list to tensor. """ context_idx = [idx_dict[word] for word in context] return Variable(torch.LongTensor(context_idx))
[ "def", "context_to_tensor", "(", "context", ",", "idx_dict", ")", ":", "context_idx", "=", "[", "idx_dict", "[", "word", "]", "for", "word", "in", "context", "]", "return", "Variable", "(", "torch", ".", "LongTensor", "(", "context_idx", ")", ")" ]
https://github.com/bamtercelboo/pytorch_word2vec/blob/6868ecac64c2801df520b7f9ed63ba79ed100c82/torch_CBOW.py#L49-L52
numba/numba
bf480b9e0da858a65508c2b17759a72ee6a44c51
numba/cuda/libdevice.py
python
rintf
(x)
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_rintf.html :param x: Argument. :type x: float32 :rtype: float32
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_rintf.html
[ "See", "https", ":", "//", "docs", ".", "nvidia", ".", "com", "/", "cuda", "/", "libdevice", "-", "users", "-", "guide", "/", "__nv_rintf", ".", "html" ]
def rintf(x): """ See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_rintf.html :param x: Argument. :type x: float32 :rtype: float32 """
[ "def", "rintf", "(", "x", ")", ":" ]
https://github.com/numba/numba/blob/bf480b9e0da858a65508c2b17759a72ee6a44c51/numba/cuda/libdevice.py#L2751-L2758
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Parser/asdl_c.py
python
ObjVisitor.visitSum
(self, sum, name)
[]
def visitSum(self, sum, name): if is_simple(sum): self.simpleSum(sum, name) return self.func_begin(name) self.emit("switch (o->kind) {", 1) for i in range(len(sum.types)): t = sum.types[i] self.visitConstructor(t, i + 1, name) self.emit("}", 1) for a in sum.attributes: self.emit("value = ast2obj_%s(o->%s);" % (a.type, a.name), 1) self.emit("if (!value) goto failed;", 1) self.emit('if (PyObject_SetAttrString(result, "%s", value) < 0)' % a.name, 1) self.emit('goto failed;', 2) self.emit('Py_DECREF(value);', 1) self.func_end()
[ "def", "visitSum", "(", "self", ",", "sum", ",", "name", ")", ":", "if", "is_simple", "(", "sum", ")", ":", "self", ".", "simpleSum", "(", "sum", ",", "name", ")", "return", "self", ".", "func_begin", "(", "name", ")", "self", ".", "emit", "(", "\"switch (o->kind) {\"", ",", "1", ")", "for", "i", "in", "range", "(", "len", "(", "sum", ".", "types", ")", ")", ":", "t", "=", "sum", ".", "types", "[", "i", "]", "self", ".", "visitConstructor", "(", "t", ",", "i", "+", "1", ",", "name", ")", "self", ".", "emit", "(", "\"}\"", ",", "1", ")", "for", "a", "in", "sum", ".", "attributes", ":", "self", ".", "emit", "(", "\"value = ast2obj_%s(o->%s);\"", "%", "(", "a", ".", "type", ",", "a", ".", "name", ")", ",", "1", ")", "self", ".", "emit", "(", "\"if (!value) goto failed;\"", ",", "1", ")", "self", ".", "emit", "(", "'if (PyObject_SetAttrString(result, \"%s\", value) < 0)'", "%", "a", ".", "name", ",", "1", ")", "self", ".", "emit", "(", "'goto failed;'", ",", "2", ")", "self", ".", "emit", "(", "'Py_DECREF(value);'", ",", "1", ")", "self", ".", "func_end", "(", ")" ]
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Parser/asdl_c.py#L1017-L1033
gmr/rabbitpy
d97fd2b1e983df0d95c2b0e2c6b29f61c79d82b9
rabbitpy/connection.py
python
Connection._qargs_ssl_validation
(self, values)
return SSL_CERT_MAP[validation]
Return the value mapped from the string value in the query string for the AMQP URL specifying which level of server certificate validation is required, if any. :param dict values: The dict of query values from the AMQP URI :rtype: int
Return the value mapped from the string value in the query string for the AMQP URL specifying which level of server certificate validation is required, if any.
[ "Return", "the", "value", "mapped", "from", "the", "string", "value", "in", "the", "query", "string", "for", "the", "AMQP", "URL", "specifying", "which", "level", "of", "server", "certificate", "validation", "is", "required", "if", "any", "." ]
def _qargs_ssl_validation(self, values): """Return the value mapped from the string value in the query string for the AMQP URL specifying which level of server certificate validation is required, if any. :param dict values: The dict of query values from the AMQP URI :rtype: int """ validation = self._qargs_mk_value(['verify', 'ssl_validation'], values) if not validation: return elif validation not in SSL_CERT_MAP: raise ValueError( 'Unsupported server cert validation option: %s', validation) return SSL_CERT_MAP[validation]
[ "def", "_qargs_ssl_validation", "(", "self", ",", "values", ")", ":", "validation", "=", "self", ".", "_qargs_mk_value", "(", "[", "'verify'", ",", "'ssl_validation'", "]", ",", "values", ")", "if", "not", "validation", ":", "return", "elif", "validation", "not", "in", "SSL_CERT_MAP", ":", "raise", "ValueError", "(", "'Unsupported server cert validation option: %s'", ",", "validation", ")", "return", "SSL_CERT_MAP", "[", "validation", "]" ]
https://github.com/gmr/rabbitpy/blob/d97fd2b1e983df0d95c2b0e2c6b29f61c79d82b9/rabbitpy/connection.py#L538-L554
ebroecker/canmatrix
219a19adf4639b0b4fd5328f039563c6d4060887
src/canmatrix/formats/sym.py
python
load
(f, **options)
return db
[]
def load(f, **options): # type: (typing.IO, **typing.Any) -> canmatrix.CanMatrix if 'symImportEncoding' in options: sym_import_encoding = options["symImportEncoding"] else: sym_import_encoding = 'iso-8859-1' calc_min_for_none = options.get('calc_min_for_none') calc_max_for_none = options.get('calc_max_for_none') float_factory = options.get('float_factory', default_float_factory) class Mode(object): glob, enums, send, sendReceive, receive = list(range(5)) mode = Mode.glob frame_name = "" frame = None db = canmatrix.CanMatrix() db.add_frame_defines("Receivable", 'BOOL False True') db.add_frame_defines("Sendable", 'BOOL False True') db.add_signal_defines("HexadecimalOutput", 'BOOL False True') db.add_signal_defines("DisplayDecimalPlaces", 'INT 0 65535') db.add_signal_defines("LongName", 'STR') for line_count, line in enumerate(f, 1): try: line = line.decode(sym_import_encoding).strip() # ignore empty line: if line.__len__() == 0: continue if line[0:6] == "Title=": title = line[6:].strip('"') db.add_global_defines("Title", "STRING") db.global_defines['Title'].set_default("canmatrix-Export") db.add_attribute("Title", title) # switch mode: if line[0:7] == "{ENUMS}": mode = Mode.enums continue if line[0:6] == "{SEND}": mode = Mode.send continue if line[0:13] == "{SENDRECEIVE}": mode = Mode.sendReceive continue if line[0:9] == "{RECEIVE}": mode = Mode.receive continue if mode == Mode.glob: # just ignore headers... continue elif mode == Mode.enums: line = line.strip() if line.startswith('enum'): while not line[5:].strip().endswith(')'): line = line.split('//')[0] if sys.version_info > (3, 0): # is there a clean way to to it? next_line = f.readline().decode(sym_import_encoding) else: next_line = next(f).decode(sym_import_encoding) if next_line == "": raise EOFError("Reached EOF before finding terminator for enum :\"{}\"".format(line)) line += next_line.strip() line = line.split('//')[0] temp_array = line[5:].strip().rstrip(')').split('(', 1) val_table_name = temp_array[0] split = canmatrix.utils.quote_aware_comma_split(temp_array[1]) temp_array = [s.rstrip(',') for s in split] temp_val_table = {} for entry in temp_array: temp_val_table[entry.split('=')[0].strip()] = entry.split('=')[ 1].replace('"', '').strip() db.add_value_table(val_table_name, temp_val_table) elif mode in {Mode.send, Mode.sendReceive, Mode.receive}: if line.startswith('['): multiplexor = None # found new frame: if frame_name != line.replace('[', '').replace(']', '').replace('"', '').strip(): frame_name = line.replace('[', '').replace(']', '').replace('"', '').strip() # TODO: CAMPid 939921818394902983238 if frame is not None: if len(frame.mux_names) > 0: frame.signal_by_name( frame.name + "_MUX").values = frame.mux_names db.add_frame(frame) frame = canmatrix.Frame(frame_name) frame.add_attribute( 'Receivable', mode in {Mode.receive, Mode.sendReceive} ) frame.add_attribute( 'Sendable', mode in {Mode.send, Mode.sendReceive} ) # key value: elif line.startswith('Var') or line.startswith('Mux'): tmp_mux = line[:3] line = line[4:] # comment = "" index_offset = 1 if tmp_mux == "Mux": index_offset = 0 comment = "" if '//' in line: split = line.split('//', 1) comment = split[1].strip() line = split[0].strip() line = line.replace(' ', ' "" ') temp_array = canmatrix.utils.quote_aware_space_split(line) sig_name = temp_array[0] is_float = False is_ascii = False enumeration = None if tmp_mux == "Mux": is_signed = False elif index_offset != 1 : is_signed = True else: is_signed = False type_label = temp_array[1] if type_label == 'unsigned': pass elif type_label == 'bit': pass elif type_label == 'raw': pass elif type_label == 'signed': is_signed = True elif type_label in ['float', 'double']: is_float = True elif type_label in ['char', 'string']: is_ascii = True elif type_label in db.value_tables.keys(): enumeration = type_label else: raise ValueError('Unknown type \'{}\' found'.format(type_label)) start_bit = int(temp_array[index_offset + 1].split(',')[0]) signal_length = int(temp_array[index_offset + 1].split(',')[1]) intel = True unit = "" factor = 1 max_value = None min_value = None long_name = None start_value = None offset = 0 value_table_name = None hexadecimal_output = False display_decimal_places = None if tmp_mux == "Mux": multiplexor = temp_array[2] if multiplexor[-1] == 'h': multiplexor = int(multiplexor[:-1], 16) else: multiplexor = int(multiplexor) if multiplexor in frame.mux_names: raise DuplicateMuxIdError( id=multiplexor, old=frame.mux_names[multiplexor], new=sig_name, line_number=line_count, line=line, ) frame.mux_names[multiplexor] = sig_name index_offset = 2 for switch in temp_array[index_offset + 2:]: if switch == "-m": intel = False elif switch == "-h": hexadecimal_output = True elif switch.startswith('/'): s = switch[1:].split(':', 1) if s[0] == 'u': unit = s[1] elif s[0] == 'f': factor = s[1] elif s[0] == 'd': start_value = s[1] elif s[0] == 'p': display_decimal_places = s[1] elif s[0] == 'o': offset = s[1] elif s[0] == 'e': value_table_name = s[1] elif s[0] == 'max': max_value = s[1] elif s[0] == 'min': min_value = s[1] elif s[0] == 'ln': long_name = s[1] # else: # print switch # else: # print switch if tmp_mux == "Mux": signal = frame.signal_by_name(frame_name + "_MUX") if signal is None: extras = {} if calc_min_for_none is not None: extras['calc_min_for_none'] = calc_min_for_none if calc_max_for_none is not None: extras['calc_max_for_none'] = calc_max_for_none # if float_factory is not None: # extras['float_factory'] = float_factory signal = canmatrix.Signal( frame_name + "_MUX", start_bit=int(start_bit), size=int(signal_length), is_little_endian=intel, is_signed=is_signed, is_float=is_float, is_ascii=is_ascii, factor=factor, offset=offset, unit=unit, multiplex='Multiplexor', comment=comment, **extras) if min_value is not None: signal.min = float_factory(min_value) if max_value is not None: signal.max = float_factory(max_value) # signal.add_comment(comment) if intel is False: # motorola set/convert start bit signal.set_startbit(start_bit) frame.add_signal(signal) signal.comments[multiplexor] = comment else: # signal = Signal(sigName, startBit, signalLength, intel, is_signed, factor, offset, min, max, unit, "", multiplexor) extras = {} if calc_min_for_none is not None: extras['calc_min_for_none'] = calc_min_for_none if calc_max_for_none is not None: extras['calc_max_for_none'] = calc_max_for_none # if float_factory is not None: # extras['float_factory'] = float_factory signal = canmatrix.Signal( sig_name, start_bit=int(start_bit), size=int(signal_length), is_little_endian=intel, is_signed=is_signed, is_float=is_float, factor=factor, offset=offset, unit=unit, multiplex=multiplexor, comment=comment, type_label=type_label, enumeration=enumeration, **extras) if min_value is not None: signal.min = float_factory(min_value) if max_value is not None: signal.max = float_factory(max_value) if intel is False: # motorola set/convert start bit signal.set_startbit(start_bit) if value_table_name is not None: signal.values = db.value_tables[value_table_name] signal.enumeration = value_table_name if enumeration is not None: signal.values = db.value_tables[enumeration] signal.enumeration = value_table_name # signal.add_comment(comment) # ... (1 / ...) because this somehow made 59.8/0.1 be 598.0 rather than 597.9999999999999 if start_value is not None: signal.initial_value = float_factory(start_value) frame.add_signal(signal) if long_name is not None: signal.add_attribute("LongName", long_name) if hexadecimal_output: signal.add_attribute("HexadecimalOutput", str(True)) if display_decimal_places is not None: signal.add_attribute("DisplayDecimalPlaces", display_decimal_places) # variable processing elif line.startswith('ID'): comment = "" if '//' in line: split = line.split('//', 1) comment = split[1].strip() line = split[0].strip() frame.arbitration_id.id = int(line.split('=')[1].strip()[:-1], 16) frame.add_comment(comment) elif line.startswith('Type'): if line.split('=')[1][:8] == "Extended": frame.arbitration_id.extended = 1 elif line.startswith('DLC'): frame.size = int(line.split('=')[1]) elif line.startswith('CycleTime'): frame.cycle_time = int(line.split('=')[1].strip()) # else: # print line # else: # print "Unrecognized line: " + l + " (%d) " % i except Exception as e: if not isinstance(e, ParsingError): ParsingError( message=str(e), line_number=line_count, line=line, original=e, ) db.load_errors.append(e) logger.error("Error decoding line %d" % line_count) logger.error(line) # TODO: CAMPid 939921818394902983238 if frame is not None: if len(frame.mux_names) > 0: frame.signal_by_name(frame.name + "_MUX").values = frame.mux_names db.add_frame(frame) return db
[ "def", "load", "(", "f", ",", "*", "*", "options", ")", ":", "# type: (typing.IO, **typing.Any) -> canmatrix.CanMatrix", "if", "'symImportEncoding'", "in", "options", ":", "sym_import_encoding", "=", "options", "[", "\"symImportEncoding\"", "]", "else", ":", "sym_import_encoding", "=", "'iso-8859-1'", "calc_min_for_none", "=", "options", ".", "get", "(", "'calc_min_for_none'", ")", "calc_max_for_none", "=", "options", ".", "get", "(", "'calc_max_for_none'", ")", "float_factory", "=", "options", ".", "get", "(", "'float_factory'", ",", "default_float_factory", ")", "class", "Mode", "(", "object", ")", ":", "glob", ",", "enums", ",", "send", ",", "sendReceive", ",", "receive", "=", "list", "(", "range", "(", "5", ")", ")", "mode", "=", "Mode", ".", "glob", "frame_name", "=", "\"\"", "frame", "=", "None", "db", "=", "canmatrix", ".", "CanMatrix", "(", ")", "db", ".", "add_frame_defines", "(", "\"Receivable\"", ",", "'BOOL False True'", ")", "db", ".", "add_frame_defines", "(", "\"Sendable\"", ",", "'BOOL False True'", ")", "db", ".", "add_signal_defines", "(", "\"HexadecimalOutput\"", ",", "'BOOL False True'", ")", "db", ".", "add_signal_defines", "(", "\"DisplayDecimalPlaces\"", ",", "'INT 0 65535'", ")", "db", ".", "add_signal_defines", "(", "\"LongName\"", ",", "'STR'", ")", "for", "line_count", ",", "line", "in", "enumerate", "(", "f", ",", "1", ")", ":", "try", ":", "line", "=", "line", ".", "decode", "(", "sym_import_encoding", ")", ".", "strip", "(", ")", "# ignore empty line:", "if", "line", ".", "__len__", "(", ")", "==", "0", ":", "continue", "if", "line", "[", "0", ":", "6", "]", "==", "\"Title=\"", ":", "title", "=", "line", "[", "6", ":", "]", ".", "strip", "(", "'\"'", ")", "db", ".", "add_global_defines", "(", "\"Title\"", ",", "\"STRING\"", ")", "db", ".", "global_defines", "[", "'Title'", "]", ".", "set_default", "(", "\"canmatrix-Export\"", ")", "db", ".", "add_attribute", "(", "\"Title\"", ",", "title", ")", "# switch mode:", "if", "line", "[", "0", ":", "7", "]", "==", "\"{ENUMS}\"", ":", "mode", "=", "Mode", ".", "enums", "continue", "if", "line", "[", "0", ":", "6", "]", "==", "\"{SEND}\"", ":", "mode", "=", "Mode", ".", "send", "continue", "if", "line", "[", "0", ":", "13", "]", "==", "\"{SENDRECEIVE}\"", ":", "mode", "=", "Mode", ".", "sendReceive", "continue", "if", "line", "[", "0", ":", "9", "]", "==", "\"{RECEIVE}\"", ":", "mode", "=", "Mode", ".", "receive", "continue", "if", "mode", "==", "Mode", ".", "glob", ":", "# just ignore headers...", "continue", "elif", "mode", "==", "Mode", ".", "enums", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ".", "startswith", "(", "'enum'", ")", ":", "while", "not", "line", "[", "5", ":", "]", ".", "strip", "(", ")", ".", "endswith", "(", "')'", ")", ":", "line", "=", "line", ".", "split", "(", "'//'", ")", "[", "0", "]", "if", "sys", ".", "version_info", ">", "(", "3", ",", "0", ")", ":", "# is there a clean way to to it?", "next_line", "=", "f", ".", "readline", "(", ")", ".", "decode", "(", "sym_import_encoding", ")", "else", ":", "next_line", "=", "next", "(", "f", ")", ".", "decode", "(", "sym_import_encoding", ")", "if", "next_line", "==", "\"\"", ":", "raise", "EOFError", "(", "\"Reached EOF before finding terminator for enum :\\\"{}\\\"\"", ".", "format", "(", "line", ")", ")", "line", "+=", "next_line", ".", "strip", "(", ")", "line", "=", "line", ".", "split", "(", "'//'", ")", "[", "0", "]", "temp_array", "=", "line", "[", "5", ":", "]", ".", "strip", "(", ")", ".", "rstrip", "(", "')'", ")", ".", "split", "(", "'('", ",", "1", ")", "val_table_name", "=", "temp_array", "[", "0", "]", "split", "=", "canmatrix", ".", "utils", ".", "quote_aware_comma_split", "(", "temp_array", "[", "1", "]", ")", "temp_array", "=", "[", "s", ".", "rstrip", "(", "','", ")", "for", "s", "in", "split", "]", "temp_val_table", "=", "{", "}", "for", "entry", "in", "temp_array", ":", "temp_val_table", "[", "entry", ".", "split", "(", "'='", ")", "[", "0", "]", ".", "strip", "(", ")", "]", "=", "entry", ".", "split", "(", "'='", ")", "[", "1", "]", ".", "replace", "(", "'\"'", ",", "''", ")", ".", "strip", "(", ")", "db", ".", "add_value_table", "(", "val_table_name", ",", "temp_val_table", ")", "elif", "mode", "in", "{", "Mode", ".", "send", ",", "Mode", ".", "sendReceive", ",", "Mode", ".", "receive", "}", ":", "if", "line", ".", "startswith", "(", "'['", ")", ":", "multiplexor", "=", "None", "# found new frame:", "if", "frame_name", "!=", "line", ".", "replace", "(", "'['", ",", "''", ")", ".", "replace", "(", "']'", ",", "''", ")", ".", "replace", "(", "'\"'", ",", "''", ")", ".", "strip", "(", ")", ":", "frame_name", "=", "line", ".", "replace", "(", "'['", ",", "''", ")", ".", "replace", "(", "']'", ",", "''", ")", ".", "replace", "(", "'\"'", ",", "''", ")", ".", "strip", "(", ")", "# TODO: CAMPid 939921818394902983238", "if", "frame", "is", "not", "None", ":", "if", "len", "(", "frame", ".", "mux_names", ")", ">", "0", ":", "frame", ".", "signal_by_name", "(", "frame", ".", "name", "+", "\"_MUX\"", ")", ".", "values", "=", "frame", ".", "mux_names", "db", ".", "add_frame", "(", "frame", ")", "frame", "=", "canmatrix", ".", "Frame", "(", "frame_name", ")", "frame", ".", "add_attribute", "(", "'Receivable'", ",", "mode", "in", "{", "Mode", ".", "receive", ",", "Mode", ".", "sendReceive", "}", ")", "frame", ".", "add_attribute", "(", "'Sendable'", ",", "mode", "in", "{", "Mode", ".", "send", ",", "Mode", ".", "sendReceive", "}", ")", "# key value:", "elif", "line", ".", "startswith", "(", "'Var'", ")", "or", "line", ".", "startswith", "(", "'Mux'", ")", ":", "tmp_mux", "=", "line", "[", ":", "3", "]", "line", "=", "line", "[", "4", ":", "]", "# comment = \"\"", "index_offset", "=", "1", "if", "tmp_mux", "==", "\"Mux\"", ":", "index_offset", "=", "0", "comment", "=", "\"\"", "if", "'//'", "in", "line", ":", "split", "=", "line", ".", "split", "(", "'//'", ",", "1", ")", "comment", "=", "split", "[", "1", "]", ".", "strip", "(", ")", "line", "=", "split", "[", "0", "]", ".", "strip", "(", ")", "line", "=", "line", ".", "replace", "(", "' '", ",", "' \"\" '", ")", "temp_array", "=", "canmatrix", ".", "utils", ".", "quote_aware_space_split", "(", "line", ")", "sig_name", "=", "temp_array", "[", "0", "]", "is_float", "=", "False", "is_ascii", "=", "False", "enumeration", "=", "None", "if", "tmp_mux", "==", "\"Mux\"", ":", "is_signed", "=", "False", "elif", "index_offset", "!=", "1", ":", "is_signed", "=", "True", "else", ":", "is_signed", "=", "False", "type_label", "=", "temp_array", "[", "1", "]", "if", "type_label", "==", "'unsigned'", ":", "pass", "elif", "type_label", "==", "'bit'", ":", "pass", "elif", "type_label", "==", "'raw'", ":", "pass", "elif", "type_label", "==", "'signed'", ":", "is_signed", "=", "True", "elif", "type_label", "in", "[", "'float'", ",", "'double'", "]", ":", "is_float", "=", "True", "elif", "type_label", "in", "[", "'char'", ",", "'string'", "]", ":", "is_ascii", "=", "True", "elif", "type_label", "in", "db", ".", "value_tables", ".", "keys", "(", ")", ":", "enumeration", "=", "type_label", "else", ":", "raise", "ValueError", "(", "'Unknown type \\'{}\\' found'", ".", "format", "(", "type_label", ")", ")", "start_bit", "=", "int", "(", "temp_array", "[", "index_offset", "+", "1", "]", ".", "split", "(", "','", ")", "[", "0", "]", ")", "signal_length", "=", "int", "(", "temp_array", "[", "index_offset", "+", "1", "]", ".", "split", "(", "','", ")", "[", "1", "]", ")", "intel", "=", "True", "unit", "=", "\"\"", "factor", "=", "1", "max_value", "=", "None", "min_value", "=", "None", "long_name", "=", "None", "start_value", "=", "None", "offset", "=", "0", "value_table_name", "=", "None", "hexadecimal_output", "=", "False", "display_decimal_places", "=", "None", "if", "tmp_mux", "==", "\"Mux\"", ":", "multiplexor", "=", "temp_array", "[", "2", "]", "if", "multiplexor", "[", "-", "1", "]", "==", "'h'", ":", "multiplexor", "=", "int", "(", "multiplexor", "[", ":", "-", "1", "]", ",", "16", ")", "else", ":", "multiplexor", "=", "int", "(", "multiplexor", ")", "if", "multiplexor", "in", "frame", ".", "mux_names", ":", "raise", "DuplicateMuxIdError", "(", "id", "=", "multiplexor", ",", "old", "=", "frame", ".", "mux_names", "[", "multiplexor", "]", ",", "new", "=", "sig_name", ",", "line_number", "=", "line_count", ",", "line", "=", "line", ",", ")", "frame", ".", "mux_names", "[", "multiplexor", "]", "=", "sig_name", "index_offset", "=", "2", "for", "switch", "in", "temp_array", "[", "index_offset", "+", "2", ":", "]", ":", "if", "switch", "==", "\"-m\"", ":", "intel", "=", "False", "elif", "switch", "==", "\"-h\"", ":", "hexadecimal_output", "=", "True", "elif", "switch", ".", "startswith", "(", "'/'", ")", ":", "s", "=", "switch", "[", "1", ":", "]", ".", "split", "(", "':'", ",", "1", ")", "if", "s", "[", "0", "]", "==", "'u'", ":", "unit", "=", "s", "[", "1", "]", "elif", "s", "[", "0", "]", "==", "'f'", ":", "factor", "=", "s", "[", "1", "]", "elif", "s", "[", "0", "]", "==", "'d'", ":", "start_value", "=", "s", "[", "1", "]", "elif", "s", "[", "0", "]", "==", "'p'", ":", "display_decimal_places", "=", "s", "[", "1", "]", "elif", "s", "[", "0", "]", "==", "'o'", ":", "offset", "=", "s", "[", "1", "]", "elif", "s", "[", "0", "]", "==", "'e'", ":", "value_table_name", "=", "s", "[", "1", "]", "elif", "s", "[", "0", "]", "==", "'max'", ":", "max_value", "=", "s", "[", "1", "]", "elif", "s", "[", "0", "]", "==", "'min'", ":", "min_value", "=", "s", "[", "1", "]", "elif", "s", "[", "0", "]", "==", "'ln'", ":", "long_name", "=", "s", "[", "1", "]", "# else:", "# print switch", "# else:", "# print switch", "if", "tmp_mux", "==", "\"Mux\"", ":", "signal", "=", "frame", ".", "signal_by_name", "(", "frame_name", "+", "\"_MUX\"", ")", "if", "signal", "is", "None", ":", "extras", "=", "{", "}", "if", "calc_min_for_none", "is", "not", "None", ":", "extras", "[", "'calc_min_for_none'", "]", "=", "calc_min_for_none", "if", "calc_max_for_none", "is", "not", "None", ":", "extras", "[", "'calc_max_for_none'", "]", "=", "calc_max_for_none", "# if float_factory is not None:", "# extras['float_factory'] = float_factory", "signal", "=", "canmatrix", ".", "Signal", "(", "frame_name", "+", "\"_MUX\"", ",", "start_bit", "=", "int", "(", "start_bit", ")", ",", "size", "=", "int", "(", "signal_length", ")", ",", "is_little_endian", "=", "intel", ",", "is_signed", "=", "is_signed", ",", "is_float", "=", "is_float", ",", "is_ascii", "=", "is_ascii", ",", "factor", "=", "factor", ",", "offset", "=", "offset", ",", "unit", "=", "unit", ",", "multiplex", "=", "'Multiplexor'", ",", "comment", "=", "comment", ",", "*", "*", "extras", ")", "if", "min_value", "is", "not", "None", ":", "signal", ".", "min", "=", "float_factory", "(", "min_value", ")", "if", "max_value", "is", "not", "None", ":", "signal", ".", "max", "=", "float_factory", "(", "max_value", ")", "# signal.add_comment(comment)", "if", "intel", "is", "False", ":", "# motorola set/convert start bit", "signal", ".", "set_startbit", "(", "start_bit", ")", "frame", ".", "add_signal", "(", "signal", ")", "signal", ".", "comments", "[", "multiplexor", "]", "=", "comment", "else", ":", "# signal = Signal(sigName, startBit, signalLength, intel, is_signed, factor, offset, min, max, unit, \"\", multiplexor)", "extras", "=", "{", "}", "if", "calc_min_for_none", "is", "not", "None", ":", "extras", "[", "'calc_min_for_none'", "]", "=", "calc_min_for_none", "if", "calc_max_for_none", "is", "not", "None", ":", "extras", "[", "'calc_max_for_none'", "]", "=", "calc_max_for_none", "# if float_factory is not None:", "# extras['float_factory'] = float_factory", "signal", "=", "canmatrix", ".", "Signal", "(", "sig_name", ",", "start_bit", "=", "int", "(", "start_bit", ")", ",", "size", "=", "int", "(", "signal_length", ")", ",", "is_little_endian", "=", "intel", ",", "is_signed", "=", "is_signed", ",", "is_float", "=", "is_float", ",", "factor", "=", "factor", ",", "offset", "=", "offset", ",", "unit", "=", "unit", ",", "multiplex", "=", "multiplexor", ",", "comment", "=", "comment", ",", "type_label", "=", "type_label", ",", "enumeration", "=", "enumeration", ",", "*", "*", "extras", ")", "if", "min_value", "is", "not", "None", ":", "signal", ".", "min", "=", "float_factory", "(", "min_value", ")", "if", "max_value", "is", "not", "None", ":", "signal", ".", "max", "=", "float_factory", "(", "max_value", ")", "if", "intel", "is", "False", ":", "# motorola set/convert start bit", "signal", ".", "set_startbit", "(", "start_bit", ")", "if", "value_table_name", "is", "not", "None", ":", "signal", ".", "values", "=", "db", ".", "value_tables", "[", "value_table_name", "]", "signal", ".", "enumeration", "=", "value_table_name", "if", "enumeration", "is", "not", "None", ":", "signal", ".", "values", "=", "db", ".", "value_tables", "[", "enumeration", "]", "signal", ".", "enumeration", "=", "value_table_name", "# signal.add_comment(comment)", "# ... (1 / ...) because this somehow made 59.8/0.1 be 598.0 rather than 597.9999999999999", "if", "start_value", "is", "not", "None", ":", "signal", ".", "initial_value", "=", "float_factory", "(", "start_value", ")", "frame", ".", "add_signal", "(", "signal", ")", "if", "long_name", "is", "not", "None", ":", "signal", ".", "add_attribute", "(", "\"LongName\"", ",", "long_name", ")", "if", "hexadecimal_output", ":", "signal", ".", "add_attribute", "(", "\"HexadecimalOutput\"", ",", "str", "(", "True", ")", ")", "if", "display_decimal_places", "is", "not", "None", ":", "signal", ".", "add_attribute", "(", "\"DisplayDecimalPlaces\"", ",", "display_decimal_places", ")", "# variable processing", "elif", "line", ".", "startswith", "(", "'ID'", ")", ":", "comment", "=", "\"\"", "if", "'//'", "in", "line", ":", "split", "=", "line", ".", "split", "(", "'//'", ",", "1", ")", "comment", "=", "split", "[", "1", "]", ".", "strip", "(", ")", "line", "=", "split", "[", "0", "]", ".", "strip", "(", ")", "frame", ".", "arbitration_id", ".", "id", "=", "int", "(", "line", ".", "split", "(", "'='", ")", "[", "1", "]", ".", "strip", "(", ")", "[", ":", "-", "1", "]", ",", "16", ")", "frame", ".", "add_comment", "(", "comment", ")", "elif", "line", ".", "startswith", "(", "'Type'", ")", ":", "if", "line", ".", "split", "(", "'='", ")", "[", "1", "]", "[", ":", "8", "]", "==", "\"Extended\"", ":", "frame", ".", "arbitration_id", ".", "extended", "=", "1", "elif", "line", ".", "startswith", "(", "'DLC'", ")", ":", "frame", ".", "size", "=", "int", "(", "line", ".", "split", "(", "'='", ")", "[", "1", "]", ")", "elif", "line", ".", "startswith", "(", "'CycleTime'", ")", ":", "frame", ".", "cycle_time", "=", "int", "(", "line", ".", "split", "(", "'='", ")", "[", "1", "]", ".", "strip", "(", ")", ")", "# else:", "# print line", "# else:", "# print \"Unrecognized line: \" + l + \" (%d) \" % i", "except", "Exception", "as", "e", ":", "if", "not", "isinstance", "(", "e", ",", "ParsingError", ")", ":", "ParsingError", "(", "message", "=", "str", "(", "e", ")", ",", "line_number", "=", "line_count", ",", "line", "=", "line", ",", "original", "=", "e", ",", ")", "db", ".", "load_errors", ".", "append", "(", "e", ")", "logger", ".", "error", "(", "\"Error decoding line %d\"", "%", "line_count", ")", "logger", ".", "error", "(", "line", ")", "# TODO: CAMPid 939921818394902983238", "if", "frame", "is", "not", "None", ":", "if", "len", "(", "frame", ".", "mux_names", ")", ">", "0", ":", "frame", ".", "signal_by_name", "(", "frame", ".", "name", "+", "\"_MUX\"", ")", ".", "values", "=", "frame", ".", "mux_names", "db", ".", "add_frame", "(", "frame", ")", "return", "db" ]
https://github.com/ebroecker/canmatrix/blob/219a19adf4639b0b4fd5328f039563c6d4060887/src/canmatrix/formats/sym.py#L329-L661
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/email/quoprimime.py
python
header_decode
(s)
return re.sub(r'=[a-fA-F0-9]{2}', _unquote_match, s, re.ASCII)
Decode a string encoded with RFC 2045 MIME header `Q' encoding. This function does not parse a full MIME header value encoded with quoted-printable (like =?iso-8895-1?q?Hello_World?=) -- please use the high level email.header class for that functionality.
Decode a string encoded with RFC 2045 MIME header `Q' encoding.
[ "Decode", "a", "string", "encoded", "with", "RFC", "2045", "MIME", "header", "Q", "encoding", "." ]
def header_decode(s): """Decode a string encoded with RFC 2045 MIME header `Q' encoding. This function does not parse a full MIME header value encoded with quoted-printable (like =?iso-8895-1?q?Hello_World?=) -- please use the high level email.header class for that functionality. """ s = s.replace('_', ' ') return re.sub(r'=[a-fA-F0-9]{2}', _unquote_match, s, re.ASCII)
[ "def", "header_decode", "(", "s", ")", ":", "s", "=", "s", ".", "replace", "(", "'_'", ",", "' '", ")", "return", "re", ".", "sub", "(", "r'=[a-fA-F0-9]{2}'", ",", "_unquote_match", ",", "s", ",", "re", ".", "ASCII", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/email/quoprimime.py#L314-L322
rsmusllp/termineter
9311d6d995a7bf0f80853a00a115a8fa16aa0727
lib/termineter/core.py
python
Framework.test_serial_connection
(self)
return True
Connect to the serial device and then verifies that the meter is responding. Once the serial device is open, this function attempts to retrieve the contents of table #0 (GEN_CONFIG_TBL) to configure the endianess it will use. Returns True on success.
Connect to the serial device and then verifies that the meter is responding. Once the serial device is open, this function attempts to retrieve the contents of table #0 (GEN_CONFIG_TBL) to configure the endianess it will use. Returns True on success.
[ "Connect", "to", "the", "serial", "device", "and", "then", "verifies", "that", "the", "meter", "is", "responding", ".", "Once", "the", "serial", "device", "is", "open", "this", "function", "attempts", "to", "retrieve", "the", "contents", "of", "table", "#0", "(", "GEN_CONFIG_TBL", ")", "to", "configure", "the", "endianess", "it", "will", "use", ".", "Returns", "True", "on", "success", "." ]
def test_serial_connection(self): """ Connect to the serial device and then verifies that the meter is responding. Once the serial device is open, this function attempts to retrieve the contents of table #0 (GEN_CONFIG_TBL) to configure the endianess it will use. Returns True on success. """ self.serial_connect() username = self.options['USERNAME'] user_id = self.options['USER_ID'] if len(username) > 10: self.logger.error('username cannot be longer than 10 characters') raise termineter.errors.FrameworkConfigurationError('username cannot be longer than 10 characters') if not (0 <= user_id <= 0xffff): self.logger.error('user id must be between 0 and 0xffff') raise termineter.errors.FrameworkConfigurationError('user id must be between 0 and 0xffff') try: if not self.serial_connection.login(username, user_id): self.logger.error('the meter has rejected the username and user id') raise termineter.errors.FrameworkConfigurationError('the meter has rejected the username and user id') except c1218.errors.C1218IOError as error: self.logger.error('serial connection has been opened but the meter is unresponsive') raise error try: general_config_table = self.serial_connection.get_table_data(0) except c1218.errors.C1218ReadTableError as error: self.logger.error('serial connection as been opened but the general configuration table (table #0) could not be read') raise error if general_config_table[0] & 1: self.logger.info('setting the connection to use big-endian for C12.19 data') self.serial_connection.c1219_endian = '>' else: self.logger.info('setting the connection to use little-endian for C12.19 data') self.serial_connection.c1219_endian = '<' try: self.serial_connection.stop() except c1218.errors.C1218IOError as error: self.logger.error('serial connection has been opened but the meter is unresponsive') raise error self.logger.warning('the serial interface has been connected') return True
[ "def", "test_serial_connection", "(", "self", ")", ":", "self", ".", "serial_connect", "(", ")", "username", "=", "self", ".", "options", "[", "'USERNAME'", "]", "user_id", "=", "self", ".", "options", "[", "'USER_ID'", "]", "if", "len", "(", "username", ")", ">", "10", ":", "self", ".", "logger", ".", "error", "(", "'username cannot be longer than 10 characters'", ")", "raise", "termineter", ".", "errors", ".", "FrameworkConfigurationError", "(", "'username cannot be longer than 10 characters'", ")", "if", "not", "(", "0", "<=", "user_id", "<=", "0xffff", ")", ":", "self", ".", "logger", ".", "error", "(", "'user id must be between 0 and 0xffff'", ")", "raise", "termineter", ".", "errors", ".", "FrameworkConfigurationError", "(", "'user id must be between 0 and 0xffff'", ")", "try", ":", "if", "not", "self", ".", "serial_connection", ".", "login", "(", "username", ",", "user_id", ")", ":", "self", ".", "logger", ".", "error", "(", "'the meter has rejected the username and user id'", ")", "raise", "termineter", ".", "errors", ".", "FrameworkConfigurationError", "(", "'the meter has rejected the username and user id'", ")", "except", "c1218", ".", "errors", ".", "C1218IOError", "as", "error", ":", "self", ".", "logger", ".", "error", "(", "'serial connection has been opened but the meter is unresponsive'", ")", "raise", "error", "try", ":", "general_config_table", "=", "self", ".", "serial_connection", ".", "get_table_data", "(", "0", ")", "except", "c1218", ".", "errors", ".", "C1218ReadTableError", "as", "error", ":", "self", ".", "logger", ".", "error", "(", "'serial connection as been opened but the general configuration table (table #0) could not be read'", ")", "raise", "error", "if", "general_config_table", "[", "0", "]", "&", "1", ":", "self", ".", "logger", ".", "info", "(", "'setting the connection to use big-endian for C12.19 data'", ")", "self", ".", "serial_connection", ".", "c1219_endian", "=", "'>'", "else", ":", "self", ".", "logger", ".", "info", "(", "'setting the connection to use little-endian for C12.19 data'", ")", "self", ".", "serial_connection", ".", "c1219_endian", "=", "'<'", "try", ":", "self", ".", "serial_connection", ".", "stop", "(", ")", "except", "c1218", ".", "errors", ".", "C1218IOError", "as", "error", ":", "self", ".", "logger", ".", "error", "(", "'serial connection has been opened but the meter is unresponsive'", ")", "raise", "error", "self", ".", "logger", ".", "warning", "(", "'the serial interface has been connected'", ")", "return", "True" ]
https://github.com/rsmusllp/termineter/blob/9311d6d995a7bf0f80853a00a115a8fa16aa0727/lib/termineter/core.py#L407-L453
cyverse/atmosphere
4a3e522f1f7b58abd9fa944c10b7455dc5cddac1
api/v1/views/machine.py
python
MachineLicense.get
(self, request, provider_uuid, identity_uuid, machine_id)
return Response(serialized_data, status=status.HTTP_200_OK)
Lookup the machine information (Lookup using the given provider/identity) Update on server (If applicable)
Lookup the machine information (Lookup using the given provider/identity) Update on server (If applicable)
[ "Lookup", "the", "machine", "information", "(", "Lookup", "using", "the", "given", "provider", "/", "identity", ")", "Update", "on", "server", "(", "If", "applicable", ")" ]
def get(self, request, provider_uuid, identity_uuid, machine_id): """ Lookup the machine information (Lookup using the given provider/identity) Update on server (If applicable) """ core_machine = ProviderMachine.objects.filter( provider__uuid=provider_uuid, identifier=machine_id ) if not core_machine: return failure_response( status.HTTP_400_BAD_REQUEST, "Machine id %s does not exist" % machine_id ) core_machine = core_machine.get() licenses = core_machine.licenses.all() serialized_data = LicenseSerializer(licenses, many=True).data return Response(serialized_data, status=status.HTTP_200_OK)
[ "def", "get", "(", "self", ",", "request", ",", "provider_uuid", ",", "identity_uuid", ",", "machine_id", ")", ":", "core_machine", "=", "ProviderMachine", ".", "objects", ".", "filter", "(", "provider__uuid", "=", "provider_uuid", ",", "identifier", "=", "machine_id", ")", "if", "not", "core_machine", ":", "return", "failure_response", "(", "status", ".", "HTTP_400_BAD_REQUEST", ",", "\"Machine id %s does not exist\"", "%", "machine_id", ")", "core_machine", "=", "core_machine", ".", "get", "(", ")", "licenses", "=", "core_machine", ".", "licenses", ".", "all", "(", ")", "serialized_data", "=", "LicenseSerializer", "(", "licenses", ",", "many", "=", "True", ")", ".", "data", "return", "Response", "(", "serialized_data", ",", "status", "=", "status", ".", "HTTP_200_OK", ")" ]
https://github.com/cyverse/atmosphere/blob/4a3e522f1f7b58abd9fa944c10b7455dc5cddac1/api/v1/views/machine.py#L311-L328
skylander86/lambda-text-extractor
6da52d077a2fc571e38bfe29c33ae68f6443cd5a
lib-linux_x64/docx/parts/styles.py
python
StylesPart._default_styles_xml
(cls)
return xml_bytes
Return a bytestream containing XML for a default styles part.
Return a bytestream containing XML for a default styles part.
[ "Return", "a", "bytestream", "containing", "XML", "for", "a", "default", "styles", "part", "." ]
def _default_styles_xml(cls): """ Return a bytestream containing XML for a default styles part. """ path = os.path.join( os.path.split(__file__)[0], '..', 'templates', 'default-styles.xml' ) with open(path, 'rb') as f: xml_bytes = f.read() return xml_bytes
[ "def", "_default_styles_xml", "(", "cls", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "split", "(", "__file__", ")", "[", "0", "]", ",", "'..'", ",", "'templates'", ",", "'default-styles.xml'", ")", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "xml_bytes", "=", "f", ".", "read", "(", ")", "return", "xml_bytes" ]
https://github.com/skylander86/lambda-text-extractor/blob/6da52d077a2fc571e38bfe29c33ae68f6443cd5a/lib-linux_x64/docx/parts/styles.py#L45-L55
keras-team/keras
5caa668b6a415675064a730f5eb46ecc08e40f65
keras/engine/keras_tensor.py
python
type_spec_with_shape
(spec, shape)
Returns a copy of TypeSpec `spec` with its shape set to `shape`.
Returns a copy of TypeSpec `spec` with its shape set to `shape`.
[ "Returns", "a", "copy", "of", "TypeSpec", "spec", "with", "its", "shape", "set", "to", "shape", "." ]
def type_spec_with_shape(spec, shape): """Returns a copy of TypeSpec `spec` with its shape set to `shape`.""" if isinstance(spec, tf.TensorSpec): # pylint: disable=protected-access # TODO(b/203201161) Figure out why mutation is needed here, and remove it. # (TensorSpec objects should be immutable; and we should not be modifying # private fields.) shape = tf.TensorShape(shape) spec._shape = shape if shape.rank is None: spec._shape_tuple = None else: spec._shape_tuple = tuple(shape.as_list()) return spec elif isinstance(spec, tf.RaggedTensorSpec): return tf.RaggedTensorSpec(shape, spec.dtype, spec.ragged_rank, spec.row_splits_dtype, spec.flat_values_spec) elif isinstance(spec, tf.SparseTensorSpec): return tf.SparseTensorSpec(shape, spec.dtype) elif hasattr(spec, 'with_shape'): # TODO(edloper): Consider adding .with_shape method to TensorSpec, # RaggedTensorSpec, and SparseTensorSpec. return spec.with_shape(shape) else: # TODO(edloper): Consider moving this check to the KerasTensor constructor. raise ValueError('Keras requires TypeSpec to have a `with_shape` method ' 'that returns a copy of `self` with an updated shape.')
[ "def", "type_spec_with_shape", "(", "spec", ",", "shape", ")", ":", "if", "isinstance", "(", "spec", ",", "tf", ".", "TensorSpec", ")", ":", "# pylint: disable=protected-access", "# TODO(b/203201161) Figure out why mutation is needed here, and remove it.", "# (TensorSpec objects should be immutable; and we should not be modifying", "# private fields.)", "shape", "=", "tf", ".", "TensorShape", "(", "shape", ")", "spec", ".", "_shape", "=", "shape", "if", "shape", ".", "rank", "is", "None", ":", "spec", ".", "_shape_tuple", "=", "None", "else", ":", "spec", ".", "_shape_tuple", "=", "tuple", "(", "shape", ".", "as_list", "(", ")", ")", "return", "spec", "elif", "isinstance", "(", "spec", ",", "tf", ".", "RaggedTensorSpec", ")", ":", "return", "tf", ".", "RaggedTensorSpec", "(", "shape", ",", "spec", ".", "dtype", ",", "spec", ".", "ragged_rank", ",", "spec", ".", "row_splits_dtype", ",", "spec", ".", "flat_values_spec", ")", "elif", "isinstance", "(", "spec", ",", "tf", ".", "SparseTensorSpec", ")", ":", "return", "tf", ".", "SparseTensorSpec", "(", "shape", ",", "spec", ".", "dtype", ")", "elif", "hasattr", "(", "spec", ",", "'with_shape'", ")", ":", "# TODO(edloper): Consider adding .with_shape method to TensorSpec,", "# RaggedTensorSpec, and SparseTensorSpec.", "return", "spec", ".", "with_shape", "(", "shape", ")", "else", ":", "# TODO(edloper): Consider moving this check to the KerasTensor constructor.", "raise", "ValueError", "(", "'Keras requires TypeSpec to have a `with_shape` method '", "'that returns a copy of `self` with an updated shape.'", ")" ]
https://github.com/keras-team/keras/blob/5caa668b6a415675064a730f5eb46ecc08e40f65/keras/engine/keras_tensor.py#L631-L658
sabri-zaki/EasY_HaCk
2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9
.modules/.sqlmap/thirdparty/clientform/clientform.py
python
urlencode
(query,doseq=False,)
return '&'.join(l)
Encode a sequence of two-element tuples or dictionary into a URL query \ string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input.
Encode a sequence of two-element tuples or dictionary into a URL query \ string.
[ "Encode", "a", "sequence", "of", "two", "-", "element", "tuples", "or", "dictionary", "into", "a", "URL", "query", "\\", "string", "." ]
def urlencode(query,doseq=False,): """Encode a sequence of two-element tuples or dictionary into a URL query \ string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of parameters in the input. """ if hasattr(query,"items"): # mapping objects query = query.items() else: # it's a bother at times that strings and string-like objects are # sequences... try: # non-sequence items should not work with len() x = len(query) # non-empty strings will fail this if len(query) and type(query[0]) != types.TupleType: raise TypeError() # zero-length sequences of all types will get here and succeed, # but that's a minor nit - since the original implementation # allowed empty dicts that type of behavior probably should be # preserved for consistency except TypeError: ty,va,tb = sys.exc_info() raise TypeError("not a valid non-string sequence or mapping " "object", tb) l = [] if not doseq: # preserve old behavior for k, v in query: k = urllib.quote_plus(str(k)) v = urllib.quote_plus(str(v)) l.append(k + '=' + v) else: for k, v in query: k = urllib.quote_plus(str(k)) if type(v) == types.StringType: v = urllib.quote_plus(v) l.append(k + '=' + v) elif type(v) == types.UnicodeType: # is there a reasonable way to convert to ASCII? # encode generates a string, but "replace" or "ignore" # lose information and "strict" can raise UnicodeError v = urllib.quote_plus(v.encode("ASCII","replace")) l.append(k + '=' + v) else: try: # is this a sufficient test for sequence-ness? x = len(v) except TypeError: # not a sequence v = urllib.quote_plus(str(v)) l.append(k + '=' + v) else: # loop over the sequence for elt in v: l.append(k + '=' + urllib.quote_plus(str(elt))) return '&'.join(l)
[ "def", "urlencode", "(", "query", ",", "doseq", "=", "False", ",", ")", ":", "if", "hasattr", "(", "query", ",", "\"items\"", ")", ":", "# mapping objects", "query", "=", "query", ".", "items", "(", ")", "else", ":", "# it's a bother at times that strings and string-like objects are", "# sequences...", "try", ":", "# non-sequence items should not work with len()", "x", "=", "len", "(", "query", ")", "# non-empty strings will fail this", "if", "len", "(", "query", ")", "and", "type", "(", "query", "[", "0", "]", ")", "!=", "types", ".", "TupleType", ":", "raise", "TypeError", "(", ")", "# zero-length sequences of all types will get here and succeed,", "# but that's a minor nit - since the original implementation", "# allowed empty dicts that type of behavior probably should be", "# preserved for consistency", "except", "TypeError", ":", "ty", ",", "va", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "raise", "TypeError", "(", "\"not a valid non-string sequence or mapping \"", "\"object\"", ",", "tb", ")", "l", "=", "[", "]", "if", "not", "doseq", ":", "# preserve old behavior", "for", "k", ",", "v", "in", "query", ":", "k", "=", "urllib", ".", "quote_plus", "(", "str", "(", "k", ")", ")", "v", "=", "urllib", ".", "quote_plus", "(", "str", "(", "v", ")", ")", "l", ".", "append", "(", "k", "+", "'='", "+", "v", ")", "else", ":", "for", "k", ",", "v", "in", "query", ":", "k", "=", "urllib", ".", "quote_plus", "(", "str", "(", "k", ")", ")", "if", "type", "(", "v", ")", "==", "types", ".", "StringType", ":", "v", "=", "urllib", ".", "quote_plus", "(", "v", ")", "l", ".", "append", "(", "k", "+", "'='", "+", "v", ")", "elif", "type", "(", "v", ")", "==", "types", ".", "UnicodeType", ":", "# is there a reasonable way to convert to ASCII?", "# encode generates a string, but \"replace\" or \"ignore\"", "# lose information and \"strict\" can raise UnicodeError", "v", "=", "urllib", ".", "quote_plus", "(", "v", ".", "encode", "(", "\"ASCII\"", ",", "\"replace\"", ")", ")", "l", ".", "append", "(", "k", "+", "'='", "+", "v", ")", "else", ":", "try", ":", "# is this a sufficient test for sequence-ness?", "x", "=", "len", "(", "v", ")", "except", "TypeError", ":", "# not a sequence", "v", "=", "urllib", ".", "quote_plus", "(", "str", "(", "v", ")", ")", "l", ".", "append", "(", "k", "+", "'='", "+", "v", ")", "else", ":", "# loop over the sequence", "for", "elt", "in", "v", ":", "l", ".", "append", "(", "k", "+", "'='", "+", "urllib", ".", "quote_plus", "(", "str", "(", "elt", ")", ")", ")", "return", "'&'", ".", "join", "(", "l", ")" ]
https://github.com/sabri-zaki/EasY_HaCk/blob/2a39ac384dd0d6fc51c0dd22e8d38cece683fdb9/.modules/.sqlmap/thirdparty/clientform/clientform.py#L151-L215
GoogleCloudPlatform/appengine-mapreduce
2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6
python/src/mapreduce/api/map_job/map_job_config.py
python
JobConfig._get_default_mr_params
(cls)
return mr_params
Gets default values for old API.
Gets default values for old API.
[ "Gets", "default", "values", "for", "old", "API", "." ]
def _get_default_mr_params(cls): """Gets default values for old API.""" cfg = cls(_lenient=True) mr_params = cfg._get_mr_params() mr_params["api_version"] = 0 return mr_params
[ "def", "_get_default_mr_params", "(", "cls", ")", ":", "cfg", "=", "cls", "(", "_lenient", "=", "True", ")", "mr_params", "=", "cfg", ".", "_get_mr_params", "(", ")", "mr_params", "[", "\"api_version\"", "]", "=", "0", "return", "mr_params" ]
https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/python/src/mapreduce/api/map_job/map_job_config.py#L154-L159
wwqgtxx/wwqLyParse
33136508e52821babd9294fdecffbdf02d73a6fc
wwqLyParse/lib/aiohttp_lib/attr/filters.py
python
_split_what
(what)
return ( frozenset(cls for cls in what if isclass(cls)), frozenset(cls for cls in what if isinstance(cls, Attribute)), )
Returns a tuple of `frozenset`s of classes and attributes.
Returns a tuple of `frozenset`s of classes and attributes.
[ "Returns", "a", "tuple", "of", "frozenset", "s", "of", "classes", "and", "attributes", "." ]
def _split_what(what): """ Returns a tuple of `frozenset`s of classes and attributes. """ return ( frozenset(cls for cls in what if isclass(cls)), frozenset(cls for cls in what if isinstance(cls, Attribute)), )
[ "def", "_split_what", "(", "what", ")", ":", "return", "(", "frozenset", "(", "cls", "for", "cls", "in", "what", "if", "isclass", "(", "cls", ")", ")", ",", "frozenset", "(", "cls", "for", "cls", "in", "what", "if", "isinstance", "(", "cls", ",", "Attribute", ")", ")", ",", ")" ]
https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/aiohttp_lib/attr/filters.py#L11-L18
antspy/quantized_distillation
bb500b7ae48a3f6751d6434126de9845b58d2d65
translation_models/help_fun.py
python
get_bleu_model
(model, dataset, options_model, options_translate=None, percentages_to_show=25, verbose=False)
return bleu
get bleu scores given a model and a dataset. it uses get_bleu_moses to compute the scores
get bleu scores given a model and a dataset. it uses get_bleu_moses to compute the scores
[ "get", "bleu", "scores", "given", "a", "model", "and", "a", "dataset", ".", "it", "uses", "get_bleu_moses", "to", "compute", "the", "scores" ]
def get_bleu_model(model, dataset, options_model, options_translate=None, percentages_to_show=25, verbose=False): 'get bleu scores given a model and a dataset. it uses get_bleu_moses to compute the scores' reference_file = dataset.testFilesPath[1] hypothesis_file = get_translation_file_model(model, dataset, options_model, options_translate=options_translate, percentages_to_show=percentages_to_show, verbose=verbose) bleu = get_bleu_moses(hypothesis_file, reference_file, file_input=True) os.remove(hypothesis_file) return bleu
[ "def", "get_bleu_model", "(", "model", ",", "dataset", ",", "options_model", ",", "options_translate", "=", "None", ",", "percentages_to_show", "=", "25", ",", "verbose", "=", "False", ")", ":", "reference_file", "=", "dataset", ".", "testFilesPath", "[", "1", "]", "hypothesis_file", "=", "get_translation_file_model", "(", "model", ",", "dataset", ",", "options_model", ",", "options_translate", "=", "options_translate", ",", "percentages_to_show", "=", "percentages_to_show", ",", "verbose", "=", "verbose", ")", "bleu", "=", "get_bleu_moses", "(", "hypothesis_file", ",", "reference_file", ",", "file_input", "=", "True", ")", "os", ".", "remove", "(", "hypothesis_file", ")", "return", "bleu" ]
https://github.com/antspy/quantized_distillation/blob/bb500b7ae48a3f6751d6434126de9845b58d2d65/translation_models/help_fun.py#L371-L381
AlexxIT/YandexStation
34c9fe2b29b856c8d92b186558480c868fe9ec1e
custom_components/yandex_station/core/yandex_session.py
python
YandexSession.get_qr
(self)
return "https://passport.yandex.ru/auth/magic/code/?track_id=" + \ resp["track_id"]
Get link to QR-code auth.
Get link to QR-code auth.
[ "Get", "link", "to", "QR", "-", "code", "auth", "." ]
async def get_qr(self) -> str: """Get link to QR-code auth.""" # step 1: csrf_token r = await self.session.get( "https://passport.yandex.ru/am?app_platform=android", proxy=self.proxy ) resp = await r.text() m = re.search(r'"csrf_token" value="([^"]+)"', resp) assert m, resp # step 2: track_id r = await self.session.post( "https://passport.yandex.ru/registration-validations/auth/password/submit", data={ "csrf_token": m[1], "retpath": "https://passport.yandex.ru/profile", "with_code": 1, }, proxy=self.proxy ) resp = await r.json() assert resp['status'] == 'ok', resp self.auth_payload = { "csrf_token": resp["csrf_token"], "track_id": resp["track_id"] } return "https://passport.yandex.ru/auth/magic/code/?track_id=" + \ resp["track_id"]
[ "async", "def", "get_qr", "(", "self", ")", "->", "str", ":", "# step 1: csrf_token", "r", "=", "await", "self", ".", "session", ".", "get", "(", "\"https://passport.yandex.ru/am?app_platform=android\"", ",", "proxy", "=", "self", ".", "proxy", ")", "resp", "=", "await", "r", ".", "text", "(", ")", "m", "=", "re", ".", "search", "(", "r'\"csrf_token\" value=\"([^\"]+)\"'", ",", "resp", ")", "assert", "m", ",", "resp", "# step 2: track_id", "r", "=", "await", "self", ".", "session", ".", "post", "(", "\"https://passport.yandex.ru/registration-validations/auth/password/submit\"", ",", "data", "=", "{", "\"csrf_token\"", ":", "m", "[", "1", "]", ",", "\"retpath\"", ":", "\"https://passport.yandex.ru/profile\"", ",", "\"with_code\"", ":", "1", ",", "}", ",", "proxy", "=", "self", ".", "proxy", ")", "resp", "=", "await", "r", ".", "json", "(", ")", "assert", "resp", "[", "'status'", "]", "==", "'ok'", ",", "resp", "self", ".", "auth_payload", "=", "{", "\"csrf_token\"", ":", "resp", "[", "\"csrf_token\"", "]", ",", "\"track_id\"", ":", "resp", "[", "\"track_id\"", "]", "}", "return", "\"https://passport.yandex.ru/auth/magic/code/?track_id=\"", "+", "resp", "[", "\"track_id\"", "]" ]
https://github.com/AlexxIT/YandexStation/blob/34c9fe2b29b856c8d92b186558480c868fe9ec1e/custom_components/yandex_station/core/yandex_session.py#L172-L202
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/konnected/binary_sensor.py
python
async_setup_entry
( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, )
Set up binary sensors attached to a Konnected device from a config entry.
Set up binary sensors attached to a Konnected device from a config entry.
[ "Set", "up", "binary", "sensors", "attached", "to", "a", "Konnected", "device", "from", "a", "config", "entry", "." ]
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up binary sensors attached to a Konnected device from a config entry.""" data = hass.data[KONNECTED_DOMAIN] device_id = config_entry.data["id"] sensors = [ KonnectedBinarySensor(device_id, pin_num, pin_data) for pin_num, pin_data in data[CONF_DEVICES][device_id][ CONF_BINARY_SENSORS ].items() ] async_add_entities(sensors)
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "config_entry", ":", "ConfigEntry", ",", "async_add_entities", ":", "AddEntitiesCallback", ",", ")", "->", "None", ":", "data", "=", "hass", ".", "data", "[", "KONNECTED_DOMAIN", "]", "device_id", "=", "config_entry", ".", "data", "[", "\"id\"", "]", "sensors", "=", "[", "KonnectedBinarySensor", "(", "device_id", ",", "pin_num", ",", "pin_data", ")", "for", "pin_num", ",", "pin_data", "in", "data", "[", "CONF_DEVICES", "]", "[", "device_id", "]", "[", "CONF_BINARY_SENSORS", "]", ".", "items", "(", ")", "]", "async_add_entities", "(", "sensors", ")" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/konnected/binary_sensor.py#L20-L34
fcurella/django-recommends
e69820f70c9f7935850c63e01b141ac06cf58e0d
recommends/providers/__init__.py
python
RecommendationProvider.get_rating_item
(self, rating)
Returns the rated object.
Returns the rated object.
[ "Returns", "the", "rated", "object", "." ]
def get_rating_item(self, rating): """Returns the rated object.""" raise NotImplementedError
[ "def", "get_rating_item", "(", "self", ",", "rating", ")", ":", "raise", "NotImplementedError" ]
https://github.com/fcurella/django-recommends/blob/e69820f70c9f7935850c63e01b141ac06cf58e0d/recommends/providers/__init__.py#L112-L114
celery/django-celery
c679b05b2abc174e6fa3231b120a07b49ec8f911
djcelery/schedulers.py
python
ModelEntry.__init__
(self, model)
[]
def __init__(self, model): self.app = current_app._get_current_object() self.name = model.name self.task = model.task try: self.schedule = model.schedule except model.DoesNotExist: logger.error('Schedule was removed from database') logger.warning('Disabling %s', self.name) self._disable(model) try: self.args = loads(model.args or '[]') self.kwargs = loads(model.kwargs or '{}') except ValueError: logging.error('Failed to serialize arguments for %s.', self.name, exc_info=1) logging.warning('Disabling %s', self.name) self._disable(model) self.options = {'queue': model.queue, 'exchange': model.exchange, 'routing_key': model.routing_key, 'expires': model.expires} self.total_run_count = model.total_run_count self.model = model if not model.last_run_at: model.last_run_at = self._default_now() orig = self.last_run_at = model.last_run_at if not is_naive(self.last_run_at): self.last_run_at = self.last_run_at.replace(tzinfo=None) assert orig.hour == self.last_run_at.hour
[ "def", "__init__", "(", "self", ",", "model", ")", ":", "self", ".", "app", "=", "current_app", ".", "_get_current_object", "(", ")", "self", ".", "name", "=", "model", ".", "name", "self", ".", "task", "=", "model", ".", "task", "try", ":", "self", ".", "schedule", "=", "model", ".", "schedule", "except", "model", ".", "DoesNotExist", ":", "logger", ".", "error", "(", "'Schedule was removed from database'", ")", "logger", ".", "warning", "(", "'Disabling %s'", ",", "self", ".", "name", ")", "self", ".", "_disable", "(", "model", ")", "try", ":", "self", ".", "args", "=", "loads", "(", "model", ".", "args", "or", "'[]'", ")", "self", ".", "kwargs", "=", "loads", "(", "model", ".", "kwargs", "or", "'{}'", ")", "except", "ValueError", ":", "logging", ".", "error", "(", "'Failed to serialize arguments for %s.'", ",", "self", ".", "name", ",", "exc_info", "=", "1", ")", "logging", ".", "warning", "(", "'Disabling %s'", ",", "self", ".", "name", ")", "self", ".", "_disable", "(", "model", ")", "self", ".", "options", "=", "{", "'queue'", ":", "model", ".", "queue", ",", "'exchange'", ":", "model", ".", "exchange", ",", "'routing_key'", ":", "model", ".", "routing_key", ",", "'expires'", ":", "model", ".", "expires", "}", "self", ".", "total_run_count", "=", "model", ".", "total_run_count", "self", ".", "model", "=", "model", "if", "not", "model", ".", "last_run_at", ":", "model", ".", "last_run_at", "=", "self", ".", "_default_now", "(", ")", "orig", "=", "self", ".", "last_run_at", "=", "model", ".", "last_run_at", "if", "not", "is_naive", "(", "self", ".", "last_run_at", ")", ":", "self", ".", "last_run_at", "=", "self", ".", "last_run_at", ".", "replace", "(", "tzinfo", "=", "None", ")", "assert", "orig", ".", "hour", "==", "self", ".", "last_run_at", ".", "hour" ]
https://github.com/celery/django-celery/blob/c679b05b2abc174e6fa3231b120a07b49ec8f911/djcelery/schedulers.py#L46-L77
cherrypy/cherrypy
a7983fe61f7237f2354915437b04295694100372
cherrypy/lib/sessions.py
python
init
(storage_type=None, path=None, path_header=None, name='session_id', timeout=60, domain=None, secure=False, clean_freq=5, persistent=True, httponly=False, debug=False, # Py27 compat # *, storage_class=RamSession, **kwargs)
Initialize session object (using cookies). storage_class The Session subclass to use. Defaults to RamSession. storage_type (deprecated) One of 'ram', 'file', memcached'. This will be used to look up the corresponding class in cherrypy.lib.sessions globals. For example, 'file' will use the FileSession class. path The 'path' value to stick in the response cookie metadata. path_header If 'path' is None (the default), then the response cookie 'path' will be pulled from request.headers[path_header]. name The name of the cookie. timeout The expiration timeout (in minutes) for the stored session data. If 'persistent' is True (the default), this is also the timeout for the cookie. domain The cookie domain. secure If False (the default) the cookie 'secure' value will not be set. If True, the cookie 'secure' value will be set (to 1). clean_freq (minutes) The poll rate for expired session cleanup. persistent If True (the default), the 'timeout' argument will be used to expire the cookie. If False, the cookie will not have an expiry, and the cookie will be a "session cookie" which expires when the browser is closed. httponly If False (the default) the cookie 'httponly' value will not be set. If True, the cookie 'httponly' value will be set (to 1). Any additional kwargs will be bound to the new Session instance, and may be specific to the storage type. See the subclass of Session you're using for more information.
Initialize session object (using cookies).
[ "Initialize", "session", "object", "(", "using", "cookies", ")", "." ]
def init(storage_type=None, path=None, path_header=None, name='session_id', timeout=60, domain=None, secure=False, clean_freq=5, persistent=True, httponly=False, debug=False, # Py27 compat # *, storage_class=RamSession, **kwargs): """Initialize session object (using cookies). storage_class The Session subclass to use. Defaults to RamSession. storage_type (deprecated) One of 'ram', 'file', memcached'. This will be used to look up the corresponding class in cherrypy.lib.sessions globals. For example, 'file' will use the FileSession class. path The 'path' value to stick in the response cookie metadata. path_header If 'path' is None (the default), then the response cookie 'path' will be pulled from request.headers[path_header]. name The name of the cookie. timeout The expiration timeout (in minutes) for the stored session data. If 'persistent' is True (the default), this is also the timeout for the cookie. domain The cookie domain. secure If False (the default) the cookie 'secure' value will not be set. If True, the cookie 'secure' value will be set (to 1). clean_freq (minutes) The poll rate for expired session cleanup. persistent If True (the default), the 'timeout' argument will be used to expire the cookie. If False, the cookie will not have an expiry, and the cookie will be a "session cookie" which expires when the browser is closed. httponly If False (the default) the cookie 'httponly' value will not be set. If True, the cookie 'httponly' value will be set (to 1). Any additional kwargs will be bound to the new Session instance, and may be specific to the storage type. See the subclass of Session you're using for more information. """ # Py27 compat storage_class = kwargs.pop('storage_class', RamSession) request = cherrypy.serving.request # Guard against running twice if hasattr(request, '_session_init_flag'): return request._session_init_flag = True # Check if request came with a session ID id = None if name in request.cookie: id = request.cookie[name].value if debug: cherrypy.log('ID obtained from request.cookie: %r' % id, 'TOOLS.SESSIONS') first_time = not hasattr(cherrypy, 'session') if storage_type: if first_time: msg = 'storage_type is deprecated. Supply storage_class instead' cherrypy.log(msg) storage_class = storage_type.title() + 'Session' storage_class = globals()[storage_class] # call setup first time only if first_time: if hasattr(storage_class, 'setup'): storage_class.setup(**kwargs) # Create and attach a new Session instance to cherrypy.serving. # It will possess a reference to (and lock, and lazily load) # the requested session data. kwargs['timeout'] = timeout kwargs['clean_freq'] = clean_freq cherrypy.serving.session = sess = storage_class(id, **kwargs) sess.debug = debug def update_cookie(id): """Update the cookie every time the session id changes.""" cherrypy.serving.response.cookie[name] = id sess.id_observers.append(update_cookie) # Create cherrypy.session which will proxy to cherrypy.serving.session if not hasattr(cherrypy, 'session'): cherrypy.session = cherrypy._ThreadLocalProxy('session') if persistent: cookie_timeout = timeout else: # See http://support.microsoft.com/kb/223799/EN-US/ # and http://support.mozilla.com/en-US/kb/Cookies cookie_timeout = None set_response_cookie(path=path, path_header=path_header, name=name, timeout=cookie_timeout, domain=domain, secure=secure, httponly=httponly)
[ "def", "init", "(", "storage_type", "=", "None", ",", "path", "=", "None", ",", "path_header", "=", "None", ",", "name", "=", "'session_id'", ",", "timeout", "=", "60", ",", "domain", "=", "None", ",", "secure", "=", "False", ",", "clean_freq", "=", "5", ",", "persistent", "=", "True", ",", "httponly", "=", "False", ",", "debug", "=", "False", ",", "# Py27 compat", "# *, storage_class=RamSession,", "*", "*", "kwargs", ")", ":", "# Py27 compat", "storage_class", "=", "kwargs", ".", "pop", "(", "'storage_class'", ",", "RamSession", ")", "request", "=", "cherrypy", ".", "serving", ".", "request", "# Guard against running twice", "if", "hasattr", "(", "request", ",", "'_session_init_flag'", ")", ":", "return", "request", ".", "_session_init_flag", "=", "True", "# Check if request came with a session ID", "id", "=", "None", "if", "name", "in", "request", ".", "cookie", ":", "id", "=", "request", ".", "cookie", "[", "name", "]", ".", "value", "if", "debug", ":", "cherrypy", ".", "log", "(", "'ID obtained from request.cookie: %r'", "%", "id", ",", "'TOOLS.SESSIONS'", ")", "first_time", "=", "not", "hasattr", "(", "cherrypy", ",", "'session'", ")", "if", "storage_type", ":", "if", "first_time", ":", "msg", "=", "'storage_type is deprecated. Supply storage_class instead'", "cherrypy", ".", "log", "(", "msg", ")", "storage_class", "=", "storage_type", ".", "title", "(", ")", "+", "'Session'", "storage_class", "=", "globals", "(", ")", "[", "storage_class", "]", "# call setup first time only", "if", "first_time", ":", "if", "hasattr", "(", "storage_class", ",", "'setup'", ")", ":", "storage_class", ".", "setup", "(", "*", "*", "kwargs", ")", "# Create and attach a new Session instance to cherrypy.serving.", "# It will possess a reference to (and lock, and lazily load)", "# the requested session data.", "kwargs", "[", "'timeout'", "]", "=", "timeout", "kwargs", "[", "'clean_freq'", "]", "=", "clean_freq", "cherrypy", ".", "serving", ".", "session", "=", "sess", "=", "storage_class", "(", "id", ",", "*", "*", "kwargs", ")", "sess", ".", "debug", "=", "debug", "def", "update_cookie", "(", "id", ")", ":", "\"\"\"Update the cookie every time the session id changes.\"\"\"", "cherrypy", ".", "serving", ".", "response", ".", "cookie", "[", "name", "]", "=", "id", "sess", ".", "id_observers", ".", "append", "(", "update_cookie", ")", "# Create cherrypy.session which will proxy to cherrypy.serving.session", "if", "not", "hasattr", "(", "cherrypy", ",", "'session'", ")", ":", "cherrypy", ".", "session", "=", "cherrypy", ".", "_ThreadLocalProxy", "(", "'session'", ")", "if", "persistent", ":", "cookie_timeout", "=", "timeout", "else", ":", "# See http://support.microsoft.com/kb/223799/EN-US/", "# and http://support.mozilla.com/en-US/kb/Cookies", "cookie_timeout", "=", "None", "set_response_cookie", "(", "path", "=", "path", ",", "path_header", "=", "path_header", ",", "name", "=", "name", ",", "timeout", "=", "cookie_timeout", ",", "domain", "=", "domain", ",", "secure", "=", "secure", ",", "httponly", "=", "httponly", ")" ]
https://github.com/cherrypy/cherrypy/blob/a7983fe61f7237f2354915437b04295694100372/cherrypy/lib/sessions.py#L722-L836
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/crypto/lwe.py
python
LWE._repr_
(self)
EXAMPLES:: sage: from sage.stats.distributions.discrete_gaussian_integer import DiscreteGaussianDistributionIntegerSampler sage: from sage.crypto.lwe import LWE sage: D = DiscreteGaussianDistributionIntegerSampler(3.0) sage: lwe = LWE(n=20, q=next_prime(400), D=D); lwe LWE(20, 401, Discrete Gaussian sampler over the Integers with sigma = 3.000000 and c = 0, 'uniform', None) sage: lwe = LWE(n=20, q=next_prime(400), D=D, secret_dist=(-3, 3)); lwe LWE(20, 401, Discrete Gaussian sampler over the Integers with sigma = 3.000000 and c = 0, (-3, 3), None)
EXAMPLES::
[ "EXAMPLES", "::" ]
def _repr_(self): """ EXAMPLES:: sage: from sage.stats.distributions.discrete_gaussian_integer import DiscreteGaussianDistributionIntegerSampler sage: from sage.crypto.lwe import LWE sage: D = DiscreteGaussianDistributionIntegerSampler(3.0) sage: lwe = LWE(n=20, q=next_prime(400), D=D); lwe LWE(20, 401, Discrete Gaussian sampler over the Integers with sigma = 3.000000 and c = 0, 'uniform', None) sage: lwe = LWE(n=20, q=next_prime(400), D=D, secret_dist=(-3, 3)); lwe LWE(20, 401, Discrete Gaussian sampler over the Integers with sigma = 3.000000 and c = 0, (-3, 3), None) """ if isinstance(self.secret_dist, str): return "LWE(%d, %d, %s, '%s', %s)"%(self.n,self.K.order(),self.D,self.secret_dist, self.m) else: return "LWE(%d, %d, %s, %s, %s)"%(self.n,self.K.order(),self.D,self.secret_dist, self.m)
[ "def", "_repr_", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "secret_dist", ",", "str", ")", ":", "return", "\"LWE(%d, %d, %s, '%s', %s)\"", "%", "(", "self", ".", "n", ",", "self", ".", "K", ".", "order", "(", ")", ",", "self", ".", "D", ",", "self", ".", "secret_dist", ",", "self", ".", "m", ")", "else", ":", "return", "\"LWE(%d, %d, %s, %s, %s)\"", "%", "(", "self", ".", "n", ",", "self", ".", "K", ".", "order", "(", ")", ",", "self", ".", "D", ",", "self", ".", "secret_dist", ",", "self", ".", "m", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/crypto/lwe.py#L330-L346