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 |
|---|---|---|---|---|---|---|---|---|---|---|
50onRed/smr | smr/shared.py | add_str | def add_str(window, line_num, str):
""" attempt to draw str on screen and ignore errors if they occur """
try:
window.addstr(line_num, 0, str)
except curses.error:
pass | python | def add_str(window, line_num, str):
""" attempt to draw str on screen and ignore errors if they occur """
try:
window.addstr(line_num, 0, str)
except curses.error:
pass | [
"def",
"add_str",
"(",
"window",
",",
"line_num",
",",
"str",
")",
":",
"try",
":",
"window",
".",
"addstr",
"(",
"line_num",
",",
"0",
",",
"str",
")",
"except",
"curses",
".",
"error",
":",
"pass"
] | attempt to draw str on screen and ignore errors if they occur | [
"attempt",
"to",
"draw",
"str",
"on",
"screen",
"and",
"ignore",
"errors",
"if",
"they",
"occur"
] | train | https://github.com/50onRed/smr/blob/999b33d86b6a900d7c4aadf03cf4a661acba9f1b/smr/shared.py#L39-L44 |
50onRed/smr | smr/shared.py | write_file_to_descriptor | def write_file_to_descriptor(input_queue, descriptor):
"""
get item from input_queue and write it to descriptor
returns True if and only if it was successfully written
"""
try:
file_name = input_queue.get(timeout=2)
descriptor.write("{}\n".format(file_name))
descriptor.flush(... | python | def write_file_to_descriptor(input_queue, descriptor):
"""
get item from input_queue and write it to descriptor
returns True if and only if it was successfully written
"""
try:
file_name = input_queue.get(timeout=2)
descriptor.write("{}\n".format(file_name))
descriptor.flush(... | [
"def",
"write_file_to_descriptor",
"(",
"input_queue",
",",
"descriptor",
")",
":",
"try",
":",
"file_name",
"=",
"input_queue",
".",
"get",
"(",
"timeout",
"=",
"2",
")",
"descriptor",
".",
"write",
"(",
"\"{}\\n\"",
".",
"format",
"(",
"file_name",
")",
... | get item from input_queue and write it to descriptor
returns True if and only if it was successfully written | [
"get",
"item",
"from",
"input_queue",
"and",
"write",
"it",
"to",
"descriptor",
"returns",
"True",
"if",
"and",
"only",
"if",
"it",
"was",
"successfully",
"written"
] | train | https://github.com/50onRed/smr/blob/999b33d86b6a900d7c4aadf03cf4a661acba9f1b/smr/shared.py#L63-L79 |
jeffrimko/Auxly | lib/auxly/listy.py | smooth | def smooth(l):
"""Yields a generator which smooths all elements as if the given list
was of depth 1.
**Examples**:
::
list(auxly.listy.smooth([1,[2,[3,[4]]]]))
# [1, 2, 3, 4]
"""
if type(l) in [list, tuple]:
for i in l:
for j in smooth(i):
yie... | python | def smooth(l):
"""Yields a generator which smooths all elements as if the given list
was of depth 1.
**Examples**:
::
list(auxly.listy.smooth([1,[2,[3,[4]]]]))
# [1, 2, 3, 4]
"""
if type(l) in [list, tuple]:
for i in l:
for j in smooth(i):
yie... | [
"def",
"smooth",
"(",
"l",
")",
":",
"if",
"type",
"(",
"l",
")",
"in",
"[",
"list",
",",
"tuple",
"]",
":",
"for",
"i",
"in",
"l",
":",
"for",
"j",
"in",
"smooth",
"(",
"i",
")",
":",
"yield",
"j",
"else",
":",
"yield",
"l"
] | Yields a generator which smooths all elements as if the given list
was of depth 1.
**Examples**:
::
list(auxly.listy.smooth([1,[2,[3,[4]]]]))
# [1, 2, 3, 4] | [
"Yields",
"a",
"generator",
"which",
"smooths",
"all",
"elements",
"as",
"if",
"the",
"given",
"list",
"was",
"of",
"depth",
"1",
"."
] | train | https://github.com/jeffrimko/Auxly/blob/5aae876bcb6ca117c81d904f9455764cdc78cd48/lib/auxly/listy.py#L21-L35 |
jordanncg/Bison | bison/cli.py | main | def main():
"""A"""
parser = argparse.ArgumentParser(description='A site preprocessor based \
on Jinja2, a templating engine for Python')
subparsers = parser.add_subparsers(description='The following options \
are available:')
# 'create' command
parser_create = subparsers.add_parser... | python | def main():
"""A"""
parser = argparse.ArgumentParser(description='A site preprocessor based \
on Jinja2, a templating engine for Python')
subparsers = parser.add_subparsers(description='The following options \
are available:')
# 'create' command
parser_create = subparsers.add_parser... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'A site preprocessor based \\\n on Jinja2, a templating engine for Python'",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"description",
"=",
... | A | [
"A"
] | train | https://github.com/jordanncg/Bison/blob/c7f04fd67d141fe26cd29db3c3fb3fc0fd0c45df/bison/cli.py#L31-L50 |
CivicSpleen/ckcache | ckcache/s3.py | S3Cache.s3path | def s3path(self, rel_path):
"""Return the path as an S3 schema"""
import urlparse
path = self.path(rel_path, public_url=True)
parts = list(urlparse.urlparse(path))
parts[0] = 's3'
parts[1] = self.bucket_name
return urlparse.urlunparse(parts) | python | def s3path(self, rel_path):
"""Return the path as an S3 schema"""
import urlparse
path = self.path(rel_path, public_url=True)
parts = list(urlparse.urlparse(path))
parts[0] = 's3'
parts[1] = self.bucket_name
return urlparse.urlunparse(parts) | [
"def",
"s3path",
"(",
"self",
",",
"rel_path",
")",
":",
"import",
"urlparse",
"path",
"=",
"self",
".",
"path",
"(",
"rel_path",
",",
"public_url",
"=",
"True",
")",
"parts",
"=",
"list",
"(",
"urlparse",
".",
"urlparse",
"(",
"path",
")",
")",
"par... | Return the path as an S3 schema | [
"Return",
"the",
"path",
"as",
"an",
"S3",
"schema"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/s3.py#L153-L164 |
CivicSpleen/ckcache | ckcache/s3.py | S3Cache.get_stream | def get_stream(self, rel_path, cb=None, return_meta=False):
"""Return the object as a stream"""
from boto.s3.key import Key
from boto.exception import S3ResponseError
import StringIO
from . import MetadataFlo
b = StringIO.StringIO()
try:
k = self._ge... | python | def get_stream(self, rel_path, cb=None, return_meta=False):
"""Return the object as a stream"""
from boto.s3.key import Key
from boto.exception import S3ResponseError
import StringIO
from . import MetadataFlo
b = StringIO.StringIO()
try:
k = self._ge... | [
"def",
"get_stream",
"(",
"self",
",",
"rel_path",
",",
"cb",
"=",
"None",
",",
"return_meta",
"=",
"False",
")",
":",
"from",
"boto",
".",
"s3",
".",
"key",
"import",
"Key",
"from",
"boto",
".",
"exception",
"import",
"S3ResponseError",
"import",
"Strin... | Return the object as a stream | [
"Return",
"the",
"object",
"as",
"a",
"stream"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/s3.py#L187-L218 |
CivicSpleen/ckcache | ckcache/s3.py | S3Cache.put_key | def put_key(self, source, rel_path):
'''Copy a file to the repository
Args:
source: Absolute path to the source file, or a file-like object
rel_path: path relative to the root of the repository
'''
k = self._get_boto_key(rel_path)
try:
k.set... | python | def put_key(self, source, rel_path):
'''Copy a file to the repository
Args:
source: Absolute path to the source file, or a file-like object
rel_path: path relative to the root of the repository
'''
k = self._get_boto_key(rel_path)
try:
k.set... | [
"def",
"put_key",
"(",
"self",
",",
"source",
",",
"rel_path",
")",
":",
"k",
"=",
"self",
".",
"_get_boto_key",
"(",
"rel_path",
")",
"try",
":",
"k",
".",
"set_contents_from_file",
"(",
"source",
")",
"except",
"AttributeError",
":",
"if",
"os",
".",
... | Copy a file to the repository
Args:
source: Absolute path to the source file, or a file-like object
rel_path: path relative to the root of the repository | [
"Copy",
"a",
"file",
"to",
"the",
"repository"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/s3.py#L246-L263 |
CivicSpleen/ckcache | ckcache/s3.py | S3Cache.put_stream | def put_stream(self, rel_path, metadata=None, cb=None):
'''Return a Flo object that can be written to to send data to S3.
This will result in a multi-part upload, possibly with each part
being sent in its own thread '''
import Queue
import time
import threading
... | python | def put_stream(self, rel_path, metadata=None, cb=None):
'''Return a Flo object that can be written to to send data to S3.
This will result in a multi-part upload, possibly with each part
being sent in its own thread '''
import Queue
import time
import threading
... | [
"def",
"put_stream",
"(",
"self",
",",
"rel_path",
",",
"metadata",
"=",
"None",
",",
"cb",
"=",
"None",
")",
":",
"import",
"Queue",
"import",
"time",
"import",
"threading",
"md5",
"=",
"metadata",
".",
"get",
"(",
"'md5'",
",",
"None",
")",
"if",
"... | Return a Flo object that can be written to to send data to S3.
This will result in a multi-part upload, possibly with each part
being sent in its own thread | [
"Return",
"a",
"Flo",
"object",
"that",
"can",
"be",
"written",
"to",
"to",
"send",
"data",
"to",
"S3",
".",
"This",
"will",
"result",
"in",
"a",
"multi",
"-",
"part",
"upload",
"possibly",
"with",
"each",
"part",
"being",
"sent",
"in",
"its",
"own",
... | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/s3.py#L265-L416 |
CivicSpleen/ckcache | ckcache/s3.py | S3Cache.remove | def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
key = self._get_boto_key(rel_path)
if key:
key.delete() | python | def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
key = self._get_boto_key(rel_path)
if key:
key.delete() | [
"def",
"remove",
"(",
"self",
",",
"rel_path",
",",
"propagate",
"=",
"False",
")",
":",
"key",
"=",
"self",
".",
"_get_boto_key",
"(",
"rel_path",
")",
"if",
"key",
":",
"key",
".",
"delete",
"(",
")"
] | Delete the file from the cache, and from the upstream | [
"Delete",
"the",
"file",
"from",
"the",
"cache",
"and",
"from",
"the",
"upstream"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/s3.py#L423-L428 |
CivicSpleen/ckcache | ckcache/s3.py | S3Cache.clean | def clean(self):
'''Delete Everything'''
for e in self.bucket.list(self.prefix):
path = e.name.replace(self.prefix, '', 1).strip('/')
if path.startswith('_'):
continue
self.remove(path) | python | def clean(self):
'''Delete Everything'''
for e in self.bucket.list(self.prefix):
path = e.name.replace(self.prefix, '', 1).strip('/')
if path.startswith('_'):
continue
self.remove(path) | [
"def",
"clean",
"(",
"self",
")",
":",
"for",
"e",
"in",
"self",
".",
"bucket",
".",
"list",
"(",
"self",
".",
"prefix",
")",
":",
"path",
"=",
"e",
".",
"name",
".",
"replace",
"(",
"self",
".",
"prefix",
",",
"''",
",",
"1",
")",
".",
"stri... | Delete Everything | [
"Delete",
"Everything"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/s3.py#L430-L438 |
CivicSpleen/ckcache | ckcache/s3.py | S3Cache.list | def list(self, path=None, with_metadata=False, include_partitions=False):
'''Get a list of all of bundle files in the cache. Does not return partition files'''
import json
sub_path = self.prefix + '/' + path.strip('/') if path else self.prefix
l = {}
for e in self.bucket.list(... | python | def list(self, path=None, with_metadata=False, include_partitions=False):
'''Get a list of all of bundle files in the cache. Does not return partition files'''
import json
sub_path = self.prefix + '/' + path.strip('/') if path else self.prefix
l = {}
for e in self.bucket.list(... | [
"def",
"list",
"(",
"self",
",",
"path",
"=",
"None",
",",
"with_metadata",
"=",
"False",
",",
"include_partitions",
"=",
"False",
")",
":",
"import",
"json",
"sub_path",
"=",
"self",
".",
"prefix",
"+",
"'/'",
"+",
"path",
".",
"strip",
"(",
"'/'",
... | Get a list of all of bundle files in the cache. Does not return partition files | [
"Get",
"a",
"list",
"of",
"all",
"of",
"bundle",
"files",
"in",
"the",
"cache",
".",
"Does",
"not",
"return",
"partition",
"files"
] | train | https://github.com/CivicSpleen/ckcache/blob/0c699b6ba97ff164e9702504f0e1643dd4cd39e1/ckcache/s3.py#L440-L470 |
klmitch/tendril | tendril/connection.py | Tendril._send_streamify | def _send_streamify(self, frame):
"""
Helper method to streamify a frame.
"""
# Get the state and framer
state = self._send_framer_state
framer = self._send_framer
# Reset the state as needed
state._reset(framer)
# Now pass the frame through str... | python | def _send_streamify(self, frame):
"""
Helper method to streamify a frame.
"""
# Get the state and framer
state = self._send_framer_state
framer = self._send_framer
# Reset the state as needed
state._reset(framer)
# Now pass the frame through str... | [
"def",
"_send_streamify",
"(",
"self",
",",
"frame",
")",
":",
"# Get the state and framer",
"state",
"=",
"self",
".",
"_send_framer_state",
"framer",
"=",
"self",
".",
"_send_framer",
"# Reset the state as needed",
"state",
".",
"_reset",
"(",
"framer",
")",
"# ... | Helper method to streamify a frame. | [
"Helper",
"method",
"to",
"streamify",
"a",
"frame",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/connection.py#L102-L115 |
klmitch/tendril | tendril/connection.py | Tendril._recv_frameify | def _recv_frameify(self, data):
"""
Helper method to frameify a stream.
"""
# Get the state and framer
state = self._recv_framer_state
framer = None
# Grab off as many frames as we can
frameify = None
while True:
# Check if we need to... | python | def _recv_frameify(self, data):
"""
Helper method to frameify a stream.
"""
# Get the state and framer
state = self._recv_framer_state
framer = None
# Grab off as many frames as we can
frameify = None
while True:
# Check if we need to... | [
"def",
"_recv_frameify",
"(",
"self",
",",
"data",
")",
":",
"# Get the state and framer",
"state",
"=",
"self",
".",
"_recv_framer_state",
"framer",
"=",
"None",
"# Grab off as many frames as we can",
"frameify",
"=",
"None",
"while",
"True",
":",
"# Check if we need... | Helper method to frameify a stream. | [
"Helper",
"method",
"to",
"frameify",
"a",
"stream",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/connection.py#L117-L153 |
klmitch/tendril | tendril/connection.py | Tendril.closed | def closed(self, error=None):
"""
Notify the application that the connection has been closed.
:param error: The exception which has caused the connection to
be closed. If the connection has been closed
due to an EOF, pass ``None``.
"""
... | python | def closed(self, error=None):
"""
Notify the application that the connection has been closed.
:param error: The exception which has caused the connection to
be closed. If the connection has been closed
due to an EOF, pass ``None``.
"""
... | [
"def",
"closed",
"(",
"self",
",",
"error",
"=",
"None",
")",
":",
"if",
"self",
".",
"_application",
":",
"try",
":",
"self",
".",
"_application",
".",
"closed",
"(",
"error",
")",
"except",
"Exception",
":",
"# Ignore exceptions from the notification",
"pa... | Notify the application that the connection has been closed.
:param error: The exception which has caused the connection to
be closed. If the connection has been closed
due to an EOF, pass ``None``. | [
"Notify",
"the",
"application",
"that",
"the",
"connection",
"has",
"been",
"closed",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/connection.py#L169-L183 |
klmitch/tendril | tendril/connection.py | Tendril.send_framer | def send_framer(self, value):
"""
Set the framer in use for the sending side of the connection.
The framer state will be reset next time the framer is used.
"""
if not isinstance(value, framers.Framer):
raise ValueError("framer must be an instance of tendril.Framer")... | python | def send_framer(self, value):
"""
Set the framer in use for the sending side of the connection.
The framer state will be reset next time the framer is used.
"""
if not isinstance(value, framers.Framer):
raise ValueError("framer must be an instance of tendril.Framer")... | [
"def",
"send_framer",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"framers",
".",
"Framer",
")",
":",
"raise",
"ValueError",
"(",
"\"framer must be an instance of tendril.Framer\"",
")",
"self",
".",
"_send_framer",
"=",
... | Set the framer in use for the sending side of the connection.
The framer state will be reset next time the framer is used. | [
"Set",
"the",
"framer",
"in",
"use",
"for",
"the",
"sending",
"side",
"of",
"the",
"connection",
".",
"The",
"framer",
"state",
"will",
"be",
"reset",
"next",
"time",
"the",
"framer",
"is",
"used",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/connection.py#L203-L212 |
klmitch/tendril | tendril/connection.py | Tendril.recv_framer | def recv_framer(self, value):
"""
Set the framer in use for the receiving side of the
connection. The framer state will be reset next time the
framer is used.
"""
if not isinstance(value, framers.Framer):
raise ValueError("framer must be an instance of tendr... | python | def recv_framer(self, value):
"""
Set the framer in use for the receiving side of the
connection. The framer state will be reset next time the
framer is used.
"""
if not isinstance(value, framers.Framer):
raise ValueError("framer must be an instance of tendr... | [
"def",
"recv_framer",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"framers",
".",
"Framer",
")",
":",
"raise",
"ValueError",
"(",
"\"framer must be an instance of tendril.Framer\"",
")",
"self",
".",
"_recv_framer",
"=",
... | Set the framer in use for the receiving side of the
connection. The framer state will be reset next time the
framer is used. | [
"Set",
"the",
"framer",
"in",
"use",
"for",
"the",
"receiving",
"side",
"of",
"the",
"connection",
".",
"The",
"framer",
"state",
"will",
"be",
"reset",
"next",
"time",
"the",
"framer",
"is",
"used",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/connection.py#L243-L253 |
klmitch/tendril | tendril/connection.py | Tendril.framers | def framers(self, value):
"""
Set the framers in use for the connection. The framer states
will be reset next time their respective framer is used.
"""
# Handle sequence values
if isinstance(value, collections.Sequence):
if len(value) != 2:
r... | python | def framers(self, value):
"""
Set the framers in use for the connection. The framer states
will be reset next time their respective framer is used.
"""
# Handle sequence values
if isinstance(value, collections.Sequence):
if len(value) != 2:
r... | [
"def",
"framers",
"(",
"self",
",",
"value",
")",
":",
"# Handle sequence values",
"if",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Sequence",
")",
":",
"if",
"len",
"(",
"value",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"'need exactly 2... | Set the framers in use for the connection. The framer states
will be reset next time their respective framer is used. | [
"Set",
"the",
"framers",
"in",
"use",
"for",
"the",
"connection",
".",
"The",
"framer",
"states",
"will",
"be",
"reset",
"next",
"time",
"their",
"respective",
"framer",
"is",
"used",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/connection.py#L283-L307 |
klmitch/tendril | tendril/connection.py | Tendril.framers | def framers(self):
"""
Reset the framers in use for the connection to be a
tendril.IdentityFramer. The framer states will be reset next
time their respective framer is used.
"""
f = self.default_framer()
self._send_framer = f
self._recv_framer = f | python | def framers(self):
"""
Reset the framers in use for the connection to be a
tendril.IdentityFramer. The framer states will be reset next
time their respective framer is used.
"""
f = self.default_framer()
self._send_framer = f
self._recv_framer = f | [
"def",
"framers",
"(",
"self",
")",
":",
"f",
"=",
"self",
".",
"default_framer",
"(",
")",
"self",
".",
"_send_framer",
"=",
"f",
"self",
".",
"_recv_framer",
"=",
"f"
] | Reset the framers in use for the connection to be a
tendril.IdentityFramer. The framer states will be reset next
time their respective framer is used. | [
"Reset",
"the",
"framers",
"in",
"use",
"for",
"the",
"connection",
"to",
"be",
"a",
"tendril",
".",
"IdentityFramer",
".",
"The",
"framer",
"states",
"will",
"be",
"reset",
"next",
"time",
"their",
"respective",
"framer",
"is",
"used",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/connection.py#L310-L319 |
klmitch/tendril | tendril/connection.py | Tendril.application | def application(self, value):
"""Update the application."""
# Always allow None
if value is None:
self._application = None
return
# Check that the state is valid
if not isinstance(value, application.Application):
raise ValueError("application... | python | def application(self, value):
"""Update the application."""
# Always allow None
if value is None:
self._application = None
return
# Check that the state is valid
if not isinstance(value, application.Application):
raise ValueError("application... | [
"def",
"application",
"(",
"self",
",",
"value",
")",
":",
"# Always allow None",
"if",
"value",
"is",
"None",
":",
"self",
".",
"_application",
"=",
"None",
"return",
"# Check that the state is valid",
"if",
"not",
"isinstance",
"(",
"value",
",",
"application"... | Update the application. | [
"Update",
"the",
"application",
"."
] | train | https://github.com/klmitch/tendril/blob/207102c83e88f8f1fa7ba605ef0aab2ae9078b36/tendril/connection.py#L337-L350 |
pop/pageup | pageup/pageup.py | build | def build():
"""
Builds pages given template.jinja, style.css, and content.rst
produces index.html.
"""
test_files()
with open('content.rst') as f:
content = publish_parts(f.read(), writer_name='html')
title = content['title']
body = content['html_body'].replace('\n',' '... | python | def build():
"""
Builds pages given template.jinja, style.css, and content.rst
produces index.html.
"""
test_files()
with open('content.rst') as f:
content = publish_parts(f.read(), writer_name='html')
title = content['title']
body = content['html_body'].replace('\n',' '... | [
"def",
"build",
"(",
")",
":",
"test_files",
"(",
")",
"with",
"open",
"(",
"'content.rst'",
")",
"as",
"f",
":",
"content",
"=",
"publish_parts",
"(",
"f",
".",
"read",
"(",
")",
",",
"writer_name",
"=",
"'html'",
")",
"title",
"=",
"content",
"[",
... | Builds pages given template.jinja, style.css, and content.rst
produces index.html. | [
"Builds",
"pages",
"given",
"template",
".",
"jinja",
"style",
".",
"css",
"and",
"content",
".",
"rst",
"produces",
"index",
".",
"html",
"."
] | train | https://github.com/pop/pageup/blob/e78471d50517e1779e6e2a5ea961f2a2def7e5e8/pageup/pageup.py#L34-L53 |
pop/pageup | pageup/pageup.py | init | def init(directory=None):
"""
Initializes a new site in the `directory`
Current working dir if directory is None.
"""
if directory is not None and not path.exists(directory):
makedirs(directory)
else:
print('%s already exists, populating with template files' % (directory))
... | python | def init(directory=None):
"""
Initializes a new site in the `directory`
Current working dir if directory is None.
"""
if directory is not None and not path.exists(directory):
makedirs(directory)
else:
print('%s already exists, populating with template files' % (directory))
... | [
"def",
"init",
"(",
"directory",
"=",
"None",
")",
":",
"if",
"directory",
"is",
"not",
"None",
"and",
"not",
"path",
".",
"exists",
"(",
"directory",
")",
":",
"makedirs",
"(",
"directory",
")",
"else",
":",
"print",
"(",
"'%s already exists, populating w... | Initializes a new site in the `directory`
Current working dir if directory is None. | [
"Initializes",
"a",
"new",
"site",
"in",
"the",
"directory",
"Current",
"working",
"dir",
"if",
"directory",
"is",
"None",
"."
] | train | https://github.com/pop/pageup/blob/e78471d50517e1779e6e2a5ea961f2a2def7e5e8/pageup/pageup.py#L56-L75 |
pop/pageup | pageup/pageup.py | grab | def grab(filename, directory):
"""
Copy dist files from their installed path to cwd/directory/filename
cwd is the current directory,
directory is their custom site name dir,
filename is the name of the example file being copied over.
"""
r = requests.get('https://raw.githubusercontent.com/El... | python | def grab(filename, directory):
"""
Copy dist files from their installed path to cwd/directory/filename
cwd is the current directory,
directory is their custom site name dir,
filename is the name of the example file being copied over.
"""
r = requests.get('https://raw.githubusercontent.com/El... | [
"def",
"grab",
"(",
"filename",
",",
"directory",
")",
":",
"r",
"=",
"requests",
".",
"get",
"(",
"'https://raw.githubusercontent.com/ElijahCaine/pageup/master/pageup/data/'",
"+",
"filename",
")",
"with",
"open",
"(",
"path",
".",
"join",
"(",
"directory",
",",
... | Copy dist files from their installed path to cwd/directory/filename
cwd is the current directory,
directory is their custom site name dir,
filename is the name of the example file being copied over. | [
"Copy",
"dist",
"files",
"from",
"their",
"installed",
"path",
"to",
"cwd",
"/",
"directory",
"/",
"filename",
"cwd",
"is",
"the",
"current",
"directory",
"directory",
"is",
"their",
"custom",
"site",
"name",
"dir",
"filename",
"is",
"the",
"name",
"of",
"... | train | https://github.com/pop/pageup/blob/e78471d50517e1779e6e2a5ea961f2a2def7e5e8/pageup/pageup.py#L77-L86 |
defnull/contexter | contexter.py | ExitStack.callback | def callback(self, callback, *args, **kwds):
""" Registers an arbitrary callback and arguments.
Cannot suppress exceptions.
"""
return self << _CloseDummy(callback, args, kwds) | python | def callback(self, callback, *args, **kwds):
""" Registers an arbitrary callback and arguments.
Cannot suppress exceptions.
"""
return self << _CloseDummy(callback, args, kwds) | [
"def",
"callback",
"(",
"self",
",",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
"<<",
"_CloseDummy",
"(",
"callback",
",",
"args",
",",
"kwds",
")"
] | Registers an arbitrary callback and arguments.
Cannot suppress exceptions. | [
"Registers",
"an",
"arbitrary",
"callback",
"and",
"arguments",
"."
] | train | https://github.com/defnull/contexter/blob/12113375bd748f40a8a26e59847dbe291b957c0d/contexter.py#L151-L156 |
defnull/contexter | contexter.py | ExitStack.pop_all | def pop_all(self):
""" Preserve the context stack by transferring it to a new instance """
ret = ExitStack()
ret._context_stack.append(self._context_stack.pop())
self._context_stack.append([]) | python | def pop_all(self):
""" Preserve the context stack by transferring it to a new instance """
ret = ExitStack()
ret._context_stack.append(self._context_stack.pop())
self._context_stack.append([]) | [
"def",
"pop_all",
"(",
"self",
")",
":",
"ret",
"=",
"ExitStack",
"(",
")",
"ret",
".",
"_context_stack",
".",
"append",
"(",
"self",
".",
"_context_stack",
".",
"pop",
"(",
")",
")",
"self",
".",
"_context_stack",
".",
"append",
"(",
"[",
"]",
")"
] | Preserve the context stack by transferring it to a new instance | [
"Preserve",
"the",
"context",
"stack",
"by",
"transferring",
"it",
"to",
"a",
"new",
"instance"
] | train | https://github.com/defnull/contexter/blob/12113375bd748f40a8a26e59847dbe291b957c0d/contexter.py#L158-L162 |
briancappello/flask-sqlalchemy-bundle | flask_sqlalchemy_bundle/base_model.py | BaseModel.update | def update(self, **kwargs):
"""Update fields on the model.
:param kwargs: The model attribute values to update the model with.
"""
self.validate(**kwargs)
for attr, value in kwargs.items():
setattr(self, attr, value)
return self | python | def update(self, **kwargs):
"""Update fields on the model.
:param kwargs: The model attribute values to update the model with.
"""
self.validate(**kwargs)
for attr, value in kwargs.items():
setattr(self, attr, value)
return self | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"validate",
"(",
"*",
"*",
"kwargs",
")",
"for",
"attr",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"attr",
",",
"value",
... | Update fields on the model.
:param kwargs: The model attribute values to update the model with. | [
"Update",
"fields",
"on",
"the",
"model",
"."
] | train | https://github.com/briancappello/flask-sqlalchemy-bundle/blob/8150896787907ef0001839b5a6ef303edccb9b6c/flask_sqlalchemy_bundle/base_model.py#L76-L84 |
briancappello/flask-sqlalchemy-bundle | flask_sqlalchemy_bundle/base_model.py | BaseModel.validate | def validate(cls, partial=True, **kwargs):
"""
Validate kwargs before setting attributes on the model
"""
data = kwargs
if not partial:
data = dict(**kwargs, **{col.name: None for col in cls.__table__.c
if col.name not in kwargs})
... | python | def validate(cls, partial=True, **kwargs):
"""
Validate kwargs before setting attributes on the model
"""
data = kwargs
if not partial:
data = dict(**kwargs, **{col.name: None for col in cls.__table__.c
if col.name not in kwargs})
... | [
"def",
"validate",
"(",
"cls",
",",
"partial",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"kwargs",
"if",
"not",
"partial",
":",
"data",
"=",
"dict",
"(",
"*",
"*",
"kwargs",
",",
"*",
"*",
"{",
"col",
".",
"name",
":",
"None"... | Validate kwargs before setting attributes on the model | [
"Validate",
"kwargs",
"before",
"setting",
"attributes",
"on",
"the",
"model"
] | train | https://github.com/briancappello/flask-sqlalchemy-bundle/blob/8150896787907ef0001839b5a6ef303edccb9b6c/flask_sqlalchemy_bundle/base_model.py#L87-L107 |
racker/torment | torment/fixtures/__init__.py | of | def of(fixture_classes: Iterable[type], context: Union[None, 'torment.TestContext'] = None) -> Iterable['torment.fixtures.Fixture']:
'''Obtain all Fixture objects of the provided classes.
**Parameters**
:``fixture_classes``: classes inheriting from ``torment.fixtures.Fixture``
:``context``: a ... | python | def of(fixture_classes: Iterable[type], context: Union[None, 'torment.TestContext'] = None) -> Iterable['torment.fixtures.Fixture']:
'''Obtain all Fixture objects of the provided classes.
**Parameters**
:``fixture_classes``: classes inheriting from ``torment.fixtures.Fixture``
:``context``: a ... | [
"def",
"of",
"(",
"fixture_classes",
":",
"Iterable",
"[",
"type",
"]",
",",
"context",
":",
"Union",
"[",
"None",
",",
"'torment.TestContext'",
"]",
"=",
"None",
")",
"->",
"Iterable",
"[",
"'torment.fixtures.Fixture'",
"]",
":",
"classes",
"=",
"list",
"... | Obtain all Fixture objects of the provided classes.
**Parameters**
:``fixture_classes``: classes inheriting from ``torment.fixtures.Fixture``
:``context``: a ``torment.TestContext`` to initialize Fixtures with
**Return Value(s)**
Instantiated ``torment.fixtures.Fixture`` objects for each... | [
"Obtain",
"all",
"Fixture",
"objects",
"of",
"the",
"provided",
"classes",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L293-L320 |
racker/torment | torment/fixtures/__init__.py | register | def register(namespace, base_classes: Tuple[type], properties: Dict[str, Any]) -> None:
'''Register a Fixture class in namespace with the given properties.
Creates a Fixture class (not object) and inserts it into the provided
namespace. The properties is a dict but allows functions to reference other
... | python | def register(namespace, base_classes: Tuple[type], properties: Dict[str, Any]) -> None:
'''Register a Fixture class in namespace with the given properties.
Creates a Fixture class (not object) and inserts it into the provided
namespace. The properties is a dict but allows functions to reference other
... | [
"def",
"register",
"(",
"namespace",
",",
"base_classes",
":",
"Tuple",
"[",
"type",
"]",
",",
"properties",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"# ensure we have a clean copy of the data",
"# and won't stomp on re-uses elsewhere in",
... | Register a Fixture class in namespace with the given properties.
Creates a Fixture class (not object) and inserts it into the provided
namespace. The properties is a dict but allows functions to reference other
properties and acts like a small DSL (domain specific language). This is
really just a dec... | [
"Register",
"a",
"Fixture",
"class",
"in",
"namespace",
"with",
"the",
"given",
"properties",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L323-L438 |
racker/torment | torment/fixtures/__init__.py | _prepare_mock | def _prepare_mock(context: 'torment.contexts.TestContext', symbol: str, return_value = None, side_effect = None) -> None:
'''Sets return value or side effect of symbol's mock in context.
.. seealso:: :py:func:`_find_mocker`
**Parameters**
:``context``: the search context
:``symbol``: ... | python | def _prepare_mock(context: 'torment.contexts.TestContext', symbol: str, return_value = None, side_effect = None) -> None:
'''Sets return value or side effect of symbol's mock in context.
.. seealso:: :py:func:`_find_mocker`
**Parameters**
:``context``: the search context
:``symbol``: ... | [
"def",
"_prepare_mock",
"(",
"context",
":",
"'torment.contexts.TestContext'",
",",
"symbol",
":",
"str",
",",
"return_value",
"=",
"None",
",",
"side_effect",
"=",
"None",
")",
"->",
"None",
":",
"methods",
"=",
"symbol",
".",
"split",
"(",
"'.'",
")",
"i... | Sets return value or side effect of symbol's mock in context.
.. seealso:: :py:func:`_find_mocker`
**Parameters**
:``context``: the search context
:``symbol``: the symbol to be located
:``return_value``: pass through to mock ``return_value``
:``side_effect``: pass through to m... | [
"Sets",
"return",
"value",
"or",
"side",
"effect",
"of",
"symbol",
"s",
"mock",
"in",
"context",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L441-L482 |
racker/torment | torment/fixtures/__init__.py | _find_mocker | def _find_mocker(symbol: str, context: 'torment.contexts.TestContext') -> Callable[[], bool]:
'''Find method within the context that mocks symbol.
Given a symbol (i.e. ``tornado.httpclient.AsyncHTTPClient.fetch``), find
the shortest ``mock_`` method that resembles the symbol. Resembles means
the lowerc... | python | def _find_mocker(symbol: str, context: 'torment.contexts.TestContext') -> Callable[[], bool]:
'''Find method within the context that mocks symbol.
Given a symbol (i.e. ``tornado.httpclient.AsyncHTTPClient.fetch``), find
the shortest ``mock_`` method that resembles the symbol. Resembles means
the lowerc... | [
"def",
"_find_mocker",
"(",
"symbol",
":",
"str",
",",
"context",
":",
"'torment.contexts.TestContext'",
")",
"->",
"Callable",
"[",
"[",
"]",
",",
"bool",
"]",
":",
"components",
"=",
"[",
"]",
"method",
"=",
"None",
"for",
"component",
"in",
"symbol",
... | Find method within the context that mocks symbol.
Given a symbol (i.e. ``tornado.httpclient.AsyncHTTPClient.fetch``), find
the shortest ``mock_`` method that resembles the symbol. Resembles means
the lowercased and periods replaced with underscores.
If no match is found, a dummy function (only returns... | [
"Find",
"method",
"within",
"the",
"context",
"that",
"mocks",
"symbol",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L485-L534 |
racker/torment | torment/fixtures/__init__.py | _resolve_functions | def _resolve_functions(functions: Dict[str, Callable[[Any], Any]], fixture: Fixture) -> None:
'''Apply functions and collect values as properties on fixture.
Call functions and apply their values as properteis on fixture.
Functions will continue to get applied until no more functions resolve.
All unres... | python | def _resolve_functions(functions: Dict[str, Callable[[Any], Any]], fixture: Fixture) -> None:
'''Apply functions and collect values as properties on fixture.
Call functions and apply their values as properteis on fixture.
Functions will continue to get applied until no more functions resolve.
All unres... | [
"def",
"_resolve_functions",
"(",
"functions",
":",
"Dict",
"[",
"str",
",",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
"]",
",",
"fixture",
":",
"Fixture",
")",
"->",
"None",
":",
"exc_info",
"=",
"last_function",
"=",
"None",
"function_count",
... | Apply functions and collect values as properties on fixture.
Call functions and apply their values as properteis on fixture.
Functions will continue to get applied until no more functions resolve.
All unresolved functions are logged and the last exception to have
occurred is also logged. This function... | [
"Apply",
"functions",
"and",
"collect",
"values",
"as",
"properties",
"on",
"fixture",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L537-L579 |
racker/torment | torment/fixtures/__init__.py | _unique_class_name | def _unique_class_name(namespace: Dict[str, Any], uuid: uuid.UUID) -> str:
'''Generate unique to namespace name for a class using uuid.
**Parameters**
:``namespace``: the namespace to verify uniqueness against
:``uuid``: the "unique" portion of the name
**Return Value(s)**
A unique stri... | python | def _unique_class_name(namespace: Dict[str, Any], uuid: uuid.UUID) -> str:
'''Generate unique to namespace name for a class using uuid.
**Parameters**
:``namespace``: the namespace to verify uniqueness against
:``uuid``: the "unique" portion of the name
**Return Value(s)**
A unique stri... | [
"def",
"_unique_class_name",
"(",
"namespace",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"uuid",
":",
"uuid",
".",
"UUID",
")",
"->",
"str",
":",
"count",
"=",
"0",
"name",
"=",
"original_name",
"=",
"'f_'",
"+",
"uuid",
".",
"hex",
"while",
"... | Generate unique to namespace name for a class using uuid.
**Parameters**
:``namespace``: the namespace to verify uniqueness against
:``uuid``: the "unique" portion of the name
**Return Value(s)**
A unique string (in namespace) using uuid. | [
"Generate",
"unique",
"to",
"namespace",
"name",
"for",
"a",
"class",
"using",
"uuid",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L582-L603 |
racker/torment | torment/fixtures/__init__.py | Fixture.category | def category(self) -> str:
'''Fixture's category (the containing testing module name)
**Examples**
:module: test_torment.test_unit.test_fixtures.fixture_a44bc6dda6654b1395a8c2cbd55d964d
:category: fixtures
'''
logger.debug('dir(self.__module__): %s', dir(self.__modu... | python | def category(self) -> str:
'''Fixture's category (the containing testing module name)
**Examples**
:module: test_torment.test_unit.test_fixtures.fixture_a44bc6dda6654b1395a8c2cbd55d964d
:category: fixtures
'''
logger.debug('dir(self.__module__): %s', dir(self.__modu... | [
"def",
"category",
"(",
"self",
")",
"->",
"str",
":",
"logger",
".",
"debug",
"(",
"'dir(self.__module__): %s'",
",",
"dir",
"(",
"self",
".",
"__module__",
")",
")",
"return",
"self",
".",
"__module__",
".",
"__name__",
".",
"rsplit",
"(",
"'.'",
",",
... | Fixture's category (the containing testing module name)
**Examples**
:module: test_torment.test_unit.test_fixtures.fixture_a44bc6dda6654b1395a8c2cbd55d964d
:category: fixtures | [
"Fixture",
"s",
"category",
"(",
"the",
"containing",
"testing",
"module",
"name",
")"
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L166-L178 |
racker/torment | torment/fixtures/__init__.py | Fixture.description | def description(self) -> str:
'''Test name in nose output (intended to be overridden).'''
return '{0.uuid.hex}—{1}'.format(self, self.context.module) | python | def description(self) -> str:
'''Test name in nose output (intended to be overridden).'''
return '{0.uuid.hex}—{1}'.format(self, self.context.module) | [
"def",
"description",
"(",
"self",
")",
"->",
"str",
":",
"return",
"'{0.uuid.hex}—{1}'.f",
"o",
"rmat(s",
"e",
"lf, ",
"s",
"lf.c",
"o",
"ntext.m",
"o",
"dule)",
""
] | Test name in nose output (intended to be overridden). | [
"Test",
"name",
"in",
"nose",
"output",
"(",
"intended",
"to",
"be",
"overridden",
")",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L181-L184 |
racker/torment | torment/fixtures/__init__.py | Fixture._execute | def _execute(self) -> None:
'''Run Fixture actions (setup, run, check).
Core test loop for Fixture. Executes setup, run, and check in order.
'''
if hasattr(self, '_last_resolver_exception'):
logger.warning('last exception from %s.%s:', self.__class__.__name__, self._last_... | python | def _execute(self) -> None:
'''Run Fixture actions (setup, run, check).
Core test loop for Fixture. Executes setup, run, and check in order.
'''
if hasattr(self, '_last_resolver_exception'):
logger.warning('last exception from %s.%s:', self.__class__.__name__, self._last_... | [
"def",
"_execute",
"(",
"self",
")",
"->",
"None",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_last_resolver_exception'",
")",
":",
"logger",
".",
"warning",
"(",
"'last exception from %s.%s:'",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
"."... | Run Fixture actions (setup, run, check).
Core test loop for Fixture. Executes setup, run, and check in order. | [
"Run",
"Fixture",
"actions",
"(",
"setup",
"run",
"check",
")",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L235-L247 |
racker/torment | torment/fixtures/__init__.py | ErrorFixture.run | def run(self) -> None:
'''Calls sibling with exception expectation.'''
with self.context.assertRaises(self.error.__class__) as error:
super().run()
self.exception = error.exception | python | def run(self) -> None:
'''Calls sibling with exception expectation.'''
with self.context.assertRaises(self.error.__class__) as error:
super().run()
self.exception = error.exception | [
"def",
"run",
"(",
"self",
")",
"->",
"None",
":",
"with",
"self",
".",
"context",
".",
"assertRaises",
"(",
"self",
".",
"error",
".",
"__class__",
")",
"as",
"error",
":",
"super",
"(",
")",
".",
"run",
"(",
")",
"self",
".",
"exception",
"=",
... | Calls sibling with exception expectation. | [
"Calls",
"sibling",
"with",
"exception",
"expectation",
"."
] | train | https://github.com/racker/torment/blob/bd5d2f978324bf9b7360edfae76d853b226c63e1/torment/fixtures/__init__.py#L283-L289 |
jalanb/pysyte | pysyte/getch.py | cache_keys | def cache_keys(keys):
"""Allow debugging via PyCharm"""
d = known_keys()
known_names = dict(zip(d.values(), d.keys()))
for k in keys:
i = (ord(k),) if len(k) == 1 else known_names[k]
_key_cache.insert(0, i) | python | def cache_keys(keys):
"""Allow debugging via PyCharm"""
d = known_keys()
known_names = dict(zip(d.values(), d.keys()))
for k in keys:
i = (ord(k),) if len(k) == 1 else known_names[k]
_key_cache.insert(0, i) | [
"def",
"cache_keys",
"(",
"keys",
")",
":",
"d",
"=",
"known_keys",
"(",
")",
"known_names",
"=",
"dict",
"(",
"zip",
"(",
"d",
".",
"values",
"(",
")",
",",
"d",
".",
"keys",
"(",
")",
")",
")",
"for",
"k",
"in",
"keys",
":",
"i",
"=",
"(",
... | Allow debugging via PyCharm | [
"Allow",
"debugging",
"via",
"PyCharm"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/getch.py#L92-L98 |
jalanb/pysyte | pysyte/getch.py | _get_keycodes | def _get_keycodes():
"""Read keypress giving a tuple of key codes
A 'key code' is the ordinal value of characters read
For example, pressing 'A' will give (65,)
"""
try:
return _key_cache.pop()
except IndexError:
pass
result = []
terminators = 'ABCDFHPQRS~'
with Ter... | python | def _get_keycodes():
"""Read keypress giving a tuple of key codes
A 'key code' is the ordinal value of characters read
For example, pressing 'A' will give (65,)
"""
try:
return _key_cache.pop()
except IndexError:
pass
result = []
terminators = 'ABCDFHPQRS~'
with Ter... | [
"def",
"_get_keycodes",
"(",
")",
":",
"try",
":",
"return",
"_key_cache",
".",
"pop",
"(",
")",
"except",
"IndexError",
":",
"pass",
"result",
"=",
"[",
"]",
"terminators",
"=",
"'ABCDFHPQRS~'",
"with",
"TerminalContext",
"(",
")",
":",
"code",
"=",
"ge... | Read keypress giving a tuple of key codes
A 'key code' is the ordinal value of characters read
For example, pressing 'A' will give (65,) | [
"Read",
"keypress",
"giving",
"a",
"tuple",
"of",
"key",
"codes"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/getch.py#L101-L131 |
jalanb/pysyte | pysyte/getch.py | get_key | def get_key():
"""Get a key from the keyboard as a string
A 'key' will be a single char, or the name of an extended key
"""
character_name = chr
codes = _get_keycodes()
if len(codes) == 1:
code = codes[0]
if code >= 32:
return character_name(code)
return cont... | python | def get_key():
"""Get a key from the keyboard as a string
A 'key' will be a single char, or the name of an extended key
"""
character_name = chr
codes = _get_keycodes()
if len(codes) == 1:
code = codes[0]
if code >= 32:
return character_name(code)
return cont... | [
"def",
"get_key",
"(",
")",
":",
"character_name",
"=",
"chr",
"codes",
"=",
"_get_keycodes",
"(",
")",
"if",
"len",
"(",
"codes",
")",
"==",
"1",
":",
"code",
"=",
"codes",
"[",
"0",
"]",
"if",
"code",
">=",
"32",
":",
"return",
"character_name",
... | Get a key from the keyboard as a string
A 'key' will be a single char, or the name of an extended key | [
"Get",
"a",
"key",
"from",
"the",
"keyboard",
"as",
"a",
"string"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/getch.py#L155-L167 |
jalanb/pysyte | pysyte/getch.py | get_string | def get_string():
"""A better str(_get_keycodes()) method"""
keycodes = _get_keycodes()
initial_code, codes = keycodes[0], keycodes[1:]
initial_char = chr(initial_code)
if initial_code == 27:
initial_char = '\\e'
elif not ascii.isgraph(initial_char):
initial_char = '\\x%x' % init... | python | def get_string():
"""A better str(_get_keycodes()) method"""
keycodes = _get_keycodes()
initial_code, codes = keycodes[0], keycodes[1:]
initial_char = chr(initial_code)
if initial_code == 27:
initial_char = '\\e'
elif not ascii.isgraph(initial_char):
initial_char = '\\x%x' % init... | [
"def",
"get_string",
"(",
")",
":",
"keycodes",
"=",
"_get_keycodes",
"(",
")",
"initial_code",
",",
"codes",
"=",
"keycodes",
"[",
"0",
"]",
",",
"keycodes",
"[",
"1",
":",
"]",
"initial_char",
"=",
"chr",
"(",
"initial_code",
")",
"if",
"initial_code",... | A better str(_get_keycodes()) method | [
"A",
"better",
"str",
"(",
"_get_keycodes",
"()",
")",
"method"
] | train | https://github.com/jalanb/pysyte/blob/4e278101943d1ceb1a6bcaf6ddc72052ecf13114/pysyte/getch.py#L282-L292 |
unitedstack/steth | stetho/agent/api.py | AgentApi.check_ports_on_br | def check_ports_on_br(self, bridge='br-ex', ports=['eth3']):
"""Check ports exist on bridge.
ovs-vsctl list-ports bridge
"""
LOG.info("RPC: check_ports_on_br bridge: %s, ports: %s" %
(bridge, ports))
cmd = ['ovs-vsctl', 'list-ports', bridge]
stdcode, std... | python | def check_ports_on_br(self, bridge='br-ex', ports=['eth3']):
"""Check ports exist on bridge.
ovs-vsctl list-ports bridge
"""
LOG.info("RPC: check_ports_on_br bridge: %s, ports: %s" %
(bridge, ports))
cmd = ['ovs-vsctl', 'list-ports', bridge]
stdcode, std... | [
"def",
"check_ports_on_br",
"(",
"self",
",",
"bridge",
"=",
"'br-ex'",
",",
"ports",
"=",
"[",
"'eth3'",
"]",
")",
":",
"LOG",
".",
"info",
"(",
"\"RPC: check_ports_on_br bridge: %s, ports: %s\"",
"%",
"(",
"bridge",
",",
"ports",
")",
")",
"cmd",
"=",
"[... | Check ports exist on bridge.
ovs-vsctl list-ports bridge | [
"Check",
"ports",
"exist",
"on",
"bridge",
"."
] | train | https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/api.py#L27-L48 |
unitedstack/steth | stetho/agent/api.py | AgentApi.ping | def ping(self, ips, boardcast=False,
count=2, timeout=2, interface=None):
"""Ping host or broadcast.
ping host -c 2 -W 2
"""
cmd = ['ping', '-c', str(count), '-W', str(timeout)]
True if not interface else cmd.extend(['-I', interface])
True if not boardcast e... | python | def ping(self, ips, boardcast=False,
count=2, timeout=2, interface=None):
"""Ping host or broadcast.
ping host -c 2 -W 2
"""
cmd = ['ping', '-c', str(count), '-W', str(timeout)]
True if not interface else cmd.extend(['-I', interface])
True if not boardcast e... | [
"def",
"ping",
"(",
"self",
",",
"ips",
",",
"boardcast",
"=",
"False",
",",
"count",
"=",
"2",
",",
"timeout",
"=",
"2",
",",
"interface",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'ping'",
",",
"'-c'",
",",
"str",
"(",
"count",
")",
",",
"'-W'... | Ping host or broadcast.
ping host -c 2 -W 2 | [
"Ping",
"host",
"or",
"broadcast",
"."
] | train | https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/api.py#L50-L72 |
unitedstack/steth | stetho/agent/api.py | AgentApi.add_vlan_to_interface | def add_vlan_to_interface(self, interface, vlan_id):
"""Add vlan interface.
ip link add link eth0 name eth0.10 type vlan id 10
"""
subif = '%s.%s' % (interface, vlan_id)
vlan_id = '%s' % vlan_id
cmd = ['ip', 'link', 'add', 'link', interface, 'name',
subif,... | python | def add_vlan_to_interface(self, interface, vlan_id):
"""Add vlan interface.
ip link add link eth0 name eth0.10 type vlan id 10
"""
subif = '%s.%s' % (interface, vlan_id)
vlan_id = '%s' % vlan_id
cmd = ['ip', 'link', 'add', 'link', interface, 'name',
subif,... | [
"def",
"add_vlan_to_interface",
"(",
"self",
",",
"interface",
",",
"vlan_id",
")",
":",
"subif",
"=",
"'%s.%s'",
"%",
"(",
"interface",
",",
"vlan_id",
")",
"vlan_id",
"=",
"'%s'",
"%",
"vlan_id",
"cmd",
"=",
"[",
"'ip'",
",",
"'link'",
",",
"'add'",
... | Add vlan interface.
ip link add link eth0 name eth0.10 type vlan id 10 | [
"Add",
"vlan",
"interface",
"."
] | train | https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/api.py#L74-L88 |
unitedstack/steth | stetho/agent/api.py | AgentApi.get_interface | def get_interface(self, interface='eth0'):
"""Interface info.
ifconfig interface
"""
LOG.info("RPC: get_interface interfae: %s" % interface)
code, message, data = agent_utils.get_interface(interface)
return agent_utils.make_response(code, message, data) | python | def get_interface(self, interface='eth0'):
"""Interface info.
ifconfig interface
"""
LOG.info("RPC: get_interface interfae: %s" % interface)
code, message, data = agent_utils.get_interface(interface)
return agent_utils.make_response(code, message, data) | [
"def",
"get_interface",
"(",
"self",
",",
"interface",
"=",
"'eth0'",
")",
":",
"LOG",
".",
"info",
"(",
"\"RPC: get_interface interfae: %s\"",
"%",
"interface",
")",
"code",
",",
"message",
",",
"data",
"=",
"agent_utils",
".",
"get_interface",
"(",
"interfac... | Interface info.
ifconfig interface | [
"Interface",
"info",
"."
] | train | https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/api.py#L90-L97 |
unitedstack/steth | stetho/agent/api.py | AgentApi.setup_link | def setup_link(self, interface, cidr):
"""Setup a link.
ip addr add dev interface
ip link set dev interface up
"""
# clear old ipaddr in interface
cmd = ['ip', 'addr', 'flush', 'dev', interface]
agent_utils.execute(cmd, root=True)
ip = IPNetwork(cidr)
... | python | def setup_link(self, interface, cidr):
"""Setup a link.
ip addr add dev interface
ip link set dev interface up
"""
# clear old ipaddr in interface
cmd = ['ip', 'addr', 'flush', 'dev', interface]
agent_utils.execute(cmd, root=True)
ip = IPNetwork(cidr)
... | [
"def",
"setup_link",
"(",
"self",
",",
"interface",
",",
"cidr",
")",
":",
"# clear old ipaddr in interface",
"cmd",
"=",
"[",
"'ip'",
",",
"'addr'",
",",
"'flush'",
",",
"'dev'",
",",
"interface",
"]",
"agent_utils",
".",
"execute",
"(",
"cmd",
",",
"root... | Setup a link.
ip addr add dev interface
ip link set dev interface up | [
"Setup",
"a",
"link",
"."
] | train | https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/api.py#L99-L119 |
unitedstack/steth | stetho/agent/api.py | AgentApi.teardown_link | def teardown_link(self, interface):
"""ip link
"""
cmd = ['ip', 'link', 'delete', interface]
stdcode, stdout = agent_utils.execute(cmd, root=True)
if stdcode == 0:
return agent_utils.make_response(code=stdcode)
# execute failed.
message = stdout.pop(0)... | python | def teardown_link(self, interface):
"""ip link
"""
cmd = ['ip', 'link', 'delete', interface]
stdcode, stdout = agent_utils.execute(cmd, root=True)
if stdcode == 0:
return agent_utils.make_response(code=stdcode)
# execute failed.
message = stdout.pop(0)... | [
"def",
"teardown_link",
"(",
"self",
",",
"interface",
")",
":",
"cmd",
"=",
"[",
"'ip'",
",",
"'link'",
",",
"'delete'",
",",
"interface",
"]",
"stdcode",
",",
"stdout",
"=",
"agent_utils",
".",
"execute",
"(",
"cmd",
",",
"root",
"=",
"True",
")",
... | ip link | [
"ip",
"link"
] | train | https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/api.py#L121-L130 |
unitedstack/steth | stetho/agent/api.py | AgentApi.setup_iperf_server | def setup_iperf_server(self, protocol='TCP', port=5001, window=None):
"""iperf -s
"""
iperf = iperf_driver.IPerfDriver()
try:
data = iperf.start_server(protocol='TCP', port=5001, window=None)
return agent_utils.make_response(code=0, data=data)
except:
... | python | def setup_iperf_server(self, protocol='TCP', port=5001, window=None):
"""iperf -s
"""
iperf = iperf_driver.IPerfDriver()
try:
data = iperf.start_server(protocol='TCP', port=5001, window=None)
return agent_utils.make_response(code=0, data=data)
except:
... | [
"def",
"setup_iperf_server",
"(",
"self",
",",
"protocol",
"=",
"'TCP'",
",",
"port",
"=",
"5001",
",",
"window",
"=",
"None",
")",
":",
"iperf",
"=",
"iperf_driver",
".",
"IPerfDriver",
"(",
")",
"try",
":",
"data",
"=",
"iperf",
".",
"start_server",
... | iperf -s | [
"iperf",
"-",
"s"
] | train | https://github.com/unitedstack/steth/blob/955884ceebf3bdc474c93cc5cf555e67d16458f1/stetho/agent/api.py#L132-L141 |
DecBayComp/RWA-python | rwa/generic.py | isreference | def isreference(a):
"""
Tell whether a variable is an object reference.
Due to garbage collection, some objects happen to get the id of a distinct variable.
As a consequence, linking is not ready yet and `isreference` returns ``False``.
"""
return False
return id(a) != id(copy.copy(a))
... | python | def isreference(a):
"""
Tell whether a variable is an object reference.
Due to garbage collection, some objects happen to get the id of a distinct variable.
As a consequence, linking is not ready yet and `isreference` returns ``False``.
"""
return False
return id(a) != id(copy.copy(a))
... | [
"def",
"isreference",
"(",
"a",
")",
":",
"return",
"False",
"return",
"id",
"(",
"a",
")",
"!=",
"id",
"(",
"copy",
".",
"copy",
"(",
"a",
")",
")",
"check",
"=",
"(",
"'__dict__'",
",",
"'__slots__'",
")",
"for",
"attr",
"in",
"check",
":",
"tr... | Tell whether a variable is an object reference.
Due to garbage collection, some objects happen to get the id of a distinct variable.
As a consequence, linking is not ready yet and `isreference` returns ``False``. | [
"Tell",
"whether",
"a",
"variable",
"is",
"an",
"object",
"reference",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L24-L43 |
DecBayComp/RWA-python | rwa/generic.py | lookup_type | def lookup_type(storable_type):
"""
Look for the Python type that corresponds to a storable type name.
"""
if storable_type.startswith('Python'):
_, module_name = storable_type.split('.', 1)
else:
module_name = storable_type
#type_name, module_name = \
names = [ _name[::-1] f... | python | def lookup_type(storable_type):
"""
Look for the Python type that corresponds to a storable type name.
"""
if storable_type.startswith('Python'):
_, module_name = storable_type.split('.', 1)
else:
module_name = storable_type
#type_name, module_name = \
names = [ _name[::-1] f... | [
"def",
"lookup_type",
"(",
"storable_type",
")",
":",
"if",
"storable_type",
".",
"startswith",
"(",
"'Python'",
")",
":",
"_",
",",
"module_name",
"=",
"storable_type",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"else",
":",
"module_name",
"=",
"storable_ty... | Look for the Python type that corresponds to a storable type name. | [
"Look",
"for",
"the",
"Python",
"type",
"that",
"corresponds",
"to",
"a",
"storable",
"type",
"name",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L46-L66 |
DecBayComp/RWA-python | rwa/generic.py | poke | def poke(exposes):
"""
Default serializer factory.
Arguments:
exposes (iterable): attributes to serialized.
Returns:
callable: serializer (`poke` routine).
"""
def _poke(store, objname, obj, container, visited=None, _stack=None):
try:
sub_container = store... | python | def poke(exposes):
"""
Default serializer factory.
Arguments:
exposes (iterable): attributes to serialized.
Returns:
callable: serializer (`poke` routine).
"""
def _poke(store, objname, obj, container, visited=None, _stack=None):
try:
sub_container = store... | [
"def",
"poke",
"(",
"exposes",
")",
":",
"def",
"_poke",
"(",
"store",
",",
"objname",
",",
"obj",
",",
"container",
",",
"visited",
"=",
"None",
",",
"_stack",
"=",
"None",
")",
":",
"try",
":",
"sub_container",
"=",
"store",
".",
"newContainer",
"(... | Default serializer factory.
Arguments:
exposes (iterable): attributes to serialized.
Returns:
callable: serializer (`poke` routine). | [
"Default",
"serializer",
"factory",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L466-L494 |
DecBayComp/RWA-python | rwa/generic.py | poke_assoc | def poke_assoc(store, objname, assoc, container, visited=None, _stack=None):
"""
Serialize association lists.
"""
try:
sub_container = store.newContainer(objname, assoc, container)
except (SystemExit, KeyboardInterrupt):
raise
except:
raise ValueError('generic poke not su... | python | def poke_assoc(store, objname, assoc, container, visited=None, _stack=None):
"""
Serialize association lists.
"""
try:
sub_container = store.newContainer(objname, assoc, container)
except (SystemExit, KeyboardInterrupt):
raise
except:
raise ValueError('generic poke not su... | [
"def",
"poke_assoc",
"(",
"store",
",",
"objname",
",",
"assoc",
",",
"container",
",",
"visited",
"=",
"None",
",",
"_stack",
"=",
"None",
")",
":",
"try",
":",
"sub_container",
"=",
"store",
".",
"newContainer",
"(",
"objname",
",",
"assoc",
",",
"co... | Serialize association lists. | [
"Serialize",
"association",
"lists",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L496-L532 |
DecBayComp/RWA-python | rwa/generic.py | default_peek | def default_peek(python_type, exposes):
"""
Autoserializer factory.
Works best in Python 3.
Arguments:
python_type (type): type constructor.
exposes (iterable): sequence of attributes.
Returns:
callable: deserializer (`peek` routine).
"""
with_args = False
... | python | def default_peek(python_type, exposes):
"""
Autoserializer factory.
Works best in Python 3.
Arguments:
python_type (type): type constructor.
exposes (iterable): sequence of attributes.
Returns:
callable: deserializer (`peek` routine).
"""
with_args = False
... | [
"def",
"default_peek",
"(",
"python_type",
",",
"exposes",
")",
":",
"with_args",
"=",
"False",
"make",
"=",
"python_type",
"try",
":",
"make",
"(",
")",
"except",
"(",
"SystemExit",
",",
"KeyboardInterrupt",
")",
":",
"raise",
"except",
":",
"make",
"=",
... | Autoserializer factory.
Works best in Python 3.
Arguments:
python_type (type): type constructor.
exposes (iterable): sequence of attributes.
Returns:
callable: deserializer (`peek` routine). | [
"Autoserializer",
"factory",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L536-L604 |
DecBayComp/RWA-python | rwa/generic.py | unsafe_peek | def unsafe_peek(init):
"""
Deserialize all the attributes available in the container and pass them in the same order
as they come in the container.
This is a factory function; returns the actual `peek` routine.
Arguments:
init: type constructor.
Returns:
callable: deserializ... | python | def unsafe_peek(init):
"""
Deserialize all the attributes available in the container and pass them in the same order
as they come in the container.
This is a factory function; returns the actual `peek` routine.
Arguments:
init: type constructor.
Returns:
callable: deserializ... | [
"def",
"unsafe_peek",
"(",
"init",
")",
":",
"def",
"peek",
"(",
"store",
",",
"container",
",",
"_stack",
"=",
"None",
")",
":",
"return",
"init",
"(",
"*",
"[",
"store",
".",
"peek",
"(",
"attr",
",",
"container",
",",
"_stack",
"=",
"_stack",
")... | Deserialize all the attributes available in the container and pass them in the same order
as they come in the container.
This is a factory function; returns the actual `peek` routine.
Arguments:
init: type constructor.
Returns:
callable: deserializer (`peek` routine). | [
"Deserialize",
"all",
"the",
"attributes",
"available",
"in",
"the",
"container",
"and",
"pass",
"them",
"in",
"the",
"same",
"order",
"as",
"they",
"come",
"in",
"the",
"container",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L606-L624 |
DecBayComp/RWA-python | rwa/generic.py | peek_with_kwargs | def peek_with_kwargs(init, args=[]):
"""
Make datatypes passing keyworded arguments to the constructor.
This is a factory function; returns the actual `peek` routine.
Arguments:
init (callable): type constructor.
args (iterable): arguments NOT to be keyworded; order does matter.
... | python | def peek_with_kwargs(init, args=[]):
"""
Make datatypes passing keyworded arguments to the constructor.
This is a factory function; returns the actual `peek` routine.
Arguments:
init (callable): type constructor.
args (iterable): arguments NOT to be keyworded; order does matter.
... | [
"def",
"peek_with_kwargs",
"(",
"init",
",",
"args",
"=",
"[",
"]",
")",
":",
"def",
"peek",
"(",
"store",
",",
"container",
",",
"_stack",
"=",
"None",
")",
":",
"return",
"init",
"(",
"*",
"[",
"store",
".",
"peek",
"(",
"attr",
",",
"container",... | Make datatypes passing keyworded arguments to the constructor.
This is a factory function; returns the actual `peek` routine.
Arguments:
init (callable): type constructor.
args (iterable): arguments NOT to be keyworded; order does matter.
Returns:
callable: deserializer (`peek`... | [
"Make",
"datatypes",
"passing",
"keyworded",
"arguments",
"to",
"the",
"constructor",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L626-L650 |
DecBayComp/RWA-python | rwa/generic.py | peek | def peek(init, exposes, debug=False):
"""
Default deserializer factory.
Arguments:
init (callable): type constructor.
exposes (iterable): attributes to be peeked and passed to `init`.
Returns:
callable: deserializer (`peek` routine).
"""
def _peek(store, container, _... | python | def peek(init, exposes, debug=False):
"""
Default deserializer factory.
Arguments:
init (callable): type constructor.
exposes (iterable): attributes to be peeked and passed to `init`.
Returns:
callable: deserializer (`peek` routine).
"""
def _peek(store, container, _... | [
"def",
"peek",
"(",
"init",
",",
"exposes",
",",
"debug",
"=",
"False",
")",
":",
"def",
"_peek",
"(",
"store",
",",
"container",
",",
"_stack",
"=",
"None",
")",
":",
"args",
"=",
"[",
"store",
".",
"peek",
"(",
"objname",
",",
"container",
",",
... | Default deserializer factory.
Arguments:
init (callable): type constructor.
exposes (iterable): attributes to be peeked and passed to `init`.
Returns:
callable: deserializer (`peek` routine). | [
"Default",
"deserializer",
"factory",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L655-L675 |
DecBayComp/RWA-python | rwa/generic.py | peek_assoc | def peek_assoc(store, container, _stack=None):
"""
Deserialize association lists.
"""
assoc = []
try:
if store.getRecordAttr('key', container) == 'escaped':
for i in container:
assoc.append(store.peek(i, container, _stack=_stack))
else:
for i i... | python | def peek_assoc(store, container, _stack=None):
"""
Deserialize association lists.
"""
assoc = []
try:
if store.getRecordAttr('key', container) == 'escaped':
for i in container:
assoc.append(store.peek(i, container, _stack=_stack))
else:
for i i... | [
"def",
"peek_assoc",
"(",
"store",
",",
"container",
",",
"_stack",
"=",
"None",
")",
":",
"assoc",
"=",
"[",
"]",
"try",
":",
"if",
"store",
".",
"getRecordAttr",
"(",
"'key'",
",",
"container",
")",
"==",
"'escaped'",
":",
"for",
"i",
"in",
"contai... | Deserialize association lists. | [
"Deserialize",
"association",
"lists",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L677-L697 |
DecBayComp/RWA-python | rwa/generic.py | most_exposes | def most_exposes(python_type):
"""
Core engine for the automatic generation of storable instances.
Finds the attributes exposed by the objects of a given type.
Mostly Python3-only.
Does not handle types which `__new__` method requires extra arguments either.
Arguments:
python_type (t... | python | def most_exposes(python_type):
"""
Core engine for the automatic generation of storable instances.
Finds the attributes exposed by the objects of a given type.
Mostly Python3-only.
Does not handle types which `__new__` method requires extra arguments either.
Arguments:
python_type (t... | [
"def",
"most_exposes",
"(",
"python_type",
")",
":",
"_exposes",
"=",
"set",
"(",
")",
"try",
":",
"# list all standard class attributes and methods:",
"do_not_expose",
"=",
"set",
"(",
"python_type",
".",
"__dir__",
"(",
"object",
")",
"+",
"[",
"'__slots__'",
... | Core engine for the automatic generation of storable instances.
Finds the attributes exposed by the objects of a given type.
Mostly Python3-only.
Does not handle types which `__new__` method requires extra arguments either.
Arguments:
python_type (type): object type.
Returns:
l... | [
"Core",
"engine",
"for",
"the",
"automatic",
"generation",
"of",
"storable",
"instances",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L703-L766 |
DecBayComp/RWA-python | rwa/generic.py | default_storable | def default_storable(python_type, exposes=None, version=None, storable_type=None, peek=default_peek):
"""
Default mechanics for building the storable instance for a type.
Arguments:
python_type (type): type.
exposes (iterable): attributes exposed by the type.
version (tuple): ver... | python | def default_storable(python_type, exposes=None, version=None, storable_type=None, peek=default_peek):
"""
Default mechanics for building the storable instance for a type.
Arguments:
python_type (type): type.
exposes (iterable): attributes exposed by the type.
version (tuple): ver... | [
"def",
"default_storable",
"(",
"python_type",
",",
"exposes",
"=",
"None",
",",
"version",
"=",
"None",
",",
"storable_type",
"=",
"None",
",",
"peek",
"=",
"default_peek",
")",
":",
"if",
"not",
"exposes",
":",
"for",
"extension",
"in",
"expose_extensions"... | Default mechanics for building the storable instance for a type.
Arguments:
python_type (type): type.
exposes (iterable): attributes exposed by the type.
version (tuple): version number.
storable_type (str): universal string identifier for the type.
peek (callable): pee... | [
"Default",
"mechanics",
"for",
"building",
"the",
"storable",
"instance",
"for",
"a",
"type",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L779-L815 |
DecBayComp/RWA-python | rwa/generic.py | kwarg_storable | def kwarg_storable(python_type, exposes=None, version=None, storable_type=None, init=None, args=[]):
"""
**Deprecated**
"""
warnings.warn('kwarg_storable', DeprecationWarning)
if init is None:
init = python_type
if exposes is None:
try:
exposes = python_type.__slots__... | python | def kwarg_storable(python_type, exposes=None, version=None, storable_type=None, init=None, args=[]):
"""
**Deprecated**
"""
warnings.warn('kwarg_storable', DeprecationWarning)
if init is None:
init = python_type
if exposes is None:
try:
exposes = python_type.__slots__... | [
"def",
"kwarg_storable",
"(",
"python_type",
",",
"exposes",
"=",
"None",
",",
"version",
"=",
"None",
",",
"storable_type",
"=",
"None",
",",
"init",
"=",
"None",
",",
"args",
"=",
"[",
"]",
")",
":",
"warnings",
".",
"warn",
"(",
"'kwarg_storable'",
... | **Deprecated** | [
"**",
"Deprecated",
"**"
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L818-L834 |
DecBayComp/RWA-python | rwa/generic.py | not_storable | def not_storable(_type):
"""
Helper for tagging unserializable types.
Arguments:
_type (type): type to be ignored.
Returns:
Storable: storable instance that does not poke.
"""
return Storable(_type, handlers=StorableHandler(poke=fake_poke, peek=fail_peek(_type))) | python | def not_storable(_type):
"""
Helper for tagging unserializable types.
Arguments:
_type (type): type to be ignored.
Returns:
Storable: storable instance that does not poke.
"""
return Storable(_type, handlers=StorableHandler(poke=fake_poke, peek=fail_peek(_type))) | [
"def",
"not_storable",
"(",
"_type",
")",
":",
"return",
"Storable",
"(",
"_type",
",",
"handlers",
"=",
"StorableHandler",
"(",
"poke",
"=",
"fake_poke",
",",
"peek",
"=",
"fail_peek",
"(",
"_type",
")",
")",
")"
] | Helper for tagging unserializable types.
Arguments:
_type (type): type to be ignored.
Returns:
Storable: storable instance that does not poke. | [
"Helper",
"for",
"tagging",
"unserializable",
"types",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L883-L896 |
DecBayComp/RWA-python | rwa/generic.py | force_auto | def force_auto(service, _type):
"""
Helper for forcing autoserialization of a datatype with already registered explicit
storable instance.
Arguments:
service (StorableService): active storable service.
_type (type): type to be autoserialized.
**Not tested**
"""
storable =... | python | def force_auto(service, _type):
"""
Helper for forcing autoserialization of a datatype with already registered explicit
storable instance.
Arguments:
service (StorableService): active storable service.
_type (type): type to be autoserialized.
**Not tested**
"""
storable =... | [
"def",
"force_auto",
"(",
"service",
",",
"_type",
")",
":",
"storable",
"=",
"service",
".",
"byPythonType",
"(",
"_type",
",",
"istype",
"=",
"True",
")",
"version",
"=",
"max",
"(",
"handler",
".",
"version",
"[",
"0",
"]",
"for",
"handler",
"in",
... | Helper for forcing autoserialization of a datatype with already registered explicit
storable instance.
Arguments:
service (StorableService): active storable service.
_type (type): type to be autoserialized.
**Not tested** | [
"Helper",
"for",
"forcing",
"autoserialization",
"of",
"a",
"datatype",
"with",
"already",
"registered",
"explicit",
"storable",
"instance",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L900-L916 |
DecBayComp/RWA-python | rwa/generic.py | poke_native | def poke_native(getstate):
"""
Serializer factory for types which state can be natively serialized.
Arguments:
getstate (callable): takes an object and returns the object's state
to be passed to `pokeNative`.
Returns:
callable: serializer (`poke` routine).
"""
de... | python | def poke_native(getstate):
"""
Serializer factory for types which state can be natively serialized.
Arguments:
getstate (callable): takes an object and returns the object's state
to be passed to `pokeNative`.
Returns:
callable: serializer (`poke` routine).
"""
de... | [
"def",
"poke_native",
"(",
"getstate",
")",
":",
"def",
"poke",
"(",
"service",
",",
"objname",
",",
"obj",
",",
"container",
",",
"visited",
"=",
"None",
",",
"_stack",
"=",
"None",
")",
":",
"service",
".",
"pokeNative",
"(",
"objname",
",",
"getstat... | Serializer factory for types which state can be natively serialized.
Arguments:
getstate (callable): takes an object and returns the object's state
to be passed to `pokeNative`.
Returns:
callable: serializer (`poke` routine). | [
"Serializer",
"factory",
"for",
"types",
"which",
"state",
"can",
"be",
"natively",
"serialized",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L940-L956 |
DecBayComp/RWA-python | rwa/generic.py | peek_native | def peek_native(make):
"""
Deserializer factory for types which state can be natively serialized.
Arguments:
make (callable): type constructor.
Returns:
callable: deserializer (`peek` routine)
"""
def peek(service, container, _stack=None):
return make(service.peekNat... | python | def peek_native(make):
"""
Deserializer factory for types which state can be natively serialized.
Arguments:
make (callable): type constructor.
Returns:
callable: deserializer (`peek` routine)
"""
def peek(service, container, _stack=None):
return make(service.peekNat... | [
"def",
"peek_native",
"(",
"make",
")",
":",
"def",
"peek",
"(",
"service",
",",
"container",
",",
"_stack",
"=",
"None",
")",
":",
"return",
"make",
"(",
"service",
".",
"peekNative",
"(",
"container",
")",
")",
"return",
"peek"
] | Deserializer factory for types which state can be natively serialized.
Arguments:
make (callable): type constructor.
Returns:
callable: deserializer (`peek` routine) | [
"Deserializer",
"factory",
"for",
"types",
"which",
"state",
"can",
"be",
"natively",
"serialized",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L958-L973 |
DecBayComp/RWA-python | rwa/generic.py | handler | def handler(init, exposes, version=None):
"""
Simple handler with default `peek` and `poke` procedures.
Arguments:
init (callable): type constructor.
exposes (iterable): attributes to be (de-)serialized.
version (tuple): version number.
Returns:
StorableHandler: sto... | python | def handler(init, exposes, version=None):
"""
Simple handler with default `peek` and `poke` procedures.
Arguments:
init (callable): type constructor.
exposes (iterable): attributes to be (de-)serialized.
version (tuple): version number.
Returns:
StorableHandler: sto... | [
"def",
"handler",
"(",
"init",
",",
"exposes",
",",
"version",
"=",
"None",
")",
":",
"return",
"StorableHandler",
"(",
"poke",
"=",
"poke",
"(",
"exposes",
")",
",",
"peek",
"=",
"peek",
"(",
"init",
",",
"exposes",
")",
",",
"version",
"=",
"versio... | Simple handler with default `peek` and `poke` procedures.
Arguments:
init (callable): type constructor.
exposes (iterable): attributes to be (de-)serialized.
version (tuple): version number.
Returns:
StorableHandler: storable handler. | [
"Simple",
"handler",
"with",
"default",
"peek",
"and",
"poke",
"procedures",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L981-L997 |
DecBayComp/RWA-python | rwa/generic.py | namedtuple_storable | def namedtuple_storable(namedtuple, *args, **kwargs):
"""
Storable factory for named tuples.
"""
return default_storable(namedtuple, namedtuple._fields, *args, **kwargs) | python | def namedtuple_storable(namedtuple, *args, **kwargs):
"""
Storable factory for named tuples.
"""
return default_storable(namedtuple, namedtuple._fields, *args, **kwargs) | [
"def",
"namedtuple_storable",
"(",
"namedtuple",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"default_storable",
"(",
"namedtuple",
",",
"namedtuple",
".",
"_fields",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Storable factory for named tuples. | [
"Storable",
"factory",
"for",
"named",
"tuples",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L1000-L1004 |
DecBayComp/RWA-python | rwa/generic.py | GenericStore.pokeStorable | def pokeStorable(self, storable, objname, obj, container, visited=None, _stack=None, **kwargs):
"""
Arguments:
storable (StorableHandler): storable instance.
objname (any): record reference.
obj (any): object to be serialized.
container (any): containe... | python | def pokeStorable(self, storable, objname, obj, container, visited=None, _stack=None, **kwargs):
"""
Arguments:
storable (StorableHandler): storable instance.
objname (any): record reference.
obj (any): object to be serialized.
container (any): containe... | [
"def",
"pokeStorable",
"(",
"self",
",",
"storable",
",",
"objname",
",",
"obj",
",",
"container",
",",
"visited",
"=",
"None",
",",
"_stack",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"#print((objname, storable.storable_type)) # debug",
"storable",
".",... | Arguments:
storable (StorableHandler): storable instance.
objname (any): record reference.
obj (any): object to be serialized.
container (any): container.
visited (dict): map of the previously serialized objects that are
passed by referenc... | [
"Arguments",
":"
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L241-L274 |
DecBayComp/RWA-python | rwa/generic.py | GenericStore.pokeVisited | def pokeVisited(self, objname, obj, record, existing, visited=None, _stack=None, **kwargs):
"""
Serialize an already serialized object.
If the underlying store supports linking, this is the place where to make links.
The default implementation delegates to :meth:`pokeStorable` or :meth... | python | def pokeVisited(self, objname, obj, record, existing, visited=None, _stack=None, **kwargs):
"""
Serialize an already serialized object.
If the underlying store supports linking, this is the place where to make links.
The default implementation delegates to :meth:`pokeStorable` or :meth... | [
"def",
"pokeVisited",
"(",
"self",
",",
"objname",
",",
"obj",
",",
"record",
",",
"existing",
",",
"visited",
"=",
"None",
",",
"_stack",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"hasPythonType",
"(",
"obj",
")",
":",
"st... | Serialize an already serialized object.
If the underlying store supports linking, this is the place where to make links.
The default implementation delegates to :meth:`pokeStorable` or :meth:`pokeNative`.
Arguments:
objname (any): record reference.
obj (any): object ... | [
"Serialize",
"an",
"already",
"serialized",
"object",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L276-L309 |
DecBayComp/RWA-python | rwa/generic.py | GenericStore.peekStorable | def peekStorable(self, storable, record, _stack=None, **kwargs):
"""
Arguments:
storable (StorableHandler): storable instance.
record (any): record.
_stack (CallStack): stack of parent object names.
Returns:
any: deserialized object.
... | python | def peekStorable(self, storable, record, _stack=None, **kwargs):
"""
Arguments:
storable (StorableHandler): storable instance.
record (any): record.
_stack (CallStack): stack of parent object names.
Returns:
any: deserialized object.
... | [
"def",
"peekStorable",
"(",
"self",
",",
"storable",
",",
"record",
",",
"_stack",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"storable",
".",
"peek",
"(",
"self",
",",
"record",
",",
"_stack",
"=",
"_stack",
",",
"*",
"*",
"kwargs",
... | Arguments:
storable (StorableHandler): storable instance.
record (any): record.
_stack (CallStack): stack of parent object names.
Returns:
any: deserialized object.
Trailing keyword arguments are passed to the :class:`Storable` instance's
:at... | [
"Arguments",
":"
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L390-L407 |
DecBayComp/RWA-python | rwa/generic.py | GenericStore.defaultStorable | def defaultStorable(self, python_type=None, storable_type=None, version=None, **kwargs):
"""
Generate a default storable instance.
Arguments:
python_type (type): Python type of the object.
storable_type (str): storable type name.
version (tuple): version n... | python | def defaultStorable(self, python_type=None, storable_type=None, version=None, **kwargs):
"""
Generate a default storable instance.
Arguments:
python_type (type): Python type of the object.
storable_type (str): storable type name.
version (tuple): version n... | [
"def",
"defaultStorable",
"(",
"self",
",",
"python_type",
"=",
"None",
",",
"storable_type",
"=",
"None",
",",
"version",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"python_type",
"is",
"None",
":",
"python_type",
"=",
"lookup_type",
"(",
"st... | Generate a default storable instance.
Arguments:
python_type (type): Python type of the object.
storable_type (str): storable type name.
version (tuple): version number of the storable handler.
Returns:
StorableHandler: storable instance.
Ex... | [
"Generate",
"a",
"default",
"storable",
"instance",
"."
] | train | https://github.com/DecBayComp/RWA-python/blob/734a52e15a0e8c244d84d74acf3fd64721074732/rwa/generic.py#L438-L462 |
zeromake/aiko | aiko/request.py | RequestParameters.get | def get(self, name: str, default: Any = None) -> Any:
"""Return the first value, either the default or actual"""
return super().get(name, [default])[0] | python | def get(self, name: str, default: Any = None) -> Any:
"""Return the first value, either the default or actual"""
return super().get(name, [default])[0] | [
"def",
"get",
"(",
"self",
",",
"name",
":",
"str",
",",
"default",
":",
"Any",
"=",
"None",
")",
"->",
"Any",
":",
"return",
"super",
"(",
")",
".",
"get",
"(",
"name",
",",
"[",
"default",
"]",
")",
"[",
"0",
"]"
] | Return the first value, either the default or actual | [
"Return",
"the",
"first",
"value",
"either",
"the",
"default",
"or",
"actual"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L31-L33 |
zeromake/aiko | aiko/request.py | RequestParameters.getlist | def getlist(self, name: str, default: Any = None) -> List[Any]:
"""Return the entire list"""
return super().get(name, default) | python | def getlist(self, name: str, default: Any = None) -> List[Any]:
"""Return the entire list"""
return super().get(name, default) | [
"def",
"getlist",
"(",
"self",
",",
"name",
":",
"str",
",",
"default",
":",
"Any",
"=",
"None",
")",
"->",
"List",
"[",
"Any",
"]",
":",
"return",
"super",
"(",
")",
".",
"get",
"(",
"name",
",",
"default",
")"
] | Return the entire list | [
"Return",
"the",
"entire",
"list"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L35-L37 |
zeromake/aiko | aiko/request.py | RequestUrl.href | def href(self) -> str:
"""
把 url 从新构建
"""
href_arr = cast(List[str], [])
href_arr.append(self.schema)
href_arr.append("://")
if self.userinfo is not None:
href_arr.append(self.userinfo)
href_arr.append("@")
href_arr.append(self.host... | python | def href(self) -> str:
"""
把 url 从新构建
"""
href_arr = cast(List[str], [])
href_arr.append(self.schema)
href_arr.append("://")
if self.userinfo is not None:
href_arr.append(self.userinfo)
href_arr.append("@")
href_arr.append(self.host... | [
"def",
"href",
"(",
"self",
")",
"->",
"str",
":",
"href_arr",
"=",
"cast",
"(",
"List",
"[",
"str",
"]",
",",
"[",
"]",
")",
"href_arr",
".",
"append",
"(",
"self",
".",
"schema",
")",
"href_arr",
".",
"append",
"(",
"\"://\"",
")",
"if",
"self"... | 把 url 从新构建 | [
"把",
"url",
"从新构建"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L77-L99 |
zeromake/aiko | aiko/request.py | Request.feed_data | def feed_data(self, data: bytes) -> None:
"""
代理 feed_data
"""
if self._parser is not None:
self._parser.feed_data(data) | python | def feed_data(self, data: bytes) -> None:
"""
代理 feed_data
"""
if self._parser is not None:
self._parser.feed_data(data) | [
"def",
"feed_data",
"(",
"self",
",",
"data",
":",
"bytes",
")",
"->",
"None",
":",
"if",
"self",
".",
"_parser",
"is",
"not",
"None",
":",
"self",
".",
"_parser",
".",
"feed_data",
"(",
"data",
")"
] | 代理 feed_data | [
"代理",
"feed_data"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L191-L196 |
zeromake/aiko | aiko/request.py | Request.on_header | def on_header(self, name: bytes, value: bytes) -> None:
"""
header 回调
"""
name_ = decode_bytes(name).casefold()
val = decode_bytes(value)
if name_ == "cookie":
# 加载上次的 cookie
self._cookies.load(val)
if name_ in self._headers:
# ... | python | def on_header(self, name: bytes, value: bytes) -> None:
"""
header 回调
"""
name_ = decode_bytes(name).casefold()
val = decode_bytes(value)
if name_ == "cookie":
# 加载上次的 cookie
self._cookies.load(val)
if name_ in self._headers:
# ... | [
"def",
"on_header",
"(",
"self",
",",
"name",
":",
"bytes",
",",
"value",
":",
"bytes",
")",
"->",
"None",
":",
"name_",
"=",
"decode_bytes",
"(",
"name",
")",
".",
"casefold",
"(",
")",
"val",
"=",
"decode_bytes",
"(",
"value",
")",
"if",
"name_",
... | header 回调 | [
"header",
"回调"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L213-L230 |
zeromake/aiko | aiko/request.py | Request.method | def method(self) -> str:
"""
获取请求方法
"""
if self._method is None:
self._method = decode_bytes(self._parser.get_method())
return self._method | python | def method(self) -> str:
"""
获取请求方法
"""
if self._method is None:
self._method = decode_bytes(self._parser.get_method())
return self._method | [
"def",
"method",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_method",
"is",
"None",
":",
"self",
".",
"_method",
"=",
"decode_bytes",
"(",
"self",
".",
"_parser",
".",
"get_method",
"(",
")",
")",
"return",
"self",
".",
"_method"
] | 获取请求方法 | [
"获取请求方法"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L239-L245 |
zeromake/aiko | aiko/request.py | Request.version | def version(self) -> Optional[str]:
"""
获取 http 版本
"""
if self._version is None:
self._version = self._parser.get_http_version()
return self._version | python | def version(self) -> Optional[str]:
"""
获取 http 版本
"""
if self._version is None:
self._version = self._parser.get_http_version()
return self._version | [
"def",
"version",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"self",
".",
"_version",
"is",
"None",
":",
"self",
".",
"_version",
"=",
"self",
".",
"_parser",
".",
"get_http_version",
"(",
")",
"return",
"self",
".",
"_version"
] | 获取 http 版本 | [
"获取",
"http",
"版本"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L255-L261 |
zeromake/aiko | aiko/request.py | Request.proxy | def proxy(self) -> bool:
"""
从 app 读取是否判断 proxy
"""
if self.app is None:
return False
return bool(cast(Any, self.app).proxy) | python | def proxy(self) -> bool:
"""
从 app 读取是否判断 proxy
"""
if self.app is None:
return False
return bool(cast(Any, self.app).proxy) | [
"def",
"proxy",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"app",
"is",
"None",
":",
"return",
"False",
"return",
"bool",
"(",
"cast",
"(",
"Any",
",",
"self",
".",
"app",
")",
".",
"proxy",
")"
] | 从 app 读取是否判断 proxy | [
"从",
"app",
"读取是否判断",
"proxy"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L279-L285 |
zeromake/aiko | aiko/request.py | Request.length | def length(self) -> Optional[int]:
"""
获取 body 长度
"""
len_ = self.get("content-length")
if len_ is not None:
return int(cast(str, len_))
return None | python | def length(self) -> Optional[int]:
"""
获取 body 长度
"""
len_ = self.get("content-length")
if len_ is not None:
return int(cast(str, len_))
return None | [
"def",
"length",
"(",
"self",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"len_",
"=",
"self",
".",
"get",
"(",
"\"content-length\"",
")",
"if",
"len_",
"is",
"not",
"None",
":",
"return",
"int",
"(",
"cast",
"(",
"str",
",",
"len_",
")",
")",
"... | 获取 body 长度 | [
"获取",
"body",
"长度"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L295-L302 |
zeromake/aiko | aiko/request.py | Request.get | def get(self, name: str) -> Union[None, str, List[str]]:
"""
获取 header
"""
name = name.casefold()
if name == "referer" or name == "referrer":
if "referrer" in self._headers:
return self._headers["referrer"]
elif "referer" in self._headers:
... | python | def get(self, name: str) -> Union[None, str, List[str]]:
"""
获取 header
"""
name = name.casefold()
if name == "referer" or name == "referrer":
if "referrer" in self._headers:
return self._headers["referrer"]
elif "referer" in self._headers:
... | [
"def",
"get",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Union",
"[",
"None",
",",
"str",
",",
"List",
"[",
"str",
"]",
"]",
":",
"name",
"=",
"name",
".",
"casefold",
"(",
")",
"if",
"name",
"==",
"\"referer\"",
"or",
"name",
"==",
"\"r... | 获取 header | [
"获取",
"header"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L304-L319 |
zeromake/aiko | aiko/request.py | Request.set | def set(self, name: str, value: str) -> None:
"""
重写请求中的 header, 不推荐使用
"""
name = name.casefold()
self._headers[name] = value | python | def set(self, name: str, value: str) -> None:
"""
重写请求中的 header, 不推荐使用
"""
name = name.casefold()
self._headers[name] = value | [
"def",
"set",
"(",
"self",
",",
"name",
":",
"str",
",",
"value",
":",
"str",
")",
"->",
"None",
":",
"name",
"=",
"name",
".",
"casefold",
"(",
")",
"self",
".",
"_headers",
"[",
"name",
"]",
"=",
"value"
] | 重写请求中的 header, 不推荐使用 | [
"重写请求中的",
"header",
"不推荐使用"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L321-L326 |
zeromake/aiko | aiko/request.py | Request.url | def url(self) -> str:
"""
path + query 的url
"""
url_str = self.parse_url.path or ""
if self.parse_url.querystring is not None:
url_str += "?" + self.parse_url.querystring
return url_str | python | def url(self) -> str:
"""
path + query 的url
"""
url_str = self.parse_url.path or ""
if self.parse_url.querystring is not None:
url_str += "?" + self.parse_url.querystring
return url_str | [
"def",
"url",
"(",
"self",
")",
"->",
"str",
":",
"url_str",
"=",
"self",
".",
"parse_url",
".",
"path",
"or",
"\"\"",
"if",
"self",
".",
"parse_url",
".",
"querystring",
"is",
"not",
"None",
":",
"url_str",
"+=",
"\"?\"",
"+",
"self",
".",
"parse_ur... | path + query 的url | [
"path",
"+",
"query",
"的url"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L329-L336 |
zeromake/aiko | aiko/request.py | Request.url | def url(self, url_str: str) -> None:
"""
url 重写
"""
if "?" in url_str:
url_arr = url_str.split("?")
self.parse_url.path = url_arr[0]
self.parse_url.querystring = url_arr[1] | python | def url(self, url_str: str) -> None:
"""
url 重写
"""
if "?" in url_str:
url_arr = url_str.split("?")
self.parse_url.path = url_arr[0]
self.parse_url.querystring = url_arr[1] | [
"def",
"url",
"(",
"self",
",",
"url_str",
":",
"str",
")",
"->",
"None",
":",
"if",
"\"?\"",
"in",
"url_str",
":",
"url_arr",
"=",
"url_str",
".",
"split",
"(",
"\"?\"",
")",
"self",
".",
"parse_url",
".",
"path",
"=",
"url_arr",
"[",
"0",
"]",
... | url 重写 | [
"url",
"重写"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L339-L346 |
zeromake/aiko | aiko/request.py | Request.path | def path(self) -> Optional[str]:
"""
获取 path
"""
path_str = self.parse_url.path
if path_str is not None and "%" in path_str:
path_str = unquote(path_str)
return path_str | python | def path(self) -> Optional[str]:
"""
获取 path
"""
path_str = self.parse_url.path
if path_str is not None and "%" in path_str:
path_str = unquote(path_str)
return path_str | [
"def",
"path",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"path_str",
"=",
"self",
".",
"parse_url",
".",
"path",
"if",
"path_str",
"is",
"not",
"None",
"and",
"\"%\"",
"in",
"path_str",
":",
"path_str",
"=",
"unquote",
"(",
"path_str",
... | 获取 path | [
"获取",
"path"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L349-L356 |
zeromake/aiko | aiko/request.py | Request.query | def query(self, query_dict: Dict[str, Any]) -> None:
"""
重写 query
"""
self.parse_url.query = cast(Any, query_dict) | python | def query(self, query_dict: Dict[str, Any]) -> None:
"""
重写 query
"""
self.parse_url.query = cast(Any, query_dict) | [
"def",
"query",
"(",
"self",
",",
"query_dict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"self",
".",
"parse_url",
".",
"query",
"=",
"cast",
"(",
"Any",
",",
"query_dict",
")"
] | 重写 query | [
"重写",
"query"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L373-L377 |
zeromake/aiko | aiko/request.py | Request.parse_url | def parse_url(self) -> RequestUrl:
"""
获取url解析对象
"""
if self._URL is None:
current_url = b"%s://%s%s" % (
encode_str(self.schema),
encode_str(self.host),
self._current_url
)
self._URL = RequestUrl(current... | python | def parse_url(self) -> RequestUrl:
"""
获取url解析对象
"""
if self._URL is None:
current_url = b"%s://%s%s" % (
encode_str(self.schema),
encode_str(self.host),
self._current_url
)
self._URL = RequestUrl(current... | [
"def",
"parse_url",
"(",
"self",
")",
"->",
"RequestUrl",
":",
"if",
"self",
".",
"_URL",
"is",
"None",
":",
"current_url",
"=",
"b\"%s://%s%s\"",
"%",
"(",
"encode_str",
"(",
"self",
".",
"schema",
")",
",",
"encode_str",
"(",
"self",
".",
"host",
")"... | 获取url解析对象 | [
"获取url解析对象"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L422-L433 |
zeromake/aiko | aiko/request.py | Request.schema | def schema(self) -> str:
"""
返回请求协议,“https” 或 “http”。
当 app.proxy 是 true 时支持 X-Forwarded-Proto。
"""
if self._ssl:
return "https"
proxy = bool(self.app and self.app.proxy)
if not proxy:
return "http"
proto = cast(str, self.get("X-For... | python | def schema(self) -> str:
"""
返回请求协议,“https” 或 “http”。
当 app.proxy 是 true 时支持 X-Forwarded-Proto。
"""
if self._ssl:
return "https"
proxy = bool(self.app and self.app.proxy)
if not proxy:
return "http"
proto = cast(str, self.get("X-For... | [
"def",
"schema",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_ssl",
":",
"return",
"\"https\"",
"proxy",
"=",
"bool",
"(",
"self",
".",
"app",
"and",
"self",
".",
"app",
".",
"proxy",
")",
"if",
"not",
"proxy",
":",
"return",
"\"http\""... | 返回请求协议,“https” 或 “http”。
当 app.proxy 是 true 时支持 X-Forwarded-Proto。 | [
"返回请求协议,“https”",
"或",
"“http”。",
"当",
"app",
".",
"proxy",
"是",
"true",
"时支持",
"X",
"-",
"Forwarded",
"-",
"Proto。"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L446-L457 |
zeromake/aiko | aiko/request.py | Request.charset | def charset(self) -> Optional[str]:
"""
获取 charset
"""
type_str = cast(str, self.get("Content-Type"))
if type_str is None or "charset" not in type_str:
return None
for i in type_str.split(";"):
item = i.strip()
if item.startswith("chars... | python | def charset(self) -> Optional[str]:
"""
获取 charset
"""
type_str = cast(str, self.get("Content-Type"))
if type_str is None or "charset" not in type_str:
return None
for i in type_str.split(";"):
item = i.strip()
if item.startswith("chars... | [
"def",
"charset",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"type_str",
"=",
"cast",
"(",
"str",
",",
"self",
".",
"get",
"(",
"\"Content-Type\"",
")",
")",
"if",
"type_str",
"is",
"None",
"or",
"\"charset\"",
"not",
"in",
"type_str",
... | 获取 charset | [
"获取",
"charset"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L475-L486 |
zeromake/aiko | aiko/request.py | Request.type | def type(self) -> Optional[str]:
"""
获取 type
"""
type_str = cast(Optional[str], self.get("Content-Type"))
if type_str is not None:
return type_str.split(";")[0]
else:
return None | python | def type(self) -> Optional[str]:
"""
获取 type
"""
type_str = cast(Optional[str], self.get("Content-Type"))
if type_str is not None:
return type_str.split(";")[0]
else:
return None | [
"def",
"type",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"type_str",
"=",
"cast",
"(",
"Optional",
"[",
"str",
"]",
",",
"self",
".",
"get",
"(",
"\"Content-Type\"",
")",
")",
"if",
"type_str",
"is",
"not",
"None",
":",
"return",
"t... | 获取 type | [
"获取",
"type"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L489-L497 |
zeromake/aiko | aiko/request.py | Request.host | def host(self) -> str:
"""
获取 host + port, 如果开启 proxy 开关。使用 X-Forwarded-Host 头
"""
host = cast(Optional[str], None)
if self.proxy and 'X-Forwarded-Host' in self._headers:
xhost = cast(Optional[str], self.get('X-Forwarded-Host'))
if xhost is not None:
... | python | def host(self) -> str:
"""
获取 host + port, 如果开启 proxy 开关。使用 X-Forwarded-Host 头
"""
host = cast(Optional[str], None)
if self.proxy and 'X-Forwarded-Host' in self._headers:
xhost = cast(Optional[str], self.get('X-Forwarded-Host'))
if xhost is not None:
... | [
"def",
"host",
"(",
"self",
")",
"->",
"str",
":",
"host",
"=",
"cast",
"(",
"Optional",
"[",
"str",
"]",
",",
"None",
")",
"if",
"self",
".",
"proxy",
"and",
"'X-Forwarded-Host'",
"in",
"self",
".",
"_headers",
":",
"xhost",
"=",
"cast",
"(",
"Opt... | 获取 host + port, 如果开启 proxy 开关。使用 X-Forwarded-Host 头 | [
"获取",
"host",
"+",
"port",
"如果开启",
"proxy",
"开关。使用",
"X",
"-",
"Forwarded",
"-",
"Host",
"头"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L500-L510 |
zeromake/aiko | aiko/request.py | Request.ips | def ips(self) -> Optional[List[str]]:
"""
获取远端代理ip
"""
if self.proxy and "X-Forwarded-For" in self._headers:
val = cast(str, self.get('X-Forwarded-For'))
ips = [i.strip() for i in val.split(",")]
return ips if len(ips) > 0 else None
return None | python | def ips(self) -> Optional[List[str]]:
"""
获取远端代理ip
"""
if self.proxy and "X-Forwarded-For" in self._headers:
val = cast(str, self.get('X-Forwarded-For'))
ips = [i.strip() for i in val.split(",")]
return ips if len(ips) > 0 else None
return None | [
"def",
"ips",
"(",
"self",
")",
"->",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
":",
"if",
"self",
".",
"proxy",
"and",
"\"X-Forwarded-For\"",
"in",
"self",
".",
"_headers",
":",
"val",
"=",
"cast",
"(",
"str",
",",
"self",
".",
"get",
"(",
... | 获取远端代理ip | [
"获取远端代理ip"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L520-L528 |
zeromake/aiko | aiko/request.py | Request.ip | def ip(self) -> Optional[str]:
"""
获取客户端ip, 开启代理会从 X-Forwarded-For 中获取
"""
ips = self.ips
if ips and len(ips) > 0:
return ips[0]
if self._transport:
return cast(
str,
self._transport.get_extra_info("peername"),
... | python | def ip(self) -> Optional[str]:
"""
获取客户端ip, 开启代理会从 X-Forwarded-For 中获取
"""
ips = self.ips
if ips and len(ips) > 0:
return ips[0]
if self._transport:
return cast(
str,
self._transport.get_extra_info("peername"),
... | [
"def",
"ip",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"ips",
"=",
"self",
".",
"ips",
"if",
"ips",
"and",
"len",
"(",
"ips",
")",
">",
"0",
":",
"return",
"ips",
"[",
"0",
"]",
"if",
"self",
".",
"_transport",
":",
"return",
... | 获取客户端ip, 开启代理会从 X-Forwarded-For 中获取 | [
"获取客户端ip,",
"开启代理会从",
"X",
"-",
"Forwarded",
"-",
"For",
"中获取"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L531-L543 |
zeromake/aiko | aiko/request.py | Request.fresh | def fresh(self) -> bool:
"""
检查请求缓存是否“新鲜”,也就是内容没有改变。
此方法用于 If-None-Match / ETag, 和 If-Modified-Since 和 Last-Modified 之间的缓存协商。
在设置一个或多个这些响应头后应该引用它。
"""
method_str = self.method
if method_str != 'GET' and method_str != 'HEAD':
return False
s = se... | python | def fresh(self) -> bool:
"""
检查请求缓存是否“新鲜”,也就是内容没有改变。
此方法用于 If-None-Match / ETag, 和 If-Modified-Since 和 Last-Modified 之间的缓存协商。
在设置一个或多个这些响应头后应该引用它。
"""
method_str = self.method
if method_str != 'GET' and method_str != 'HEAD':
return False
s = se... | [
"def",
"fresh",
"(",
"self",
")",
"->",
"bool",
":",
"method_str",
"=",
"self",
".",
"method",
"if",
"method_str",
"!=",
"'GET'",
"and",
"method_str",
"!=",
"'HEAD'",
":",
"return",
"False",
"s",
"=",
"self",
".",
"ctx",
".",
"status",
"if",
"(",
"s"... | 检查请求缓存是否“新鲜”,也就是内容没有改变。
此方法用于 If-None-Match / ETag, 和 If-Modified-Since 和 Last-Modified 之间的缓存协商。
在设置一个或多个这些响应头后应该引用它。 | [
"检查请求缓存是否“新鲜”,也就是内容没有改变。",
"此方法用于",
"If",
"-",
"None",
"-",
"Match",
"/",
"ETag",
"和",
"If",
"-",
"Modified",
"-",
"Since",
"和",
"Last",
"-",
"Modified",
"之间的缓存协商。",
"在设置一个或多个这些响应头后应该引用它。"
] | train | https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/request.py#L567-L582 |
littlemo/moear-api-common | moear_api_common/utils/__init__.py | get_config_dict | def get_config_dict(config):
'''
获取配置数据字典
对传入的配置包进行格式化处理,生成一个字典对象
:param object config: 配置模块
:return: 配置数据字典
:rtype: dict
'''
dst = {}
tmp = config.__dict__
key_list = dir(config)
key_list.remove('os')
for k, v in tmp.items():
if k in key_list and not k.startswi... | python | def get_config_dict(config):
'''
获取配置数据字典
对传入的配置包进行格式化处理,生成一个字典对象
:param object config: 配置模块
:return: 配置数据字典
:rtype: dict
'''
dst = {}
tmp = config.__dict__
key_list = dir(config)
key_list.remove('os')
for k, v in tmp.items():
if k in key_list and not k.startswi... | [
"def",
"get_config_dict",
"(",
"config",
")",
":",
"dst",
"=",
"{",
"}",
"tmp",
"=",
"config",
".",
"__dict__",
"key_list",
"=",
"dir",
"(",
"config",
")",
"key_list",
".",
"remove",
"(",
"'os'",
")",
"for",
"k",
",",
"v",
"in",
"tmp",
".",
"items"... | 获取配置数据字典
对传入的配置包进行格式化处理,生成一个字典对象
:param object config: 配置模块
:return: 配置数据字典
:rtype: dict | [
"获取配置数据字典"
] | train | https://github.com/littlemo/moear-api-common/blob/2a89a052d92592dd8e67bd50ec2fadc0219ac5d0/moear_api_common/utils/__init__.py#L29-L46 |
mrstephenneal/dirutility | dirutility/walk/filter.py | PathFilters.validate | def validate(self, path):
"""Run path against filter sets and return True if all pass"""
# Exclude hidden files and folders with '.' prefix
if os.path.basename(path).startswith('.'):
return False
# Check that current path level is more than min path and less than max path
... | python | def validate(self, path):
"""Run path against filter sets and return True if all pass"""
# Exclude hidden files and folders with '.' prefix
if os.path.basename(path).startswith('.'):
return False
# Check that current path level is more than min path and less than max path
... | [
"def",
"validate",
"(",
"self",
",",
"path",
")",
":",
"# Exclude hidden files and folders with '.' prefix",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
".",
"startswith",
"(",
"'.'",
")",
":",
"return",
"False",
"# Check that current path level is... | Run path against filter sets and return True if all pass | [
"Run",
"path",
"against",
"filter",
"sets",
"and",
"return",
"True",
"if",
"all",
"pass"
] | train | https://github.com/mrstephenneal/dirutility/blob/339378659e2d7e09c53acfc51c5df745bb0cd517/dirutility/walk/filter.py#L49-L74 |
emin63/eyap | eyap/__init__.py | Make.comment_thread | def comment_thread(cls, backend, *args, **kwargs):
"""Create a comment thread for the desired backend.
:arg backend: String name of backend (e.g., 'file',
'github', 'redis', etc.).
:arg *args, **kwargs: Arguments to be passed to contructor
... | python | def comment_thread(cls, backend, *args, **kwargs):
"""Create a comment thread for the desired backend.
:arg backend: String name of backend (e.g., 'file',
'github', 'redis', etc.).
:arg *args, **kwargs: Arguments to be passed to contructor
... | [
"def",
"comment_thread",
"(",
"cls",
",",
"backend",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ct_cls",
"=",
"cls",
".",
"_known_backends",
".",
"get",
"(",
"backend",
")",
"if",
"not",
"ct_cls",
":",
"return",
"None",
"return",
"ct_cls",
... | Create a comment thread for the desired backend.
:arg backend: String name of backend (e.g., 'file',
'github', 'redis', etc.).
:arg *args, **kwargs: Arguments to be passed to contructor
for that backend.
~-~-~-~-~-~-~-~-~-~... | [
"Create",
"a",
"comment",
"thread",
"for",
"the",
"desired",
"backend",
"."
] | train | https://github.com/emin63/eyap/blob/a610761973b478ca0e864e970be05ce29d5994a5/eyap/__init__.py#L123-L145 |
political-memory/django-representatives-votes | representatives_votes/contrib/francedata/import_dossiers.py | find_dossier | def find_dossier(data):
'''
Find dossier with reference matching either 'ref_an' or 'ref_sen',
create it if not found. Ensure its reference is 'ref_an' if both fields
are present.
'''
changed = False
dossier = None
reffield = None
for field in [k for k in ('ref_an', 'ref_sen') if ... | python | def find_dossier(data):
'''
Find dossier with reference matching either 'ref_an' or 'ref_sen',
create it if not found. Ensure its reference is 'ref_an' if both fields
are present.
'''
changed = False
dossier = None
reffield = None
for field in [k for k in ('ref_an', 'ref_sen') if ... | [
"def",
"find_dossier",
"(",
"data",
")",
":",
"changed",
"=",
"False",
"dossier",
"=",
"None",
"reffield",
"=",
"None",
"for",
"field",
"in",
"[",
"k",
"for",
"k",
"in",
"(",
"'ref_an'",
",",
"'ref_sen'",
")",
"if",
"k",
"in",
"data",
"]",
":",
"tr... | Find dossier with reference matching either 'ref_an' or 'ref_sen',
create it if not found. Ensure its reference is 'ref_an' if both fields
are present. | [
"Find",
"dossier",
"with",
"reference",
"matching",
"either",
"ref_an",
"or",
"ref_sen",
"create",
"it",
"if",
"not",
"found",
".",
"Ensure",
"its",
"reference",
"is",
"ref_an",
"if",
"both",
"fields",
"are",
"present",
"."
] | train | https://github.com/political-memory/django-representatives-votes/blob/97f9f29deefec05f18e51f6c38270b791b921bac/representatives_votes/contrib/francedata/import_dossiers.py#L36-L66 |
donovan-duplessis/pwnurl | pwnurl/models/base.py | BaseModel.saveform | def saveform(cls, form):
""" Create and save form model data to database """
columns = dict()
for name, field in cls.form_fields.iteritems():
columns[name] = getattr(form, field).data
instance = cls(**columns)
return instance.save() | python | def saveform(cls, form):
""" Create and save form model data to database """
columns = dict()
for name, field in cls.form_fields.iteritems():
columns[name] = getattr(form, field).data
instance = cls(**columns)
return instance.save() | [
"def",
"saveform",
"(",
"cls",
",",
"form",
")",
":",
"columns",
"=",
"dict",
"(",
")",
"for",
"name",
",",
"field",
"in",
"cls",
".",
"form_fields",
".",
"iteritems",
"(",
")",
":",
"columns",
"[",
"name",
"]",
"=",
"getattr",
"(",
"form",
",",
... | Create and save form model data to database | [
"Create",
"and",
"save",
"form",
"model",
"data",
"to",
"database"
] | train | https://github.com/donovan-duplessis/pwnurl/blob/a13e27694f738228d186ea437b4d15ef5a925a87/pwnurl/models/base.py#L28-L35 |
donovan-duplessis/pwnurl | pwnurl/models/base.py | BaseModel.get_by_id | def get_by_id(cls, id):
""" Get model by identifier """
if any((isinstance(id, basestring) and id.isdigit(), isinstance(id,
(int, float)))):
return cls.query.get(int(id))
return None | python | def get_by_id(cls, id):
""" Get model by identifier """
if any((isinstance(id, basestring) and id.isdigit(), isinstance(id,
(int, float)))):
return cls.query.get(int(id))
return None | [
"def",
"get_by_id",
"(",
"cls",
",",
"id",
")",
":",
"if",
"any",
"(",
"(",
"isinstance",
"(",
"id",
",",
"basestring",
")",
"and",
"id",
".",
"isdigit",
"(",
")",
",",
"isinstance",
"(",
"id",
",",
"(",
"int",
",",
"float",
")",
")",
")",
")",... | Get model by identifier | [
"Get",
"model",
"by",
"identifier"
] | train | https://github.com/donovan-duplessis/pwnurl/blob/a13e27694f738228d186ea437b4d15ef5a925a87/pwnurl/models/base.py#L38-L44 |
donovan-duplessis/pwnurl | pwnurl/models/base.py | BaseModel.update | def update(self, commit=True, **kwargs):
""" Update model attributes and save to database """
for (attr, value) in kwargs.iteritems():
setattr(self, attr, value)
return commit and self.save() or self | python | def update(self, commit=True, **kwargs):
""" Update model attributes and save to database """
for (attr, value) in kwargs.iteritems():
setattr(self, attr, value)
return commit and self.save() or self | [
"def",
"update",
"(",
"self",
",",
"commit",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"(",
"attr",
",",
"value",
")",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"attr",
",",
"value",
")",
"return",... | Update model attributes and save to database | [
"Update",
"model",
"attributes",
"and",
"save",
"to",
"database"
] | train | https://github.com/donovan-duplessis/pwnurl/blob/a13e27694f738228d186ea437b4d15ef5a925a87/pwnurl/models/base.py#L53-L58 |
donovan-duplessis/pwnurl | pwnurl/models/base.py | BaseModel.save | def save(self, commit=True):
""" Save model to database """
db.session.add(self)
if commit:
db.session.commit()
return self | python | def save(self, commit=True):
""" Save model to database """
db.session.add(self)
if commit:
db.session.commit()
return self | [
"def",
"save",
"(",
"self",
",",
"commit",
"=",
"True",
")",
":",
"db",
".",
"session",
".",
"add",
"(",
"self",
")",
"if",
"commit",
":",
"db",
".",
"session",
".",
"commit",
"(",
")",
"return",
"self"
] | Save model to database | [
"Save",
"model",
"to",
"database"
] | train | https://github.com/donovan-duplessis/pwnurl/blob/a13e27694f738228d186ea437b4d15ef5a925a87/pwnurl/models/base.py#L60-L66 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.