repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
ewiger/mlab
src/mlab/awmstools.py
romanNumeral
def romanNumeral(n): """ >>> romanNumeral(13) 'XIII' >>> romanNumeral(2944) 'MMCMXLIV' """ if 0 > n > 4000: raise ValueError('``n`` must lie between 1 and 3999: %d' % n) roman = 'I IV V IX X XL L XC C CD D CM M'.split() arabic = [1, 4, 5, 9, 10, 40, 50, 90, 10...
python
def romanNumeral(n): """ >>> romanNumeral(13) 'XIII' >>> romanNumeral(2944) 'MMCMXLIV' """ if 0 > n > 4000: raise ValueError('``n`` must lie between 1 and 3999: %d' % n) roman = 'I IV V IX X XL L XC C CD D CM M'.split() arabic = [1, 4, 5, 9, 10, 40, 50, 90, 10...
[ "def", "romanNumeral", "(", "n", ")", ":", "if", "0", ">", "n", ">", "4000", ":", "raise", "ValueError", "(", "'``n`` must lie between 1 and 3999: %d'", "%", "n", ")", "roman", "=", "'I IV V IX X XL L XC C CD D CM M'", ".", "split", "(", ")", ...
>>> romanNumeral(13) 'XIII' >>> romanNumeral(2944) 'MMCMXLIV'
[ ">>>", "romanNumeral", "(", "13", ")", "XIII", ">>>", "romanNumeral", "(", "2944", ")", "MMCMXLIV" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1987-L2002
ewiger/mlab
src/mlab/awmstools.py
first
def first(n, it, constructor=list): """ >>> first(3,iter([1,2,3,4])) [1, 2, 3] >>> first(3,iter([1,2,3,4]), iter) #doctest: +ELLIPSIS <itertools.islice object at ...> >>> first(3,iter([1,2,3,4]), tuple) (1, 2, 3) """ return constructor(itertools.islice(it,n))
python
def first(n, it, constructor=list): """ >>> first(3,iter([1,2,3,4])) [1, 2, 3] >>> first(3,iter([1,2,3,4]), iter) #doctest: +ELLIPSIS <itertools.islice object at ...> >>> first(3,iter([1,2,3,4]), tuple) (1, 2, 3) """ return constructor(itertools.islice(it,n))
[ "def", "first", "(", "n", ",", "it", ",", "constructor", "=", "list", ")", ":", "return", "constructor", "(", "itertools", ".", "islice", "(", "it", ",", "n", ")", ")" ]
>>> first(3,iter([1,2,3,4])) [1, 2, 3] >>> first(3,iter([1,2,3,4]), iter) #doctest: +ELLIPSIS <itertools.islice object at ...> >>> first(3,iter([1,2,3,4]), tuple) (1, 2, 3)
[ ">>>", "first", "(", "3", "iter", "(", "[", "1", "2", "3", "4", "]", "))", "[", "1", "2", "3", "]", ">>>", "first", "(", "3", "iter", "(", "[", "1", "2", "3", "4", "]", ")", "iter", ")", "#doctest", ":", "+", "ELLIPSIS", "<itertools", ".", ...
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L2011-L2020
ewiger/mlab
src/mlab/awmstools.py
drop
def drop(n, it, constructor=list): """ >>> first(10,drop(10,xrange(sys.maxint),iter)) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] """ return constructor(itertools.islice(it,n,None))
python
def drop(n, it, constructor=list): """ >>> first(10,drop(10,xrange(sys.maxint),iter)) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] """ return constructor(itertools.islice(it,n,None))
[ "def", "drop", "(", "n", ",", "it", ",", "constructor", "=", "list", ")", ":", "return", "constructor", "(", "itertools", ".", "islice", "(", "it", ",", "n", ",", "None", ")", ")" ]
>>> first(10,drop(10,xrange(sys.maxint),iter)) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[ ">>>", "first", "(", "10", "drop", "(", "10", "xrange", "(", "sys", ".", "maxint", ")", "iter", "))", "[", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "]" ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L2021-L2026
ewiger/mlab
src/mlab/awmstools.py
DryRun.run
def run(self, func, *args, **kwargs): """Same as ``self.dryRun`` if ``self.dry``, else same as ``self.wetRun``.""" if self.dry: return self.dryRun(func, *args, **kwargs) else: return self.wetRun(func, *args, **kwargs)
python
def run(self, func, *args, **kwargs): """Same as ``self.dryRun`` if ``self.dry``, else same as ``self.wetRun``.""" if self.dry: return self.dryRun(func, *args, **kwargs) else: return self.wetRun(func, *args, **kwargs)
[ "def", "run", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "dry", ":", "return", "self", ".", "dryRun", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "return", "...
Same as ``self.dryRun`` if ``self.dry``, else same as ``self.wetRun``.
[ "Same", "as", "self", ".", "dryRun", "if", "self", ".", "dry", "else", "same", "as", "self", ".", "wetRun", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1516-L1521
ewiger/mlab
src/mlab/awmstools.py
DryRun.dryRun
def dryRun(self, func, *args, **kwargs): """Instead of running function with `*args` and `**kwargs`, just print out the function call.""" print >> self.out, \ self.formatterDict.get(func, self.defaultFormatter)(func, *args, **kwargs)
python
def dryRun(self, func, *args, **kwargs): """Instead of running function with `*args` and `**kwargs`, just print out the function call.""" print >> self.out, \ self.formatterDict.get(func, self.defaultFormatter)(func, *args, **kwargs)
[ "def", "dryRun", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "print", ">>", "self", ".", "out", ",", "self", ".", "formatterDict", ".", "get", "(", "func", ",", "self", ".", "defaultFormatter", ")", "(", "func", ...
Instead of running function with `*args` and `**kwargs`, just print out the function call.
[ "Instead", "of", "running", "function", "with", "*", "args", "and", "**", "kwargs", "just", "print", "out", "the", "function", "call", "." ]
train
https://github.com/ewiger/mlab/blob/72a98adf6499f548848ad44c604f74d68f07fe4f/src/mlab/awmstools.py#L1528-L1533
rlisagor/pynetlinux
pynetlinux/brctl.py
iterbridges
def iterbridges(): ''' Iterate over all the bridges in the system. ''' net_files = os.listdir(SYSFS_NET_PATH) for d in net_files: path = os.path.join(SYSFS_NET_PATH, d) if not os.path.isdir(path): continue if os.path.exists(os.path.join(path, b"bridge")): yiel...
python
def iterbridges(): ''' Iterate over all the bridges in the system. ''' net_files = os.listdir(SYSFS_NET_PATH) for d in net_files: path = os.path.join(SYSFS_NET_PATH, d) if not os.path.isdir(path): continue if os.path.exists(os.path.join(path, b"bridge")): yiel...
[ "def", "iterbridges", "(", ")", ":", "net_files", "=", "os", ".", "listdir", "(", "SYSFS_NET_PATH", ")", "for", "d", "in", "net_files", ":", "path", "=", "os", ".", "path", ".", "join", "(", "SYSFS_NET_PATH", ",", "d", ")", "if", "not", "os", ".", ...
Iterate over all the bridges in the system.
[ "Iterate", "over", "all", "the", "bridges", "in", "the", "system", "." ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L97-L105
rlisagor/pynetlinux
pynetlinux/brctl.py
addbr
def addbr(name): ''' Create new bridge with the given name ''' fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name) return Bridge(name)
python
def addbr(name): ''' Create new bridge with the given name ''' fcntl.ioctl(ifconfig.sockfd, SIOCBRADDBR, name) return Bridge(name)
[ "def", "addbr", "(", "name", ")", ":", "fcntl", ".", "ioctl", "(", "ifconfig", ".", "sockfd", ",", "SIOCBRADDBR", ",", "name", ")", "return", "Bridge", "(", "name", ")" ]
Create new bridge with the given name
[ "Create", "new", "bridge", "with", "the", "given", "name" ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L113-L116
rlisagor/pynetlinux
pynetlinux/brctl.py
Bridge.iterifs
def iterifs(self): ''' Iterate over all the interfaces in this bridge. ''' if_path = os.path.join(SYSFS_NET_PATH, self.name, b"brif") net_files = os.listdir(if_path) for iface in net_files: yield iface
python
def iterifs(self): ''' Iterate over all the interfaces in this bridge. ''' if_path = os.path.join(SYSFS_NET_PATH, self.name, b"brif") net_files = os.listdir(if_path) for iface in net_files: yield iface
[ "def", "iterifs", "(", "self", ")", ":", "if_path", "=", "os", ".", "path", ".", "join", "(", "SYSFS_NET_PATH", ",", "self", ".", "name", ",", "b\"brif\"", ")", "net_files", "=", "os", ".", "listdir", "(", "if_path", ")", "for", "iface", "in", "net_f...
Iterate over all the interfaces in this bridge.
[ "Iterate", "over", "all", "the", "interfaces", "in", "this", "bridge", "." ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L32-L37
rlisagor/pynetlinux
pynetlinux/brctl.py
Bridge.addif
def addif(self, iface): ''' Add the interface with the given name to this bridge. Equivalent to brctl addif [bridge] [interface]. ''' if type(iface) == ifconfig.Interface: devindex = iface.index else: devindex = ifconfig.Interface(iface).index ifreq = ...
python
def addif(self, iface): ''' Add the interface with the given name to this bridge. Equivalent to brctl addif [bridge] [interface]. ''' if type(iface) == ifconfig.Interface: devindex = iface.index else: devindex = ifconfig.Interface(iface).index ifreq = ...
[ "def", "addif", "(", "self", ",", "iface", ")", ":", "if", "type", "(", "iface", ")", "==", "ifconfig", ".", "Interface", ":", "devindex", "=", "iface", ".", "index", "else", ":", "devindex", "=", "ifconfig", ".", "Interface", "(", "iface", ")", ".",...
Add the interface with the given name to this bridge. Equivalent to brctl addif [bridge] [interface].
[ "Add", "the", "interface", "with", "the", "given", "name", "to", "this", "bridge", ".", "Equivalent", "to", "brctl", "addif", "[", "bridge", "]", "[", "interface", "]", "." ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L45-L54
rlisagor/pynetlinux
pynetlinux/brctl.py
Bridge.delif
def delif(self, iface): ''' Remove the interface with the given name from this bridge. Equivalent to brctl delif [bridge] [interface]''' if type(iface) == ifconfig.Interface: devindex = iface.index else: devindex = ifconfig.Interface(iface).index ifreq...
python
def delif(self, iface): ''' Remove the interface with the given name from this bridge. Equivalent to brctl delif [bridge] [interface]''' if type(iface) == ifconfig.Interface: devindex = iface.index else: devindex = ifconfig.Interface(iface).index ifreq...
[ "def", "delif", "(", "self", ",", "iface", ")", ":", "if", "type", "(", "iface", ")", "==", "ifconfig", ".", "Interface", ":", "devindex", "=", "iface", ".", "index", "else", ":", "devindex", "=", "ifconfig", ".", "Interface", "(", "iface", ")", ".",...
Remove the interface with the given name from this bridge. Equivalent to brctl delif [bridge] [interface]
[ "Remove", "the", "interface", "with", "the", "given", "name", "from", "this", "bridge", ".", "Equivalent", "to", "brctl", "delif", "[", "bridge", "]", "[", "interface", "]" ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L57-L66
rlisagor/pynetlinux
pynetlinux/brctl.py
Bridge.delete
def delete(self): ''' Brings down the bridge interface, and removes it. Equivalent to ifconfig [bridge] down && brctl delbr [bridge]. ''' self.down() fcntl.ioctl(ifconfig.sockfd, SIOCBRDELBR, self.name) return self
python
def delete(self): ''' Brings down the bridge interface, and removes it. Equivalent to ifconfig [bridge] down && brctl delbr [bridge]. ''' self.down() fcntl.ioctl(ifconfig.sockfd, SIOCBRDELBR, self.name) return self
[ "def", "delete", "(", "self", ")", ":", "self", ".", "down", "(", ")", "fcntl", ".", "ioctl", "(", "ifconfig", ".", "sockfd", ",", "SIOCBRDELBR", ",", "self", ".", "name", ")", "return", "self" ]
Brings down the bridge interface, and removes it. Equivalent to ifconfig [bridge] down && brctl delbr [bridge].
[ "Brings", "down", "the", "bridge", "interface", "and", "removes", "it", ".", "Equivalent", "to", "ifconfig", "[", "bridge", "]", "down", "&&", "brctl", "delbr", "[", "bridge", "]", "." ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/brctl.py#L76-L81
jluttine/d3py
d3py/core.py
_get_random_id
def _get_random_id(): """ Get a random (i.e., unique) string identifier""" symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.choice(symbols) for _ in range(15))
python
def _get_random_id(): """ Get a random (i.e., unique) string identifier""" symbols = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.choice(symbols) for _ in range(15))
[ "def", "_get_random_id", "(", ")", ":", "symbols", "=", "string", ".", "ascii_uppercase", "+", "string", ".", "ascii_lowercase", "+", "string", ".", "digits", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "symbols", ")", "for", "_", "in...
Get a random (i.e., unique) string identifier
[ "Get", "a", "random", "(", "i", ".", "e", ".", "unique", ")", "string", "identifier" ]
train
https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L16-L19
jluttine/d3py
d3py/core.py
get_lib_filename
def get_lib_filename(category, name): """ Get a filename of a built-in library file. """ base_dir = os.path.dirname(os.path.abspath(__file__)) if category == 'js': filename = os.path.join('js', '{0}.js'.format(name)) elif category == 'css': filename = os.path.join('css', '{0}.css'.format...
python
def get_lib_filename(category, name): """ Get a filename of a built-in library file. """ base_dir = os.path.dirname(os.path.abspath(__file__)) if category == 'js': filename = os.path.join('js', '{0}.js'.format(name)) elif category == 'css': filename = os.path.join('css', '{0}.css'.format...
[ "def", "get_lib_filename", "(", "category", ",", "name", ")", ":", "base_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "if", "category", "==", "'js'", ":", "filename", "=", "os", ".",...
Get a filename of a built-in library file.
[ "Get", "a", "filename", "of", "a", "built", "-", "in", "library", "file", "." ]
train
https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L29-L40
jluttine/d3py
d3py/core.py
output_notebook
def output_notebook( d3js_url="//d3js.org/d3.v3.min", requirejs_url="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js", html_template=None ): """ Import required Javascript libraries to Jupyter Notebook. """ if html_template is None: html_template = read_lib('ht...
python
def output_notebook( d3js_url="//d3js.org/d3.v3.min", requirejs_url="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js", html_template=None ): """ Import required Javascript libraries to Jupyter Notebook. """ if html_template is None: html_template = read_lib('ht...
[ "def", "output_notebook", "(", "d3js_url", "=", "\"//d3js.org/d3.v3.min\"", ",", "requirejs_url", "=", "\"//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.min.js\"", ",", "html_template", "=", "None", ")", ":", "if", "html_template", "is", "None", ":", "html_templ...
Import required Javascript libraries to Jupyter Notebook.
[ "Import", "required", "Javascript", "libraries", "to", "Jupyter", "Notebook", "." ]
train
https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L59-L76
jluttine/d3py
d3py/core.py
create_graph_html
def create_graph_html(js_template, css_template, html_template=None): """ Create HTML code block given the graph Javascript and CSS. """ if html_template is None: html_template = read_lib('html', 'graph') # Create div ID for the graph and give it to the JS and CSS templates so # they can refere...
python
def create_graph_html(js_template, css_template, html_template=None): """ Create HTML code block given the graph Javascript and CSS. """ if html_template is None: html_template = read_lib('html', 'graph') # Create div ID for the graph and give it to the JS and CSS templates so # they can refere...
[ "def", "create_graph_html", "(", "js_template", ",", "css_template", ",", "html_template", "=", "None", ")", ":", "if", "html_template", "is", "None", ":", "html_template", "=", "read_lib", "(", "'html'", ",", "'graph'", ")", "# Create div ID for the graph and give ...
Create HTML code block given the graph Javascript and CSS.
[ "Create", "HTML", "code", "block", "given", "the", "graph", "Javascript", "and", "CSS", "." ]
train
https://github.com/jluttine/d3py/blob/2856eb3aa23c4ae17897fcd6a25b68203eb1e9e0/d3py/core.py#L79-L95
viraja1/grammar-check
download_lt.py
get_newest_possible_languagetool_version
def get_newest_possible_languagetool_version(): """Return newest compatible version. >>> version = get_newest_possible_languagetool_version() >>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION] True """ java_path = find_executable('java') if not java_path: # Just ignore this...
python
def get_newest_possible_languagetool_version(): """Return newest compatible version. >>> version = get_newest_possible_languagetool_version() >>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION] True """ java_path = find_executable('java') if not java_path: # Just ignore this...
[ "def", "get_newest_possible_languagetool_version", "(", ")", ":", "java_path", "=", "find_executable", "(", "'java'", ")", "if", "not", "java_path", ":", "# Just ignore this and assume an old version of Java. It might not be", "# found because of a PATHEXT-related issue", "# (https...
Return newest compatible version. >>> version = get_newest_possible_languagetool_version() >>> version in [JAVA_6_COMPATIBLE_VERSION, LATEST_VERSION] True
[ "Return", "newest", "compatible", "version", "." ]
train
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/download_lt.py#L33-L69
rlisagor/pynetlinux
pynetlinux/ifconfig.py
iterifs
def iterifs(physical=True): ''' Iterate over all the interfaces in the system. If physical is true, then return only real physical interfaces (not 'lo', etc).''' net_files = os.listdir(SYSFS_NET_PATH) interfaces = set() virtual = set() for d in net_files: path = os.path.join(SYSFS_NE...
python
def iterifs(physical=True): ''' Iterate over all the interfaces in the system. If physical is true, then return only real physical interfaces (not 'lo', etc).''' net_files = os.listdir(SYSFS_NET_PATH) interfaces = set() virtual = set() for d in net_files: path = os.path.join(SYSFS_NE...
[ "def", "iterifs", "(", "physical", "=", "True", ")", ":", "net_files", "=", "os", ".", "listdir", "(", "SYSFS_NET_PATH", ")", "interfaces", "=", "set", "(", ")", "virtual", "=", "set", "(", ")", "for", "d", "in", "net_files", ":", "path", "=", "os", ...
Iterate over all the interfaces in the system. If physical is true, then return only real physical interfaces (not 'lo', etc).
[ "Iterate", "over", "all", "the", "interfaces", "in", "the", "system", ".", "If", "physical", "is", "true", "then", "return", "only", "real", "physical", "interfaces", "(", "not", "lo", "etc", ")", "." ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L353-L388
rlisagor/pynetlinux
pynetlinux/ifconfig.py
init
def init(): ''' Initialize the library ''' globals()["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM) globals()["sockfd"] = globals()["sock"].fileno()
python
def init(): ''' Initialize the library ''' globals()["sock"] = socket.socket(socket.AF_INET, socket.SOCK_STREAM) globals()["sockfd"] = globals()["sock"].fileno()
[ "def", "init", "(", ")", ":", "globals", "(", ")", "[", "\"sock\"", "]", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "globals", "(", ")", "[", "\"sockfd\"", "]", "=", "globals", "(", ")", "["...
Initialize the library
[ "Initialize", "the", "library" ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L403-L406
rlisagor/pynetlinux
pynetlinux/ifconfig.py
Interface.up
def up(self): ''' Bring up the bridge interface. Equivalent to ifconfig [iface] up. ''' # Get existing device flags ifreq = struct.pack('16sh', self.name, 0) flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1] # Set new flags flags = flags | IFF_U...
python
def up(self): ''' Bring up the bridge interface. Equivalent to ifconfig [iface] up. ''' # Get existing device flags ifreq = struct.pack('16sh', self.name, 0) flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1] # Set new flags flags = flags | IFF_U...
[ "def", "up", "(", "self", ")", ":", "# Get existing device flags", "ifreq", "=", "struct", ".", "pack", "(", "'16sh'", ",", "self", ".", "name", ",", "0", ")", "flags", "=", "struct", ".", "unpack", "(", "'16sh'", ",", "fcntl", ".", "ioctl", "(", "so...
Bring up the bridge interface. Equivalent to ifconfig [iface] up.
[ "Bring", "up", "the", "bridge", "interface", ".", "Equivalent", "to", "ifconfig", "[", "iface", "]", "up", "." ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L142-L152
rlisagor/pynetlinux
pynetlinux/ifconfig.py
Interface.is_up
def is_up(self): ''' Return True if the interface is up, False otherwise. ''' # Get existing device flags ifreq = struct.pack('16sh', self.name, 0) flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1] # Set new flags if flags & IFF_UP: ...
python
def is_up(self): ''' Return True if the interface is up, False otherwise. ''' # Get existing device flags ifreq = struct.pack('16sh', self.name, 0) flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1] # Set new flags if flags & IFF_UP: ...
[ "def", "is_up", "(", "self", ")", ":", "# Get existing device flags", "ifreq", "=", "struct", ".", "pack", "(", "'16sh'", ",", "self", ".", "name", ",", "0", ")", "flags", "=", "struct", ".", "unpack", "(", "'16sh'", ",", "fcntl", ".", "ioctl", "(", ...
Return True if the interface is up, False otherwise.
[ "Return", "True", "if", "the", "interface", "is", "up", "False", "otherwise", "." ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L166-L177
rlisagor/pynetlinux
pynetlinux/ifconfig.py
Interface.get_mac
def get_mac(self): ''' Obtain the device's mac address. ''' ifreq = struct.pack('16sH14s', self.name, AF_UNIX, b'\x00'*14) res = fcntl.ioctl(sockfd, SIOCGIFHWADDR, ifreq) address = struct.unpack('16sH14s', res)[2] mac = struct.unpack('6B8x', address) return ":".join(['%0...
python
def get_mac(self): ''' Obtain the device's mac address. ''' ifreq = struct.pack('16sH14s', self.name, AF_UNIX, b'\x00'*14) res = fcntl.ioctl(sockfd, SIOCGIFHWADDR, ifreq) address = struct.unpack('16sH14s', res)[2] mac = struct.unpack('6B8x', address) return ":".join(['%0...
[ "def", "get_mac", "(", "self", ")", ":", "ifreq", "=", "struct", ".", "pack", "(", "'16sH14s'", ",", "self", ".", "name", ",", "AF_UNIX", ",", "b'\\x00'", "*", "14", ")", "res", "=", "fcntl", ".", "ioctl", "(", "sockfd", ",", "SIOCGIFHWADDR", ",", ...
Obtain the device's mac address.
[ "Obtain", "the", "device", "s", "mac", "address", "." ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L179-L186
rlisagor/pynetlinux
pynetlinux/ifconfig.py
Interface.set_mac
def set_mac(self, newmac): ''' Set the device's mac address. Device must be down for this to succeed. ''' macbytes = [int(i, 16) for i in newmac.split(':')] ifreq = struct.pack('16sH6B8x', self.name, AF_UNIX, *macbytes) fcntl.ioctl(sockfd, SIOCSIFHWADDR, ifreq)
python
def set_mac(self, newmac): ''' Set the device's mac address. Device must be down for this to succeed. ''' macbytes = [int(i, 16) for i in newmac.split(':')] ifreq = struct.pack('16sH6B8x', self.name, AF_UNIX, *macbytes) fcntl.ioctl(sockfd, SIOCSIFHWADDR, ifreq)
[ "def", "set_mac", "(", "self", ",", "newmac", ")", ":", "macbytes", "=", "[", "int", "(", "i", ",", "16", ")", "for", "i", "in", "newmac", ".", "split", "(", "':'", ")", "]", "ifreq", "=", "struct", ".", "pack", "(", "'16sH6B8x'", ",", "self", ...
Set the device's mac address. Device must be down for this to succeed.
[ "Set", "the", "device", "s", "mac", "address", ".", "Device", "must", "be", "down", "for", "this", "to", "succeed", "." ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L189-L194
rlisagor/pynetlinux
pynetlinux/ifconfig.py
Interface.get_index
def get_index(self): ''' Convert an interface name to an index value. ''' ifreq = struct.pack('16si', self.name, 0) res = fcntl.ioctl(sockfd, SIOCGIFINDEX, ifreq) return struct.unpack("16si", res)[1]
python
def get_index(self): ''' Convert an interface name to an index value. ''' ifreq = struct.pack('16si', self.name, 0) res = fcntl.ioctl(sockfd, SIOCGIFINDEX, ifreq) return struct.unpack("16si", res)[1]
[ "def", "get_index", "(", "self", ")", ":", "ifreq", "=", "struct", ".", "pack", "(", "'16si'", ",", "self", ".", "name", ",", "0", ")", "res", "=", "fcntl", ".", "ioctl", "(", "sockfd", ",", "SIOCGIFINDEX", ",", "ifreq", ")", "return", "struct", "....
Convert an interface name to an index value.
[ "Convert", "an", "interface", "name", "to", "an", "index", "value", "." ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L233-L237
rlisagor/pynetlinux
pynetlinux/ifconfig.py
Interface.set_pause_param
def set_pause_param(self, autoneg, rx_pause, tx_pause): """ Ethernet has flow control! The inter-frame pause can be adjusted, by auto-negotiation through an ethernet frame type with a simple two-field payload, and by setting it explicitly. http://en.wikipedia.org/wiki/Ethernet_f...
python
def set_pause_param(self, autoneg, rx_pause, tx_pause): """ Ethernet has flow control! The inter-frame pause can be adjusted, by auto-negotiation through an ethernet frame type with a simple two-field payload, and by setting it explicitly. http://en.wikipedia.org/wiki/Ethernet_f...
[ "def", "set_pause_param", "(", "self", ",", "autoneg", ",", "rx_pause", ",", "tx_pause", ")", ":", "# create a struct ethtool_pauseparm", "# create a struct ifreq with its .ifr_data pointing at the above", "ecmd", "=", "array", ".", "array", "(", "'B'", ",", "struct", "...
Ethernet has flow control! The inter-frame pause can be adjusted, by auto-negotiation through an ethernet frame type with a simple two-field payload, and by setting it explicitly. http://en.wikipedia.org/wiki/Ethernet_flow_control
[ "Ethernet", "has", "flow", "control!", "The", "inter", "-", "frame", "pause", "can", "be", "adjusted", "by", "auto", "-", "negotiation", "through", "an", "ethernet", "frame", "type", "with", "a", "simple", "two", "-", "field", "payload", "and", "by", "sett...
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/ifconfig.py#L306-L320
viraja1/grammar-check
setup.py
get_version
def get_version(): """Return version string.""" with io.open('grammar_check/__init__.py', encoding='utf-8') as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
python
def get_version(): """Return version string.""" with io.open('grammar_check/__init__.py', encoding='utf-8') as input_file: for line in input_file: if line.startswith('__version__'): return ast.parse(line).body[0].value.s
[ "def", "get_version", "(", ")", ":", "with", "io", ".", "open", "(", "'grammar_check/__init__.py'", ",", "encoding", "=", "'utf-8'", ")", "as", "input_file", ":", "for", "line", "in", "input_file", ":", "if", "line", ".", "startswith", "(", "'__version__'", ...
Return version string.
[ "Return", "version", "string", "." ]
train
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/setup.py#L129-L134
viraja1/grammar-check
setup.py
split_elements
def split_elements(value): """Split a string with comma or space-separated elements into a list.""" l = [v.strip() for v in value.split(',')] if len(l) == 1: l = value.split() return l
python
def split_elements(value): """Split a string with comma or space-separated elements into a list.""" l = [v.strip() for v in value.split(',')] if len(l) == 1: l = value.split() return l
[ "def", "split_elements", "(", "value", ")", ":", "l", "=", "[", "v", ".", "strip", "(", ")", "for", "v", "in", "value", ".", "split", "(", "','", ")", "]", "if", "len", "(", "l", ")", "==", "1", ":", "l", "=", "value", ".", "split", "(", ")...
Split a string with comma or space-separated elements into a list.
[ "Split", "a", "string", "with", "comma", "or", "space", "-", "separated", "elements", "into", "a", "list", "." ]
train
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/setup.py#L194-L199
viraja1/grammar-check
setup.py
generate_py2k
def generate_py2k(config, py2k_dir=PY2K_DIR, run_tests=False): """Generate Python 2 code from Python 3 code.""" def copy(src, dst): if (not os.path.isfile(dst) or os.path.getmtime(src) > os.path.getmtime(dst)): shutil.copy(src, dst) return dst return None ...
python
def generate_py2k(config, py2k_dir=PY2K_DIR, run_tests=False): """Generate Python 2 code from Python 3 code.""" def copy(src, dst): if (not os.path.isfile(dst) or os.path.getmtime(src) > os.path.getmtime(dst)): shutil.copy(src, dst) return dst return None ...
[ "def", "generate_py2k", "(", "config", ",", "py2k_dir", "=", "PY2K_DIR", ",", "run_tests", "=", "False", ")", ":", "def", "copy", "(", "src", ",", "dst", ")", ":", "if", "(", "not", "os", ".", "path", ".", "isfile", "(", "dst", ")", "or", "os", "...
Generate Python 2 code from Python 3 code.
[ "Generate", "Python", "2", "code", "from", "Python", "3", "code", "." ]
train
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/setup.py#L448-L551
viraja1/grammar-check
setup.py
default_hook
def default_hook(config): """Default setup hook.""" if (any(arg.startswith('bdist') for arg in sys.argv) and os.path.isdir(PY2K_DIR) != IS_PY2K and os.path.isdir(LIB_DIR)): shutil.rmtree(LIB_DIR) if IS_PY2K and any(arg.startswith('install') or arg.startswith('buil...
python
def default_hook(config): """Default setup hook.""" if (any(arg.startswith('bdist') for arg in sys.argv) and os.path.isdir(PY2K_DIR) != IS_PY2K and os.path.isdir(LIB_DIR)): shutil.rmtree(LIB_DIR) if IS_PY2K and any(arg.startswith('install') or arg.startswith('buil...
[ "def", "default_hook", "(", "config", ")", ":", "if", "(", "any", "(", "arg", ".", "startswith", "(", "'bdist'", ")", "for", "arg", "in", "sys", ".", "argv", ")", "and", "os", ".", "path", ".", "isdir", "(", "PY2K_DIR", ")", "!=", "IS_PY2K", "and",...
Default setup hook.
[ "Default", "setup", "hook", "." ]
train
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/setup.py#L566-L578
rlisagor/pynetlinux
pynetlinux/route.py
get_default_if
def get_default_if(): """ Returns the default interface """ f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): interf = words[0] break except ValueError: pass...
python
def get_default_if(): """ Returns the default interface """ f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): interf = words[0] break except ValueError: pass...
[ "def", "get_default_if", "(", ")", ":", "f", "=", "open", "(", "'/proc/net/route'", ",", "'r'", ")", "for", "line", "in", "f", ":", "words", "=", "line", ".", "split", "(", ")", "dest", "=", "words", "[", "1", "]", "try", ":", "if", "(", "int", ...
Returns the default interface
[ "Returns", "the", "default", "interface" ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/route.py#L1-L13
rlisagor/pynetlinux
pynetlinux/route.py
get_default_gw
def get_default_gw(): """ Returns the default gateway """ octet_list = [] gw_from_route = None f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): gw_from_route = words[2] ...
python
def get_default_gw(): """ Returns the default gateway """ octet_list = [] gw_from_route = None f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): gw_from_route = words[2] ...
[ "def", "get_default_gw", "(", ")", ":", "octet_list", "=", "[", "]", "gw_from_route", "=", "None", "f", "=", "open", "(", "'/proc/net/route'", ",", "'r'", ")", "for", "line", "in", "f", ":", "words", "=", "line", ".", "split", "(", ")", "dest", "=", ...
Returns the default gateway
[ "Returns", "the", "default", "gateway" ]
train
https://github.com/rlisagor/pynetlinux/blob/e3f16978855c6649685f0c43d4c3fcf768427ae5/pynetlinux/route.py#L15-L40
daniellawrence/graphitesend
graphitesend/graphitesend.py
init
def init(init_type='plaintext_tcp', *args, **kwargs): """ Create the module instance of the GraphiteClient. """ global _module_instance reset() validate_init_types = ['plaintext_tcp', 'plaintext', 'pickle_tcp', 'pickle', 'plain'] if init_type not in validate_init...
python
def init(init_type='plaintext_tcp', *args, **kwargs): """ Create the module instance of the GraphiteClient. """ global _module_instance reset() validate_init_types = ['plaintext_tcp', 'plaintext', 'pickle_tcp', 'pickle', 'plain'] if init_type not in validate_init...
[ "def", "init", "(", "init_type", "=", "'plaintext_tcp'", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "_module_instance", "reset", "(", ")", "validate_init_types", "=", "[", "'plaintext_tcp'", ",", "'plaintext'", ",", "'pickle_tcp'", ",", "...
Create the module instance of the GraphiteClient.
[ "Create", "the", "module", "instance", "of", "the", "GraphiteClient", "." ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L526-L550
daniellawrence/graphitesend
graphitesend/graphitesend.py
send
def send(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _module_in...
python
def send(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _module_in...
[ "def", "send", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "_module_instance", ":", "raise", "GraphiteSendException", "(", "\"Must call graphitesend.init() before sending\"", ")", "_module_instance", ".", "send", "(", "*", "args", ",", "*",...
Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method.
[ "Make", "sure", "that", "we", "have", "an", "instance", "of", "the", "GraphiteClient", ".", "Then", "send", "the", "metrics", "to", "the", "graphite", "server", ".", "User", "consumable", "method", "." ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L553-L563
daniellawrence/graphitesend
graphitesend/graphitesend.py
send_dict
def send_dict(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _modul...
python
def send_dict(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _modul...
[ "def", "send_dict", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "_module_instance", ":", "raise", "GraphiteSendException", "(", "\"Must call graphitesend.init() before sending\"", ")", "_module_instance", ".", "send_dict", "(", "*", "args", "...
Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method.
[ "Make", "sure", "that", "we", "have", "an", "instance", "of", "the", "GraphiteClient", ".", "Then", "send", "the", "metrics", "to", "the", "graphite", "server", ".", "User", "consumable", "method", "." ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L566-L575
daniellawrence/graphitesend
graphitesend/graphitesend.py
send_list
def send_list(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _modul...
python
def send_list(*args, **kwargs): """ Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method. """ if not _module_instance: raise GraphiteSendException( "Must call graphitesend.init() before sending") _modul...
[ "def", "send_list", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "_module_instance", ":", "raise", "GraphiteSendException", "(", "\"Must call graphitesend.init() before sending\"", ")", "_module_instance", ".", "send_list", "(", "*", "args", "...
Make sure that we have an instance of the GraphiteClient. Then send the metrics to the graphite server. User consumable method.
[ "Make", "sure", "that", "we", "have", "an", "instance", "of", "the", "GraphiteClient", ".", "Then", "send", "the", "metrics", "to", "the", "graphite", "server", ".", "User", "consumable", "method", "." ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L578-L587
daniellawrence/graphitesend
graphitesend/graphitesend.py
cli
def cli(): """ Allow the module to be called from the cli. """ import argparse parser = argparse.ArgumentParser(description='Send data to graphite') # Core of the application is to accept a metric and a value. parser.add_argument('metric', metavar='metric', type=str, help='...
python
def cli(): """ Allow the module to be called from the cli. """ import argparse parser = argparse.ArgumentParser(description='Send data to graphite') # Core of the application is to accept a metric and a value. parser.add_argument('metric', metavar='metric', type=str, help='...
[ "def", "cli", "(", ")", ":", "import", "argparse", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Send data to graphite'", ")", "# Core of the application is to accept a metric and a value.", "parser", ".", "add_argument", "(", "'metric'", ...
Allow the module to be called from the cli.
[ "Allow", "the", "module", "to", "be", "called", "from", "the", "cli", "." ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L600-L617
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient.connect
def connect(self): """ Make a TCP connection to the graphite server on port self.port """ self.socket = socket.socket() self.socket.settimeout(self.timeout_in_seconds) try: self.socket.connect(self.addr) except socket.timeout: raise Graphit...
python
def connect(self): """ Make a TCP connection to the graphite server on port self.port """ self.socket = socket.socket() self.socket.settimeout(self.timeout_in_seconds) try: self.socket.connect(self.addr) except socket.timeout: raise Graphit...
[ "def", "connect", "(", "self", ")", ":", "self", ".", "socket", "=", "socket", ".", "socket", "(", ")", "self", ".", "socket", ".", "settimeout", "(", "self", ".", "timeout_in_seconds", ")", "try", ":", "self", ".", "socket", ".", "connect", "(", "se...
Make a TCP connection to the graphite server on port self.port
[ "Make", "a", "TCP", "connection", "to", "the", "graphite", "server", "on", "port", "self", ".", "port" ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L148-L169
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient.autoreconnect
def autoreconnect(self, sleep=1, attempt=3, exponential=True, jitter=5): """ Tries to reconnect with some delay: exponential=False: up to `attempt` times with `sleep` seconds between each try exponential=True: up to `attempt` times with exponential growing `sleep` and r...
python
def autoreconnect(self, sleep=1, attempt=3, exponential=True, jitter=5): """ Tries to reconnect with some delay: exponential=False: up to `attempt` times with `sleep` seconds between each try exponential=True: up to `attempt` times with exponential growing `sleep` and r...
[ "def", "autoreconnect", "(", "self", ",", "sleep", "=", "1", ",", "attempt", "=", "3", ",", "exponential", "=", "True", ",", "jitter", "=", "5", ")", ":", "p", "=", "0", "while", "attempt", "is", "None", "or", "attempt", ">", "0", ":", "try", ":"...
Tries to reconnect with some delay: exponential=False: up to `attempt` times with `sleep` seconds between each try exponential=True: up to `attempt` times with exponential growing `sleep` and random delay in range 1..`jitter` (exponential backoff) :param sleep: time to sleep ...
[ "Tries", "to", "reconnect", "with", "some", "delay", ":" ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L175-L213
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient.disconnect
def disconnect(self): """ Close the TCP connection with the graphite server. """ try: self.socket.shutdown(1) # If its currently a socket, set it to None except AttributeError: self.socket = None except Exception: self.socket =...
python
def disconnect(self): """ Close the TCP connection with the graphite server. """ try: self.socket.shutdown(1) # If its currently a socket, set it to None except AttributeError: self.socket = None except Exception: self.socket =...
[ "def", "disconnect", "(", "self", ")", ":", "try", ":", "self", ".", "socket", ".", "shutdown", "(", "1", ")", "# If its currently a socket, set it to None", "except", "AttributeError", ":", "self", ".", "socket", "=", "None", "except", "Exception", ":", "self...
Close the TCP connection with the graphite server.
[ "Close", "the", "TCP", "connection", "with", "the", "graphite", "server", "." ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L221-L236
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient._dispatch_send
def _dispatch_send(self, message): """ Dispatch the different steps of sending """ if self.dryrun: return message if not self.socket: raise GraphiteSendException( "Socket was not created before send" ) sending_functio...
python
def _dispatch_send(self, message): """ Dispatch the different steps of sending """ if self.dryrun: return message if not self.socket: raise GraphiteSendException( "Socket was not created before send" ) sending_functio...
[ "def", "_dispatch_send", "(", "self", ",", "message", ")", ":", "if", "self", ".", "dryrun", ":", "return", "message", "if", "not", "self", ".", "socket", ":", "raise", "GraphiteSendException", "(", "\"Socket was not created before send\"", ")", "sending_function"...
Dispatch the different steps of sending
[ "Dispatch", "the", "different", "steps", "of", "sending" ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L238-L263
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient._send_and_reconnect
def _send_and_reconnect(self, message): """Send _message_ to Graphite Server and attempt reconnect on failure. If _autoreconnect_ was specified, attempt to reconnect if first send fails. :raises AttributeError: When the socket has not been set. :raises socket.error: When the so...
python
def _send_and_reconnect(self, message): """Send _message_ to Graphite Server and attempt reconnect on failure. If _autoreconnect_ was specified, attempt to reconnect if first send fails. :raises AttributeError: When the socket has not been set. :raises socket.error: When the so...
[ "def", "_send_and_reconnect", "(", "self", ",", "message", ")", ":", "try", ":", "self", ".", "socket", ".", "sendall", "(", "message", ".", "encode", "(", "\"ascii\"", ")", ")", "except", "(", "AttributeError", ",", "socket", ".", "error", ")", ":", "...
Send _message_ to Graphite Server and attempt reconnect on failure. If _autoreconnect_ was specified, attempt to reconnect if first send fails. :raises AttributeError: When the socket has not been set. :raises socket.error: When the socket connection is no longer valid.
[ "Send", "_message_", "to", "Graphite", "Server", "and", "attempt", "reconnect", "on", "failure", "." ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L292-L307
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient.send
def send(self, metric, value, timestamp=None, formatter=None): """ Format a single metric/value pair, and send it to the graphite server. :param metric: name of the metric :type prefix: string :param value: value of the metric :type prefix: float or int :...
python
def send(self, metric, value, timestamp=None, formatter=None): """ Format a single metric/value pair, and send it to the graphite server. :param metric: name of the metric :type prefix: string :param value: value of the metric :type prefix: float or int :...
[ "def", "send", "(", "self", ",", "metric", ",", "value", ",", "timestamp", "=", "None", ",", "formatter", "=", "None", ")", ":", "if", "formatter", "is", "None", ":", "formatter", "=", "self", ".", "formatter", "message", "=", "formatter", "(", "metric...
Format a single metric/value pair, and send it to the graphite server. :param metric: name of the metric :type prefix: string :param value: value of the metric :type prefix: float or int :param timestmap: epoch time of the event :type prefix: float or int ...
[ "Format", "a", "single", "metric", "/", "value", "pair", "and", "send", "it", "to", "the", "graphite", "server", "." ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L316-L345
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient.send_dict
def send_dict(self, data, timestamp=None, formatter=None): """ Format a dict of metric/values pairs, and send them all to the graphite server. :param data: key,value pair of metric name and metric value :type prefix: dict :param timestmap: epoch time of the event ...
python
def send_dict(self, data, timestamp=None, formatter=None): """ Format a dict of metric/values pairs, and send them all to the graphite server. :param data: key,value pair of metric name and metric value :type prefix: dict :param timestmap: epoch time of the event ...
[ "def", "send_dict", "(", "self", ",", "data", ",", "timestamp", "=", "None", ",", "formatter", "=", "None", ")", ":", "if", "formatter", "is", "None", ":", "formatter", "=", "self", ".", "formatter", "metric_list", "=", "[", "]", "for", "metric", ",", ...
Format a dict of metric/values pairs, and send them all to the graphite server. :param data: key,value pair of metric name and metric value :type prefix: dict :param timestmap: epoch time of the event :type prefix: float or int :param formatter: option non-default format...
[ "Format", "a", "dict", "of", "metric", "/", "values", "pairs", "and", "send", "them", "all", "to", "the", "graphite", "server", "." ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L347-L375
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphiteClient.enable_asynchronous
def enable_asynchronous(self): """Check if socket have been monkey patched by gevent""" def is_monkey_patched(): try: from gevent import monkey, socket except ImportError: return False if hasattr(monkey, "saved"): retur...
python
def enable_asynchronous(self): """Check if socket have been monkey patched by gevent""" def is_monkey_patched(): try: from gevent import monkey, socket except ImportError: return False if hasattr(monkey, "saved"): retur...
[ "def", "enable_asynchronous", "(", "self", ")", ":", "def", "is_monkey_patched", "(", ")", ":", "try", ":", "from", "gevent", "import", "monkey", ",", "socket", "except", "ImportError", ":", "return", "False", "if", "hasattr", "(", "monkey", ",", "\"saved\""...
Check if socket have been monkey patched by gevent
[ "Check", "if", "socket", "have", "been", "monkey", "patched", "by", "gevent" ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L425-L440
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphitePickleClient.str2listtuple
def str2listtuple(self, string_message): "Covert a string that is ready to be sent to graphite into a tuple" if type(string_message).__name__ not in ('str', 'unicode'): raise TypeError("Must provide a string or unicode") if not string_message.endswith('\n'): string_mess...
python
def str2listtuple(self, string_message): "Covert a string that is ready to be sent to graphite into a tuple" if type(string_message).__name__ not in ('str', 'unicode'): raise TypeError("Must provide a string or unicode") if not string_message.endswith('\n'): string_mess...
[ "def", "str2listtuple", "(", "self", ",", "string_message", ")", ":", "if", "type", "(", "string_message", ")", ".", "__name__", "not", "in", "(", "'str'", ",", "'unicode'", ")", ":", "raise", "TypeError", "(", "\"Must provide a string or unicode\"", ")", "if"...
Covert a string that is ready to be sent to graphite into a tuple
[ "Covert", "a", "string", "that", "is", "ready", "to", "be", "sent", "to", "graphite", "into", "a", "tuple" ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L455-L490
daniellawrence/graphitesend
graphitesend/graphitesend.py
GraphitePickleClient._send
def _send(self, message): """ Given a message send it to the graphite server. """ # An option to lowercase the entire message if self.lowercase_metric_names: message = message.lower() # convert the message into a pickled payload. message = self.str2listtuple(message...
python
def _send(self, message): """ Given a message send it to the graphite server. """ # An option to lowercase the entire message if self.lowercase_metric_names: message = message.lower() # convert the message into a pickled payload. message = self.str2listtuple(message...
[ "def", "_send", "(", "self", ",", "message", ")", ":", "# An option to lowercase the entire message", "if", "self", ".", "lowercase_metric_names", ":", "message", "=", "message", ".", "lower", "(", ")", "# convert the message into a pickled payload.", "message", "=", ...
Given a message send it to the graphite server.
[ "Given", "a", "message", "send", "it", "to", "the", "graphite", "server", "." ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/graphitesend.py#L492-L523
daniellawrence/graphitesend
graphitesend/formatter.py
GraphiteStructuredFormatter.clean_metric_name
def clean_metric_name(self, metric_name): """ Make sure the metric is free of control chars, spaces, tabs, etc. """ if not self._clean_metric_name: return metric_name metric_name = str(metric_name) for _from, _to in self.cleaning_replacement_list: ...
python
def clean_metric_name(self, metric_name): """ Make sure the metric is free of control chars, spaces, tabs, etc. """ if not self._clean_metric_name: return metric_name metric_name = str(metric_name) for _from, _to in self.cleaning_replacement_list: ...
[ "def", "clean_metric_name", "(", "self", ",", "metric_name", ")", ":", "if", "not", "self", ".", "_clean_metric_name", ":", "return", "metric_name", "metric_name", "=", "str", "(", "metric_name", ")", "for", "_from", ",", "_to", "in", "self", ".", "cleaning_...
Make sure the metric is free of control chars, spaces, tabs, etc.
[ "Make", "sure", "the", "metric", "is", "free", "of", "control", "chars", "spaces", "tabs", "etc", "." ]
train
https://github.com/daniellawrence/graphitesend/blob/02281263e642f9b6e146886d4544e1d7aebd7753/graphitesend/formatter.py#L69-L78
viraja1/grammar-check
grammar_check/__init__.py
LanguageTool._get_languages
def _get_languages(cls) -> set: """Get supported languages (by querying the server).""" if not cls._server_is_alive(): cls._start_server_on_free_port() url = urllib.parse.urljoin(cls._url, 'Languages') languages = set() for e in cls._get_root(url, num_tries=1): ...
python
def _get_languages(cls) -> set: """Get supported languages (by querying the server).""" if not cls._server_is_alive(): cls._start_server_on_free_port() url = urllib.parse.urljoin(cls._url, 'Languages') languages = set() for e in cls._get_root(url, num_tries=1): ...
[ "def", "_get_languages", "(", "cls", ")", "->", "set", ":", "if", "not", "cls", ".", "_server_is_alive", "(", ")", ":", "cls", ".", "_start_server_on_free_port", "(", ")", "url", "=", "urllib", ".", "parse", ".", "urljoin", "(", "cls", ".", "_url", ","...
Get supported languages (by querying the server).
[ "Get", "supported", "languages", "(", "by", "querying", "the", "server", ")", "." ]
train
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/grammar_check/__init__.py#L277-L286
viraja1/grammar-check
grammar_check/__init__.py
LanguageTool._get_attrib
def _get_attrib(cls): """Get matches element attributes.""" if not cls._server_is_alive(): cls._start_server_on_free_port() params = {'language': FAILSAFE_LANGUAGE, 'text': ''} data = urllib.parse.urlencode(params).encode() root = cls._get_root(cls._url, data, num_tri...
python
def _get_attrib(cls): """Get matches element attributes.""" if not cls._server_is_alive(): cls._start_server_on_free_port() params = {'language': FAILSAFE_LANGUAGE, 'text': ''} data = urllib.parse.urlencode(params).encode() root = cls._get_root(cls._url, data, num_tri...
[ "def", "_get_attrib", "(", "cls", ")", ":", "if", "not", "cls", ".", "_server_is_alive", "(", ")", ":", "cls", ".", "_start_server_on_free_port", "(", ")", "params", "=", "{", "'language'", ":", "FAILSAFE_LANGUAGE", ",", "'text'", ":", "''", "}", "data", ...
Get matches element attributes.
[ "Get", "matches", "element", "attributes", "." ]
train
https://github.com/viraja1/grammar-check/blob/103bf27119b85b4ef26c8f8d4089b6c882cabe5c/grammar_check/__init__.py#L289-L296
nephila/djangocms-page-meta
djangocms_page_meta/admin.py
get_form
def get_form(self, request, obj=None, **kwargs): """ Patched method for PageAdmin.get_form. Returns a page form without the base field 'meta_description' which is overridden in djangocms-page-meta. This is triggered in the page add view and in the change view if the meta description of the pag...
python
def get_form(self, request, obj=None, **kwargs): """ Patched method for PageAdmin.get_form. Returns a page form without the base field 'meta_description' which is overridden in djangocms-page-meta. This is triggered in the page add view and in the change view if the meta description of the pag...
[ "def", "get_form", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "language", "=", "get_language_from_request", "(", "request", ",", "obj", ")", "form", "=", "_BASE_PAGEADMIN__GET_FORM", "(", "self", ",", "request"...
Patched method for PageAdmin.get_form. Returns a page form without the base field 'meta_description' which is overridden in djangocms-page-meta. This is triggered in the page add view and in the change view if the meta description of the page is empty.
[ "Patched", "method", "for", "PageAdmin", ".", "get_form", "." ]
train
https://github.com/nephila/djangocms-page-meta/blob/a38efe3fe3a717d9ad91bfc6aacab90989cd04a4/djangocms_page_meta/admin.py#L91-L106
nephila/djangocms-page-meta
djangocms_page_meta/utils.py
get_cache_key
def get_cache_key(page, language): """ Create the cache key for the current page and language """ from cms.cache import _get_cache_key try: site_id = page.node.site_id except AttributeError: # CMS_3_4 site_id = page.site_id return _get_cache_key('page_meta', page, language, ...
python
def get_cache_key(page, language): """ Create the cache key for the current page and language """ from cms.cache import _get_cache_key try: site_id = page.node.site_id except AttributeError: # CMS_3_4 site_id = page.site_id return _get_cache_key('page_meta', page, language, ...
[ "def", "get_cache_key", "(", "page", ",", "language", ")", ":", "from", "cms", ".", "cache", "import", "_get_cache_key", "try", ":", "site_id", "=", "page", ".", "node", ".", "site_id", "except", "AttributeError", ":", "# CMS_3_4", "site_id", "=", "page", ...
Create the cache key for the current page and language
[ "Create", "the", "cache", "key", "for", "the", "current", "page", "and", "language" ]
train
https://github.com/nephila/djangocms-page-meta/blob/a38efe3fe3a717d9ad91bfc6aacab90989cd04a4/djangocms_page_meta/utils.py#L10-L19
nephila/djangocms-page-meta
djangocms_page_meta/utils.py
get_page_meta
def get_page_meta(page, language): """ Retrieves all the meta information for the page in the given language :param page: a Page instance :param lang: a language code :return: Meta instance :type: object """ from django.core.cache import cache from meta.views import Meta from ....
python
def get_page_meta(page, language): """ Retrieves all the meta information for the page in the given language :param page: a Page instance :param lang: a language code :return: Meta instance :type: object """ from django.core.cache import cache from meta.views import Meta from ....
[ "def", "get_page_meta", "(", "page", ",", "language", ")", ":", "from", "django", ".", "core", ".", "cache", "import", "cache", "from", "meta", ".", "views", "import", "Meta", "from", ".", "models", "import", "PageMeta", ",", "TitleMeta", "try", ":", "me...
Retrieves all the meta information for the page in the given language :param page: a Page instance :param lang: a language code :return: Meta instance :type: object
[ "Retrieves", "all", "the", "meta", "information", "for", "the", "page", "in", "the", "given", "language" ]
train
https://github.com/nephila/djangocms-page-meta/blob/a38efe3fe3a717d9ad91bfc6aacab90989cd04a4/djangocms_page_meta/utils.py#L22-L143
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
MPR121.begin
def begin(self, address=MPR121_I2CADDR_DEFAULT, i2c=None, **kwargs): """Initialize communication with the MPR121. Can specify a custom I2C address for the device using the address parameter (defaults to 0x5A). Optional i2c parameter allows specifying a custom I2C bus source (defaults...
python
def begin(self, address=MPR121_I2CADDR_DEFAULT, i2c=None, **kwargs): """Initialize communication with the MPR121. Can specify a custom I2C address for the device using the address parameter (defaults to 0x5A). Optional i2c parameter allows specifying a custom I2C bus source (defaults...
[ "def", "begin", "(", "self", ",", "address", "=", "MPR121_I2CADDR_DEFAULT", ",", "i2c", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Assume we're using platform's default I2C bus if none is specified.", "if", "i2c", "is", "None", ":", "import", "Adafruit_GPIO"...
Initialize communication with the MPR121. Can specify a custom I2C address for the device using the address parameter (defaults to 0x5A). Optional i2c parameter allows specifying a custom I2C bus source (defaults to platform's I2C bus). Returns True if communication with the MPR121 ...
[ "Initialize", "communication", "with", "the", "MPR121", "." ]
train
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L73-L93
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
MPR121.set_thresholds
def set_thresholds(self, touch, release): """Set the touch and release threshold for all inputs to the provided values. Both touch and release should be a value between 0 to 255 (inclusive). """ assert touch >= 0 and touch <= 255, 'touch must be between 0-255 (inclusive)' ...
python
def set_thresholds(self, touch, release): """Set the touch and release threshold for all inputs to the provided values. Both touch and release should be a value between 0 to 255 (inclusive). """ assert touch >= 0 and touch <= 255, 'touch must be between 0-255 (inclusive)' ...
[ "def", "set_thresholds", "(", "self", ",", "touch", ",", "release", ")", ":", "assert", "touch", ">=", "0", "and", "touch", "<=", "255", ",", "'touch must be between 0-255 (inclusive)'", "assert", "release", ">=", "0", "and", "release", "<=", "255", ",", "'r...
Set the touch and release threshold for all inputs to the provided values. Both touch and release should be a value between 0 to 255 (inclusive).
[ "Set", "the", "touch", "and", "release", "threshold", "for", "all", "inputs", "to", "the", "provided", "values", ".", "Both", "touch", "and", "release", "should", "be", "a", "value", "between", "0", "to", "255", "(", "inclusive", ")", "." ]
train
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L148-L158
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
MPR121.filtered_data
def filtered_data(self, pin): """Return filtered data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' return self._i2c_retry(self._device.readU16LE, MPR121_FILTDATA_0L + pin*2)
python
def filtered_data(self, pin): """Return filtered data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' return self._i2c_retry(self._device.readU16LE, MPR121_FILTDATA_0L + pin*2)
[ "def", "filtered_data", "(", "self", ",", "pin", ")", ":", "assert", "pin", ">=", "0", "and", "pin", "<", "12", ",", "'pin must be between 0-11 (inclusive)'", "return", "self", ".", "_i2c_retry", "(", "self", ".", "_device", ".", "readU16LE", ",", "MPR121_FI...
Return filtered data register value for the provided pin (0-11). Useful for debugging.
[ "Return", "filtered", "data", "register", "value", "for", "the", "provided", "pin", "(", "0", "-", "11", ")", ".", "Useful", "for", "debugging", "." ]
train
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L160-L165
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
MPR121.baseline_data
def baseline_data(self, pin): """Return baseline data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' bl = self._i2c_retry(self._device.readU8, MPR121_BASELINE_0 + pin) return bl <<...
python
def baseline_data(self, pin): """Return baseline data register value for the provided pin (0-11). Useful for debugging. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' bl = self._i2c_retry(self._device.readU8, MPR121_BASELINE_0 + pin) return bl <<...
[ "def", "baseline_data", "(", "self", ",", "pin", ")", ":", "assert", "pin", ">=", "0", "and", "pin", "<", "12", ",", "'pin must be between 0-11 (inclusive)'", "bl", "=", "self", ".", "_i2c_retry", "(", "self", ".", "_device", ".", "readU8", ",", "MPR121_BA...
Return baseline data register value for the provided pin (0-11). Useful for debugging.
[ "Return", "baseline", "data", "register", "value", "for", "the", "provided", "pin", "(", "0", "-", "11", ")", ".", "Useful", "for", "debugging", "." ]
train
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L167-L173
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
MPR121.touched
def touched(self): """Return touch state of all pins as a 12-bit value where each bit represents a pin, with a value of 1 being touched and 0 not being touched. """ t = self._i2c_retry(self._device.readU16LE, MPR121_TOUCHSTATUS_L) return t & 0x0FFF
python
def touched(self): """Return touch state of all pins as a 12-bit value where each bit represents a pin, with a value of 1 being touched and 0 not being touched. """ t = self._i2c_retry(self._device.readU16LE, MPR121_TOUCHSTATUS_L) return t & 0x0FFF
[ "def", "touched", "(", "self", ")", ":", "t", "=", "self", ".", "_i2c_retry", "(", "self", ".", "_device", ".", "readU16LE", ",", "MPR121_TOUCHSTATUS_L", ")", "return", "t", "&", "0x0FFF" ]
Return touch state of all pins as a 12-bit value where each bit represents a pin, with a value of 1 being touched and 0 not being touched.
[ "Return", "touch", "state", "of", "all", "pins", "as", "a", "12", "-", "bit", "value", "where", "each", "bit", "represents", "a", "pin", "with", "a", "value", "of", "1", "being", "touched", "and", "0", "not", "being", "touched", "." ]
train
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L175-L180
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
MPR121.is_touched
def is_touched(self, pin): """Return True if the specified pin is being touched, otherwise returns False. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' t = self.touched() return (t & (1 << pin)) > 0
python
def is_touched(self, pin): """Return True if the specified pin is being touched, otherwise returns False. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' t = self.touched() return (t & (1 << pin)) > 0
[ "def", "is_touched", "(", "self", ",", "pin", ")", ":", "assert", "pin", ">=", "0", "and", "pin", "<", "12", ",", "'pin must be between 0-11 (inclusive)'", "t", "=", "self", ".", "touched", "(", ")", "return", "(", "t", "&", "(", "1", "<<", "pin", ")...
Return True if the specified pin is being touched, otherwise returns False.
[ "Return", "True", "if", "the", "specified", "pin", "is", "being", "touched", "otherwise", "returns", "False", "." ]
train
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L182-L188
vertical-knowledge/ripozo-sqlalchemy
profiling/profile.py
profileit
def profileit(func): """ Decorator straight up stolen from stackoverflow """ def wrapper(*args, **kwargs): datafn = func.__name__ + ".profile" # Name the data file sensibly prof = cProfile.Profile() prof.enable() retval = prof.runcall(func, *args, **kwargs) prof.d...
python
def profileit(func): """ Decorator straight up stolen from stackoverflow """ def wrapper(*args, **kwargs): datafn = func.__name__ + ".profile" # Name the data file sensibly prof = cProfile.Profile() prof.enable() retval = prof.runcall(func, *args, **kwargs) prof.d...
[ "def", "profileit", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "datafn", "=", "func", ".", "__name__", "+", "\".profile\"", "# Name the data file sensibly", "prof", "=", "cProfile", ".", "Profile", "(", ...
Decorator straight up stolen from stackoverflow
[ "Decorator", "straight", "up", "stolen", "from", "stackoverflow" ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/profiling/profile.py#L29-L46
gforcada/haproxy_log_analysis
haproxy/filters.py
filter_ip_range
def filter_ip_range(ip_range): """Filter :class:`.Line` objects by IP range. Both *192.168.1.203* and *192.168.1.10* are valid if the provided ip range is ``192.168.1`` whereas *192.168.2.103* is not valid (note the *.2.*). :param ip_range: IP range that you want to filter to. :type ip_range: ...
python
def filter_ip_range(ip_range): """Filter :class:`.Line` objects by IP range. Both *192.168.1.203* and *192.168.1.10* are valid if the provided ip range is ``192.168.1`` whereas *192.168.2.103* is not valid (note the *.2.*). :param ip_range: IP range that you want to filter to. :type ip_range: ...
[ "def", "filter_ip_range", "(", "ip_range", ")", ":", "def", "filter_func", "(", "log_line", ")", ":", "ip", "=", "log_line", ".", "get_ip", "(", ")", "if", "ip", ":", "return", "ip", ".", "startswith", "(", "ip_range", ")", "return", "filter_func" ]
Filter :class:`.Line` objects by IP range. Both *192.168.1.203* and *192.168.1.10* are valid if the provided ip range is ``192.168.1`` whereas *192.168.2.103* is not valid (note the *.2.*). :param ip_range: IP range that you want to filter to. :type ip_range: string :returns: a function that f...
[ "Filter", ":", "class", ":", ".", "Line", "objects", "by", "IP", "range", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/filters.py#L22-L39
gforcada/haproxy_log_analysis
haproxy/filters.py
filter_slow_requests
def filter_slow_requests(slowness): """Filter :class:`.Line` objects by their response time. :param slowness: minimum time, in milliseconds, a server needs to answer a request. If the server takes more time than that the log line is accepted. :type slowness: string :returns: a function that...
python
def filter_slow_requests(slowness): """Filter :class:`.Line` objects by their response time. :param slowness: minimum time, in milliseconds, a server needs to answer a request. If the server takes more time than that the log line is accepted. :type slowness: string :returns: a function that...
[ "def", "filter_slow_requests", "(", "slowness", ")", ":", "def", "filter_func", "(", "log_line", ")", ":", "slowness_int", "=", "int", "(", "slowness", ")", "return", "slowness_int", "<=", "log_line", ".", "time_wait_response", "return", "filter_func" ]
Filter :class:`.Line` objects by their response time. :param slowness: minimum time, in milliseconds, a server needs to answer a request. If the server takes more time than that the log line is accepted. :type slowness: string :returns: a function that filters by the server response time. :...
[ "Filter", ":", "class", ":", ".", "Line", "objects", "by", "their", "response", "time", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/filters.py#L71-L85
gforcada/haproxy_log_analysis
haproxy/filters.py
filter_wait_on_queues
def filter_wait_on_queues(max_waiting): """Filter :class:`.Line` objects by their queueing time in HAProxy. :param max_waiting: maximum time, in milliseconds, a request is waiting on HAProxy prior to be delivered to a backend server. If HAProxy takes less than that time the log line is counted....
python
def filter_wait_on_queues(max_waiting): """Filter :class:`.Line` objects by their queueing time in HAProxy. :param max_waiting: maximum time, in milliseconds, a request is waiting on HAProxy prior to be delivered to a backend server. If HAProxy takes less than that time the log line is counted....
[ "def", "filter_wait_on_queues", "(", "max_waiting", ")", ":", "def", "filter_func", "(", "log_line", ")", ":", "waiting", "=", "int", "(", "max_waiting", ")", "return", "waiting", ">=", "log_line", ".", "time_wait_queues", "return", "filter_func" ]
Filter :class:`.Line` objects by their queueing time in HAProxy. :param max_waiting: maximum time, in milliseconds, a request is waiting on HAProxy prior to be delivered to a backend server. If HAProxy takes less than that time the log line is counted. :type max_waiting: string :returns: a ...
[ "Filter", ":", "class", ":", ".", "Line", "objects", "by", "their", "queueing", "time", "in", "HAProxy", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/filters.py#L88-L103
gforcada/haproxy_log_analysis
haproxy/filters.py
filter_time_frame
def filter_time_frame(start, delta): """Filter :class:`.Line` objects by their connection time. :param start: a time expression (see -s argument on --help for its format) to filter log lines that are before this time. :type start: string :param delta: a relative time expression (see -s argument o...
python
def filter_time_frame(start, delta): """Filter :class:`.Line` objects by their connection time. :param start: a time expression (see -s argument on --help for its format) to filter log lines that are before this time. :type start: string :param delta: a relative time expression (see -s argument o...
[ "def", "filter_time_frame", "(", "start", ",", "delta", ")", ":", "start_value", "=", "start", "delta_value", "=", "delta", "end_value", "=", "None", "if", "start_value", "is", "not", "''", ":", "start_value", "=", "_date_str_to_datetime", "(", "start_value", ...
Filter :class:`.Line` objects by their connection time. :param start: a time expression (see -s argument on --help for its format) to filter log lines that are before this time. :type start: string :param delta: a relative time expression (see -s argument on --help for its format) to limit the ...
[ "Filter", ":", "class", ":", ".", "Line", "objects", "by", "their", "connection", "time", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/filters.py#L106-L144
gforcada/haproxy_log_analysis
haproxy/filters.py
filter_response_size
def filter_response_size(size): """Filter :class:`.Line` objects by the response size (in bytes). Specially useful when looking for big file downloads. :param size: Minimum amount of bytes a response body weighted. :type size: string :returns: a function that filters by the response size. :rty...
python
def filter_response_size(size): """Filter :class:`.Line` objects by the response size (in bytes). Specially useful when looking for big file downloads. :param size: Minimum amount of bytes a response body weighted. :type size: string :returns: a function that filters by the response size. :rty...
[ "def", "filter_response_size", "(", "size", ")", ":", "if", "size", ".", "startswith", "(", "'+'", ")", ":", "size_value", "=", "int", "(", "size", "[", "1", ":", "]", ")", "else", ":", "size_value", "=", "int", "(", "size", ")", "def", "filter_func"...
Filter :class:`.Line` objects by the response size (in bytes). Specially useful when looking for big file downloads. :param size: Minimum amount of bytes a response body weighted. :type size: string :returns: a function that filters by the response size. :rtype: function
[ "Filter", ":", "class", ":", ".", "Line", "objects", "by", "the", "response", "size", "(", "in", "bytes", ")", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/filters.py#L238-L262
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/easy_resource.py
_get_fields_for_model
def _get_fields_for_model(model): """ Gets all of the fields on the model. :param DeclarativeModel model: A SQLAlchemy ORM Model :return: A tuple of the fields on the Model corresponding to the columns on the Model. :rtype: tuple """ fields = [] for name in model._sa_class_manag...
python
def _get_fields_for_model(model): """ Gets all of the fields on the model. :param DeclarativeModel model: A SQLAlchemy ORM Model :return: A tuple of the fields on the Model corresponding to the columns on the Model. :rtype: tuple """ fields = [] for name in model._sa_class_manag...
[ "def", "_get_fields_for_model", "(", "model", ")", ":", "fields", "=", "[", "]", "for", "name", "in", "model", ".", "_sa_class_manager", ":", "prop", "=", "getattr", "(", "model", ",", "name", ")", "if", "isinstance", "(", "prop", ".", "property", ",", ...
Gets all of the fields on the model. :param DeclarativeModel model: A SQLAlchemy ORM Model :return: A tuple of the fields on the Model corresponding to the columns on the Model. :rtype: tuple
[ "Gets", "all", "of", "the", "fields", "on", "the", "model", "." ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/easy_resource.py#L16-L33
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/easy_resource.py
_get_relationships
def _get_relationships(model): """ Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships o...
python
def _get_relationships(model): """ Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships o...
[ "def", "_get_relationships", "(", "model", ")", ":", "relationships", "=", "[", "]", "for", "name", ",", "relationship", "in", "inspect", "(", "model", ")", ".", "relationships", ".", "items", "(", ")", ":", "class_", "=", "relationship", ".", "mapper", ...
Gets the necessary relationships for the resource by inspecting the sqlalchemy model for relationships. :param DeclarativeMeta model: The SQLAlchemy ORM model. :return: A tuple of Relationship/ListRelationship instances corresponding to the relationships on the Model. :rtype: tuple
[ "Gets", "the", "necessary", "relationships", "for", "the", "resource", "by", "inspecting", "the", "sqlalchemy", "model", "for", "relationships", "." ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/easy_resource.py#L48-L66
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/easy_resource.py
create_resource
def create_resource(model, session_handler, resource_bases=(CRUDL,), relationships=None, links=None, preprocessors=None, postprocessors=None, fields=None, paginate_by=100, auto_relationships=True, pks=None, create_fields=None, update_fields...
python
def create_resource(model, session_handler, resource_bases=(CRUDL,), relationships=None, links=None, preprocessors=None, postprocessors=None, fields=None, paginate_by=100, auto_relationships=True, pks=None, create_fields=None, update_fields...
[ "def", "create_resource", "(", "model", ",", "session_handler", ",", "resource_bases", "=", "(", "CRUDL", ",", ")", ",", "relationships", "=", "None", ",", "links", "=", "None", ",", "preprocessors", "=", "None", ",", "postprocessors", "=", "None", ",", "f...
Creates a ResourceBase subclass by inspecting a SQLAlchemy Model. This is somewhat more restrictive than explicitly creating managers and resources. However, if you only need any of the basic CRUD+L operations, :param sqlalchemy.Model model: This is the model that will be ...
[ "Creates", "a", "ResourceBase", "subclass", "by", "inspecting", "a", "SQLAlchemy", "Model", ".", "This", "is", "somewhat", "more", "restrictive", "than", "explicitly", "creating", "managers", "and", "resources", ".", "However", "if", "you", "only", "need", "any"...
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/easy_resource.py#L69-L145
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log._is_pickle_valid
def _is_pickle_valid(self): """Logic to decide if the file should be processed or just needs to be loaded from its pickle data. """ if not os.path.exists(self._pickle_file): return False else: file_mtime = os.path.getmtime(self.logfile) pickle_...
python
def _is_pickle_valid(self): """Logic to decide if the file should be processed or just needs to be loaded from its pickle data. """ if not os.path.exists(self._pickle_file): return False else: file_mtime = os.path.getmtime(self.logfile) pickle_...
[ "def", "_is_pickle_valid", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "_pickle_file", ")", ":", "return", "False", "else", ":", "file_mtime", "=", "os", ".", "path", ".", "getmtime", "(", "self", ".", "log...
Logic to decide if the file should be processed or just needs to be loaded from its pickle data.
[ "Logic", "to", "decide", "if", "the", "file", "should", "be", "processed", "or", "just", "needs", "to", "be", "loaded", "from", "its", "pickle", "data", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L44-L55
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log._load
def _load(self): """Load data from a pickle file. """ with open(self._pickle_file, 'rb') as source: pickler = pickle.Unpickler(source) for attribute in self._pickle_attributes: pickle_data = pickler.load() setattr(self, attribute, pickle_data)
python
def _load(self): """Load data from a pickle file. """ with open(self._pickle_file, 'rb') as source: pickler = pickle.Unpickler(source) for attribute in self._pickle_attributes: pickle_data = pickler.load() setattr(self, attribute, pickle_data)
[ "def", "_load", "(", "self", ")", ":", "with", "open", "(", "self", ".", "_pickle_file", ",", "'rb'", ")", "as", "source", ":", "pickler", "=", "pickle", ".", "Unpickler", "(", "source", ")", "for", "attribute", "in", "self", ".", "_pickle_attributes", ...
Load data from a pickle file.
[ "Load", "data", "from", "a", "pickle", "file", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L57-L64
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log._save
def _save(self): """Save the attributes defined on _pickle_attributes in a pickle file. This improves a lot the nth run as the log file does not need to be processed every time. """ with open(self._pickle_file, 'wb') as source: pickler = pickle.Pickler(source, pickle...
python
def _save(self): """Save the attributes defined on _pickle_attributes in a pickle file. This improves a lot the nth run as the log file does not need to be processed every time. """ with open(self._pickle_file, 'wb') as source: pickler = pickle.Pickler(source, pickle...
[ "def", "_save", "(", "self", ")", ":", "with", "open", "(", "self", ".", "_pickle_file", ",", "'wb'", ")", "as", "source", ":", "pickler", "=", "pickle", ".", "Pickler", "(", "source", ",", "pickle", ".", "HIGHEST_PROTOCOL", ")", "for", "attribute", "i...
Save the attributes defined on _pickle_attributes in a pickle file. This improves a lot the nth run as the log file does not need to be processed every time.
[ "Save", "the", "attributes", "defined", "on", "_pickle_attributes", "in", "a", "pickle", "file", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L66-L77
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.parse_data
def parse_data(self, logfile): """Parse data from data stream and replace object lines. :param logfile: [required] Log file data stream. :type logfile: str """ for line in logfile: stripped_line = line.strip() parsed_line = Line(stripped_line) ...
python
def parse_data(self, logfile): """Parse data from data stream and replace object lines. :param logfile: [required] Log file data stream. :type logfile: str """ for line in logfile: stripped_line = line.strip() parsed_line = Line(stripped_line) ...
[ "def", "parse_data", "(", "self", ",", "logfile", ")", ":", "for", "line", "in", "logfile", ":", "stripped_line", "=", "line", ".", "strip", "(", ")", "parsed_line", "=", "Line", "(", "stripped_line", ")", "if", "parsed_line", ".", "valid", ":", "self", ...
Parse data from data stream and replace object lines. :param logfile: [required] Log file data stream. :type logfile: str
[ "Parse", "data", "from", "data", "stream", "and", "replace", "object", "lines", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L79-L94
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.filter
def filter(self, filter_func, reverse=False): """Filter current log lines by a given filter function. This allows to drill down data out of the log file by filtering the relevant log lines to analyze. For example, filter by a given IP so only log lines for that IP are further p...
python
def filter(self, filter_func, reverse=False): """Filter current log lines by a given filter function. This allows to drill down data out of the log file by filtering the relevant log lines to analyze. For example, filter by a given IP so only log lines for that IP are further p...
[ "def", "filter", "(", "self", ",", "filter_func", ",", "reverse", "=", "False", ")", ":", "new_log_file", "=", "Log", "(", ")", "new_log_file", ".", "logfile", "=", "self", ".", "logfile", "new_log_file", ".", "total_lines", "=", "0", "new_log_file", ".", ...
Filter current log lines by a given filter function. This allows to drill down data out of the log file by filtering the relevant log lines to analyze. For example, filter by a given IP so only log lines for that IP are further processed with commands (top paths, http status counter......
[ "Filter", "current", "log", "lines", "by", "a", "given", "filter", "function", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L96-L136
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.commands
def commands(cls): """Returns a list of all methods that start with ``cmd_``.""" cmds = [cmd[4:] for cmd in dir(cls) if cmd.startswith('cmd_')] return cmds
python
def commands(cls): """Returns a list of all methods that start with ``cmd_``.""" cmds = [cmd[4:] for cmd in dir(cls) if cmd.startswith('cmd_')] return cmds
[ "def", "commands", "(", "cls", ")", ":", "cmds", "=", "[", "cmd", "[", "4", ":", "]", "for", "cmd", "in", "dir", "(", "cls", ")", "if", "cmd", ".", "startswith", "(", "'cmd_'", ")", "]", "return", "cmds" ]
Returns a list of all methods that start with ``cmd_``.
[ "Returns", "a", "list", "of", "all", "methods", "that", "start", "with", "cmd_", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L139-L142
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_http_methods
def cmd_http_methods(self): """Reports a breakdown of how many requests have been made per HTTP method (GET, POST...). """ methods = defaultdict(int) for line in self._valid_lines: methods[line.http_request_method] += 1 return methods
python
def cmd_http_methods(self): """Reports a breakdown of how many requests have been made per HTTP method (GET, POST...). """ methods = defaultdict(int) for line in self._valid_lines: methods[line.http_request_method] += 1 return methods
[ "def", "cmd_http_methods", "(", "self", ")", ":", "methods", "=", "defaultdict", "(", "int", ")", "for", "line", "in", "self", ".", "_valid_lines", ":", "methods", "[", "line", ".", "http_request_method", "]", "+=", "1", "return", "methods" ]
Reports a breakdown of how many requests have been made per HTTP method (GET, POST...).
[ "Reports", "a", "breakdown", "of", "how", "many", "requests", "have", "been", "made", "per", "HTTP", "method", "(", "GET", "POST", "...", ")", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L152-L159
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_ip_counter
def cmd_ip_counter(self): """Reports a breakdown of how many requests have been made per IP. .. note:: To enable this command requests need to provide a header with the forwarded IP (usually X-Forwarded-For) and be it the only header being captured. """ ip_...
python
def cmd_ip_counter(self): """Reports a breakdown of how many requests have been made per IP. .. note:: To enable this command requests need to provide a header with the forwarded IP (usually X-Forwarded-For) and be it the only header being captured. """ ip_...
[ "def", "cmd_ip_counter", "(", "self", ")", ":", "ip_counter", "=", "defaultdict", "(", "int", ")", "for", "line", "in", "self", ".", "_valid_lines", ":", "ip", "=", "line", ".", "get_ip", "(", ")", "if", "ip", "is", "not", "None", ":", "ip_counter", ...
Reports a breakdown of how many requests have been made per IP. .. note:: To enable this command requests need to provide a header with the forwarded IP (usually X-Forwarded-For) and be it the only header being captured.
[ "Reports", "a", "breakdown", "of", "how", "many", "requests", "have", "been", "made", "per", "IP", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L161-L174
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_status_codes_counter
def cmd_status_codes_counter(self): """Generate statistics about HTTP status codes. 404, 500 and so on. """ status_codes = defaultdict(int) for line in self._valid_lines: status_codes[line.status_code] += 1 return status_codes
python
def cmd_status_codes_counter(self): """Generate statistics about HTTP status codes. 404, 500 and so on. """ status_codes = defaultdict(int) for line in self._valid_lines: status_codes[line.status_code] += 1 return status_codes
[ "def", "cmd_status_codes_counter", "(", "self", ")", ":", "status_codes", "=", "defaultdict", "(", "int", ")", "for", "line", "in", "self", ".", "_valid_lines", ":", "status_codes", "[", "line", ".", "status_code", "]", "+=", "1", "return", "status_codes" ]
Generate statistics about HTTP status codes. 404, 500 and so on.
[ "Generate", "statistics", "about", "HTTP", "status", "codes", ".", "404", "500", "and", "so", "on", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L188-L194
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_request_path_counter
def cmd_request_path_counter(self): """Generate statistics about HTTP requests' path.""" paths = defaultdict(int) for line in self._valid_lines: paths[line.http_request_path] += 1 return paths
python
def cmd_request_path_counter(self): """Generate statistics about HTTP requests' path.""" paths = defaultdict(int) for line in self._valid_lines: paths[line.http_request_path] += 1 return paths
[ "def", "cmd_request_path_counter", "(", "self", ")", ":", "paths", "=", "defaultdict", "(", "int", ")", "for", "line", "in", "self", ".", "_valid_lines", ":", "paths", "[", "line", ".", "http_request_path", "]", "+=", "1", "return", "paths" ]
Generate statistics about HTTP requests' path.
[ "Generate", "statistics", "about", "HTTP", "requests", "path", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L196-L201
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_slow_requests
def cmd_slow_requests(self): """List all requests that took a certain amount of time to be processed. .. warning:: By now hardcoded to 1 second (1000 milliseconds), improve the command line interface to allow to send parameters to each command or globally. ...
python
def cmd_slow_requests(self): """List all requests that took a certain amount of time to be processed. .. warning:: By now hardcoded to 1 second (1000 milliseconds), improve the command line interface to allow to send parameters to each command or globally. ...
[ "def", "cmd_slow_requests", "(", "self", ")", ":", "slow_requests", "=", "[", "line", ".", "time_wait_response", "for", "line", "in", "self", ".", "_valid_lines", "if", "line", ".", "time_wait_response", ">", "1000", "]", "return", "slow_requests" ]
List all requests that took a certain amount of time to be processed. .. warning:: By now hardcoded to 1 second (1000 milliseconds), improve the command line interface to allow to send parameters to each command or globally.
[ "List", "all", "requests", "that", "took", "a", "certain", "amount", "of", "time", "to", "be", "processed", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L215-L229
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_average_response_time
def cmd_average_response_time(self): """Returns the average response time of all, non aborted, requests.""" average = [ line.time_wait_response for line in self._valid_lines if line.time_wait_response >= 0 ] divisor = float(len(average)) if di...
python
def cmd_average_response_time(self): """Returns the average response time of all, non aborted, requests.""" average = [ line.time_wait_response for line in self._valid_lines if line.time_wait_response >= 0 ] divisor = float(len(average)) if di...
[ "def", "cmd_average_response_time", "(", "self", ")", ":", "average", "=", "[", "line", ".", "time_wait_response", "for", "line", "in", "self", ".", "_valid_lines", "if", "line", ".", "time_wait_response", ">=", "0", "]", "divisor", "=", "float", "(", "len",...
Returns the average response time of all, non aborted, requests.
[ "Returns", "the", "average", "response", "time", "of", "all", "non", "aborted", "requests", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L231-L242
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_average_waiting_time
def cmd_average_waiting_time(self): """Returns the average queue time of all, non aborted, requests.""" average = [ line.time_wait_queues for line in self._valid_lines if line.time_wait_queues >= 0 ] divisor = float(len(average)) if divisor > ...
python
def cmd_average_waiting_time(self): """Returns the average queue time of all, non aborted, requests.""" average = [ line.time_wait_queues for line in self._valid_lines if line.time_wait_queues >= 0 ] divisor = float(len(average)) if divisor > ...
[ "def", "cmd_average_waiting_time", "(", "self", ")", ":", "average", "=", "[", "line", ".", "time_wait_queues", "for", "line", "in", "self", ".", "_valid_lines", "if", "line", ".", "time_wait_queues", ">=", "0", "]", "divisor", "=", "float", "(", "len", "(...
Returns the average queue time of all, non aborted, requests.
[ "Returns", "the", "average", "queue", "time", "of", "all", "non", "aborted", "requests", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L244-L255
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_server_load
def cmd_server_load(self): """Generate statistics regarding how many requests were processed by each downstream server. """ servers = defaultdict(int) for line in self._valid_lines: servers[line.server_name] += 1 return servers
python
def cmd_server_load(self): """Generate statistics regarding how many requests were processed by each downstream server. """ servers = defaultdict(int) for line in self._valid_lines: servers[line.server_name] += 1 return servers
[ "def", "cmd_server_load", "(", "self", ")", ":", "servers", "=", "defaultdict", "(", "int", ")", "for", "line", "in", "self", ".", "_valid_lines", ":", "servers", "[", "line", ".", "server_name", "]", "+=", "1", "return", "servers" ]
Generate statistics regarding how many requests were processed by each downstream server.
[ "Generate", "statistics", "regarding", "how", "many", "requests", "were", "processed", "by", "each", "downstream", "server", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L268-L275
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_queue_peaks
def cmd_queue_peaks(self): """Generate a list of the requests peaks on the queue. A queue peak is defined by the biggest value on the backend queue on a series of log lines that are between log lines without being queued. .. warning:: Allow to configure up to which pe...
python
def cmd_queue_peaks(self): """Generate a list of the requests peaks on the queue. A queue peak is defined by the biggest value on the backend queue on a series of log lines that are between log lines without being queued. .. warning:: Allow to configure up to which pe...
[ "def", "cmd_queue_peaks", "(", "self", ")", ":", "threshold", "=", "1", "peaks", "=", "[", "]", "current_peak", "=", "0", "current_queue", "=", "0", "current_span", "=", "0", "first_on_queue", "=", "None", "for", "line", "in", "self", ".", "_valid_lines", ...
Generate a list of the requests peaks on the queue. A queue peak is defined by the biggest value on the backend queue on a series of log lines that are between log lines without being queued. .. warning:: Allow to configure up to which peak can be ignored. Currently ...
[ "Generate", "a", "list", "of", "the", "requests", "peaks", "on", "the", "queue", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L277-L330
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_connection_type
def cmd_connection_type(self): """Generates statistics on how many requests are made via HTTP and how many are made via SSL. .. note:: This only works if the request path contains the default port for SSL (443). .. warning:: The ports are hardcoded, they s...
python
def cmd_connection_type(self): """Generates statistics on how many requests are made via HTTP and how many are made via SSL. .. note:: This only works if the request path contains the default port for SSL (443). .. warning:: The ports are hardcoded, they s...
[ "def", "cmd_connection_type", "(", "self", ")", ":", "https", "=", "0", "non_https", "=", "0", "for", "line", "in", "self", ".", "_valid_lines", ":", "if", "line", ".", "is_https", "(", ")", ":", "https", "+=", "1", "else", ":", "non_https", "+=", "1...
Generates statistics on how many requests are made via HTTP and how many are made via SSL. .. note:: This only works if the request path contains the default port for SSL (443). .. warning:: The ports are hardcoded, they should be configurable.
[ "Generates", "statistics", "on", "how", "many", "requests", "are", "made", "via", "HTTP", "and", "how", "many", "are", "made", "via", "SSL", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L332-L350
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_requests_per_minute
def cmd_requests_per_minute(self): """Generates statistics on how many requests were made per minute. .. note:: Try to combine it with time constrains (``-s`` and ``-d``) as this command output can be huge otherwise. """ if len(self._valid_lines) == 0: re...
python
def cmd_requests_per_minute(self): """Generates statistics on how many requests were made per minute. .. note:: Try to combine it with time constrains (``-s`` and ``-d``) as this command output can be huge otherwise. """ if len(self._valid_lines) == 0: re...
[ "def", "cmd_requests_per_minute", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_valid_lines", ")", "==", "0", ":", "return", "current_minute", "=", "self", ".", "_valid_lines", "[", "0", "]", ".", "accept_date", "current_minute_counter", "=", "0", ...
Generates statistics on how many requests were made per minute. .. note:: Try to combine it with time constrains (``-s`` and ``-d``) as this command output can be huge otherwise.
[ "Generates", "statistics", "on", "how", "many", "requests", "were", "made", "per", "minute", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L352-L398
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log.cmd_print
def cmd_print(self): """Returns the raw lines to be printed.""" if not self._valid_lines: return '' return '\n'.join([line.raw_line for line in self._valid_lines]) + '\n'
python
def cmd_print(self): """Returns the raw lines to be printed.""" if not self._valid_lines: return '' return '\n'.join([line.raw_line for line in self._valid_lines]) + '\n'
[ "def", "cmd_print", "(", "self", ")", ":", "if", "not", "self", ".", "_valid_lines", ":", "return", "''", "return", "'\\n'", ".", "join", "(", "[", "line", ".", "raw_line", "for", "line", "in", "self", ".", "_valid_lines", "]", ")", "+", "'\\n'" ]
Returns the raw lines to be printed.
[ "Returns", "the", "raw", "lines", "to", "be", "printed", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L400-L404
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log._sort_lines
def _sort_lines(self): """Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are...
python
def _sort_lines(self): """Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are...
[ "def", "_sort_lines", "(", "self", ")", ":", "self", ".", "_valid_lines", "=", "sorted", "(", "self", ".", "_valid_lines", ",", "key", "=", "lambda", "line", ":", "line", ".", "accept_date", ",", ")" ]
Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are already processed and log...
[ "Haproxy", "writes", "its", "logs", "after", "having", "gathered", "all", "information", "related", "to", "each", "specific", "connection", ".", "A", "simple", "request", "can", "be", "really", "quick", "but", "others", "can", "be", "really", "slow", "thus", ...
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L406-L419
gforcada/haproxy_log_analysis
haproxy/logfile.py
Log._sort_and_trim
def _sort_and_trim(data, reverse=False): """Sorts a dictionary with at least two fields on each of them sorting by the second element. .. warning:: Right now is hardcoded to 10 elements, improve the command line interface to allow to send parameters to each command or global...
python
def _sort_and_trim(data, reverse=False): """Sorts a dictionary with at least two fields on each of them sorting by the second element. .. warning:: Right now is hardcoded to 10 elements, improve the command line interface to allow to send parameters to each command or global...
[ "def", "_sort_and_trim", "(", "data", ",", "reverse", "=", "False", ")", ":", "threshold", "=", "10", "data_list", "=", "data", ".", "items", "(", ")", "data_list", "=", "sorted", "(", "data_list", ",", "key", "=", "lambda", "data_info", ":", "data_info"...
Sorts a dictionary with at least two fields on each of them sorting by the second element. .. warning:: Right now is hardcoded to 10 elements, improve the command line interface to allow to send parameters to each command or globally.
[ "Sorts", "a", "dictionary", "with", "at", "least", "two", "fields", "on", "each", "of", "them", "sorting", "by", "the", "second", "element", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/logfile.py#L422-L437
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
db_access_point
def db_access_point(func): """ Wraps a function that actually accesses the database. It injects a session into the method and attempts to handle it after the function has run. :param method func: The method that is interacting with the database. """ @wraps(func) def wrapper(self, *args,...
python
def db_access_point(func): """ Wraps a function that actually accesses the database. It injects a session into the method and attempts to handle it after the function has run. :param method func: The method that is interacting with the database. """ @wraps(func) def wrapper(self, *args,...
[ "def", "db_access_point", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Wrapper responsible for handling\n sessions\n \"\"\"", "session", "=...
Wraps a function that actually accesses the database. It injects a session into the method and attempts to handle it after the function has run. :param method func: The method that is interacting with the database.
[ "Wraps", "a", "function", "that", "actually", "accesses", "the", "database", ".", "It", "injects", "a", "session", "into", "the", "method", "and", "attempts", "to", "handle", "it", "after", "the", "function", "has", "run", "." ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L42-L65
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager._get_field_python_type
def _get_field_python_type(model, name): """ Gets the python type for the attribute on the model with the name provided. :param Model model: The SqlAlchemy model class. :param unicode name: The column name on the model that you are attempting to get the python type. ...
python
def _get_field_python_type(model, name): """ Gets the python type for the attribute on the model with the name provided. :param Model model: The SqlAlchemy model class. :param unicode name: The column name on the model that you are attempting to get the python type. ...
[ "def", "_get_field_python_type", "(", "model", ",", "name", ")", ":", "try", ":", "return", "getattr", "(", "model", ",", "name", ")", ".", "property", ".", "columns", "[", "0", "]", ".", "type", ".", "python_type", "except", "AttributeError", ":", "# It...
Gets the python type for the attribute on the model with the name provided. :param Model model: The SqlAlchemy model class. :param unicode name: The column name on the model that you are attempting to get the python type. :return: The python type of the column :rtype...
[ "Gets", "the", "python", "type", "for", "the", "attribute", "on", "the", "model", "with", "the", "name", "provided", "." ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L90-L109
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.get_field_type
def get_field_type(cls, name): """ Takes a field name and gets an appropriate BaseField instance for that column. It inspects the Model that is set on the manager to determine what the BaseField subclass should be. :param unicode name: :return: A BaseField subclass that...
python
def get_field_type(cls, name): """ Takes a field name and gets an appropriate BaseField instance for that column. It inspects the Model that is set on the manager to determine what the BaseField subclass should be. :param unicode name: :return: A BaseField subclass that...
[ "def", "get_field_type", "(", "cls", ",", "name", ")", ":", "python_type", "=", "cls", ".", "_get_field_python_type", "(", "cls", ".", "model", ",", "name", ")", "if", "python_type", "in", "_COLUMN_FIELD_MAP", ":", "field_class", "=", "_COLUMN_FIELD_MAP", "[",...
Takes a field name and gets an appropriate BaseField instance for that column. It inspects the Model that is set on the manager to determine what the BaseField subclass should be. :param unicode name: :return: A BaseField subclass that is appropriate for translating a strin...
[ "Takes", "a", "field", "name", "and", "gets", "an", "appropriate", "BaseField", "instance", "for", "that", "column", ".", "It", "inspects", "the", "Model", "that", "is", "set", "on", "the", "manager", "to", "determine", "what", "the", "BaseField", "subclass"...
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L112-L127
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.create
def create(self, session, values, *args, **kwargs): """ Creates a new instance of the self.model and persists it to the database. :param dict values: The dictionary of values to set on the model. The key is the column name and the value is what it will be set to...
python
def create(self, session, values, *args, **kwargs): """ Creates a new instance of the self.model and persists it to the database. :param dict values: The dictionary of values to set on the model. The key is the column name and the value is what it will be set to...
[ "def", "create", "(", "self", ",", "session", ",", "values", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "model", "=", "self", ".", "model", "(", ")", "model", "=", "self", ".", "_set_values_on_model", "(", "model", ",", "values", ",", "fi...
Creates a new instance of the self.model and persists it to the database. :param dict values: The dictionary of values to set on the model. The key is the column name and the value is what it will be set to. If the cls._create_fields is defined then it will ...
[ "Creates", "a", "new", "instance", "of", "the", "self", ".", "model", "and", "persists", "it", "to", "the", "database", "." ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L130-L150
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.retrieve
def retrieve(self, session, lookup_keys, *args, **kwargs): """ Retrieves a model using the lookup keys provided. Only one model should be returned by the lookup_keys or else the manager will fail. :param Session session: The SQLAlchemy session to use :param dict lookup_k...
python
def retrieve(self, session, lookup_keys, *args, **kwargs): """ Retrieves a model using the lookup keys provided. Only one model should be returned by the lookup_keys or else the manager will fail. :param Session session: The SQLAlchemy session to use :param dict lookup_k...
[ "def", "retrieve", "(", "self", ",", "session", ",", "lookup_keys", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "model", "=", "self", ".", "_get_model", "(", "lookup_keys", ",", "session", ")", "return", "self", ".", "serialize_model", "(", "m...
Retrieves a model using the lookup keys provided. Only one model should be returned by the lookup_keys or else the manager will fail. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values ...
[ "Retrieves", "a", "model", "using", "the", "lookup", "keys", "provided", ".", "Only", "one", "model", "should", "be", "returned", "by", "the", "lookup_keys", "or", "else", "the", "manager", "will", "fail", "." ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L153-L169
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.retrieve_list
def retrieve_list(self, session, filters, *args, **kwargs): """ Retrieves a list of the model for this manager. It is restricted by the filters provided. :param Session session: The SQLAlchemy session to use :param dict filters: The filters to restrict the returned m...
python
def retrieve_list(self, session, filters, *args, **kwargs): """ Retrieves a list of the model for this manager. It is restricted by the filters provided. :param Session session: The SQLAlchemy session to use :param dict filters: The filters to restrict the returned m...
[ "def", "retrieve_list", "(", "self", ",", "session", ",", "filters", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "queryset", "(", "session", ")", "translator", "=", "IntegerField", "(", "'tmp'", ")", "pagination_count"...
Retrieves a list of the model for this manager. It is restricted by the filters provided. :param Session session: The SQLAlchemy session to use :param dict filters: The filters to restrict the returned models on :return: A tuple of the list of dictionary representation ...
[ "Retrieves", "a", "list", "of", "the", "model", "for", "this", "manager", ".", "It", "is", "restricted", "by", "the", "filters", "provided", "." ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L172-L214
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.update
def update(self, session, lookup_keys, updates, *args, **kwargs): """ Updates the model with the specified lookup_keys and returns the dictified object. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and...
python
def update(self, session, lookup_keys, updates, *args, **kwargs): """ Updates the model with the specified lookup_keys and returns the dictified object. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and...
[ "def", "update", "(", "self", ",", "session", ",", "lookup_keys", ",", "updates", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "model", "=", "self", ".", "_get_model", "(", "lookup_keys", ",", "session", ")", "model", "=", "self", ".", "_set_...
Updates the model with the specified lookup_keys and returns the dictified object. :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :param dict updates: The columns and the values to upda...
[ "Updates", "the", "model", "with", "the", "specified", "lookup_keys", "and", "returns", "the", "dictified", "object", "." ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L217-L236
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.delete
def delete(self, session, lookup_keys, *args, **kwargs): """ Deletes the model found using the lookup_keys :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: An empty dicti...
python
def delete(self, session, lookup_keys, *args, **kwargs): """ Deletes the model found using the lookup_keys :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: An empty dicti...
[ "def", "delete", "(", "self", ",", "session", ",", "lookup_keys", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "model", "=", "self", ".", "_get_model", "(", "lookup_keys", ",", "session", ")", "session", ".", "delete", "(", "model", ")", "ses...
Deletes the model found using the lookup_keys :param Session session: The SQLAlchemy session to use :param dict lookup_keys: A dictionary mapping the fields and their expected values :return: An empty dictionary :rtype: dict :raises: NotFoundException
[ "Deletes", "the", "model", "found", "using", "the", "lookup_keys" ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L239-L253
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager.serialize_model
def serialize_model(self, model, field_dict=None): """ Takes a model and serializes the fields provided into a dictionary. :param Model model: The Sqlalchemy model instance to serialize :param dict field_dict: The dictionary of fields to return. :return: The serialized m...
python
def serialize_model(self, model, field_dict=None): """ Takes a model and serializes the fields provided into a dictionary. :param Model model: The Sqlalchemy model instance to serialize :param dict field_dict: The dictionary of fields to return. :return: The serialized m...
[ "def", "serialize_model", "(", "self", ",", "model", ",", "field_dict", "=", "None", ")", ":", "response", "=", "self", ".", "_serialize_model_helper", "(", "model", ",", "field_dict", "=", "field_dict", ")", "return", "make_json_safe", "(", "response", ")" ]
Takes a model and serializes the fields provided into a dictionary. :param Model model: The Sqlalchemy model instance to serialize :param dict field_dict: The dictionary of fields to return. :return: The serialized model. :rtype: dict
[ "Takes", "a", "model", "and", "serializes", "the", "fields", "provided", "into", "a", "dictionary", "." ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L264-L275
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager._serialize_model_helper
def _serialize_model_helper(self, model, field_dict=None): """ A recursive function for serializing a model into a json ready format. """ field_dict = field_dict or self.dot_field_list_to_dict() if model is None: return None if isinstance(model, Query...
python
def _serialize_model_helper(self, model, field_dict=None): """ A recursive function for serializing a model into a json ready format. """ field_dict = field_dict or self.dot_field_list_to_dict() if model is None: return None if isinstance(model, Query...
[ "def", "_serialize_model_helper", "(", "self", ",", "model", ",", "field_dict", "=", "None", ")", ":", "field_dict", "=", "field_dict", "or", "self", ".", "dot_field_list_to_dict", "(", ")", "if", "model", "is", "None", ":", "return", "None", "if", "isinstan...
A recursive function for serializing a model into a json ready format.
[ "A", "recursive", "function", "for", "serializing", "a", "model", "into", "a", "json", "ready", "format", "." ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L277-L298
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager._get_model
def _get_model(self, lookup_keys, session): """ Gets the sqlalchemy Model instance associated with the lookup keys. :param dict lookup_keys: A dictionary of the keys and their associated values. :param Session session: The sqlalchemy session :return: The sqla...
python
def _get_model(self, lookup_keys, session): """ Gets the sqlalchemy Model instance associated with the lookup keys. :param dict lookup_keys: A dictionary of the keys and their associated values. :param Session session: The sqlalchemy session :return: The sqla...
[ "def", "_get_model", "(", "self", ",", "lookup_keys", ",", "session", ")", ":", "try", ":", "return", "self", ".", "queryset", "(", "session", ")", ".", "filter_by", "(", "*", "*", "lookup_keys", ")", ".", "one", "(", ")", "except", "NoResultFound", ":...
Gets the sqlalchemy Model instance associated with the lookup keys. :param dict lookup_keys: A dictionary of the keys and their associated values. :param Session session: The sqlalchemy session :return: The sqlalchemy orm model instance.
[ "Gets", "the", "sqlalchemy", "Model", "instance", "associated", "with", "the", "lookup", "keys", "." ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L300-L314
vertical-knowledge/ripozo-sqlalchemy
ripozo_sqlalchemy/alchemymanager.py
AlchemyManager._set_values_on_model
def _set_values_on_model(self, model, values, fields=None): """ Updates the values with the specified values. :param Model model: The sqlalchemy model instance :param dict values: The dictionary of attributes and the values to set. :param list fields: A list of strin...
python
def _set_values_on_model(self, model, values, fields=None): """ Updates the values with the specified values. :param Model model: The sqlalchemy model instance :param dict values: The dictionary of attributes and the values to set. :param list fields: A list of strin...
[ "def", "_set_values_on_model", "(", "self", ",", "model", ",", "values", ",", "fields", "=", "None", ")", ":", "fields", "=", "fields", "or", "self", ".", "fields", "for", "name", ",", "val", "in", "six", ".", "iteritems", "(", "values", ")", ":", "i...
Updates the values with the specified values. :param Model model: The sqlalchemy model instance :param dict values: The dictionary of attributes and the values to set. :param list fields: A list of strings indicating the valid fields. Defaults to self.fields. :re...
[ "Updates", "the", "values", "with", "the", "specified", "values", "." ]
train
https://github.com/vertical-knowledge/ripozo-sqlalchemy/blob/4bcc57ec6db1b39b84b50553bb264e4950ce4ec2/ripozo_sqlalchemy/alchemymanager.py#L316-L333
gforcada/haproxy_log_analysis
haproxy/main.py
print_commands
def print_commands(): """Prints all commands available from Log with their description. """ dummy_log_file = Log() commands = Log.commands() commands.sort() for cmd in commands: cmd = getattr(dummy_log_file, 'cmd_{0}'.format(cmd)) description = cmd.__doc__ if descrip...
python
def print_commands(): """Prints all commands available from Log with their description. """ dummy_log_file = Log() commands = Log.commands() commands.sort() for cmd in commands: cmd = getattr(dummy_log_file, 'cmd_{0}'.format(cmd)) description = cmd.__doc__ if descrip...
[ "def", "print_commands", "(", ")", ":", "dummy_log_file", "=", "Log", "(", ")", "commands", "=", "Log", ".", "commands", "(", ")", "commands", ".", "sort", "(", ")", "for", "cmd", "in", "commands", ":", "cmd", "=", "getattr", "(", "dummy_log_file", ","...
Prints all commands available from Log with their description.
[ "Prints", "all", "commands", "available", "from", "Log", "with", "their", "description", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/main.py#L191-L206
gforcada/haproxy_log_analysis
haproxy/main.py
print_filters
def print_filters(): """Prints all filters available with their description.""" for filter_name in VALID_FILTERS: filter_func = getattr(filters, 'filter_{0}'.format(filter_name)) description = filter_func.__doc__ if description: description = re.sub(r'\n\s+', ' ', description...
python
def print_filters(): """Prints all filters available with their description.""" for filter_name in VALID_FILTERS: filter_func = getattr(filters, 'filter_{0}'.format(filter_name)) description = filter_func.__doc__ if description: description = re.sub(r'\n\s+', ' ', description...
[ "def", "print_filters", "(", ")", ":", "for", "filter_name", "in", "VALID_FILTERS", ":", "filter_func", "=", "getattr", "(", "filters", ",", "'filter_{0}'", ".", "format", "(", "filter_name", ")", ")", "description", "=", "filter_func", ".", "__doc__", "if", ...
Prints all filters available with their description.
[ "Prints", "all", "filters", "available", "with", "their", "description", "." ]
train
https://github.com/gforcada/haproxy_log_analysis/blob/a899895359bd4df6f35e279ad75c32c5afcfe916/haproxy/main.py#L209-L218