repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
quantmind/pulsar
pulsar/apps/wsgi/formdata.py
HttpBodyReader._waiting_expect
def _waiting_expect(self): '''``True`` when the client is waiting for 100 Continue. ''' if self._expect_sent is None: if self.environ.get('HTTP_EXPECT', '').lower() == '100-continue': return True self._expect_sent = '' return False
python
def _waiting_expect(self): '''``True`` when the client is waiting for 100 Continue. ''' if self._expect_sent is None: if self.environ.get('HTTP_EXPECT', '').lower() == '100-continue': return True self._expect_sent = '' return False
[ "def", "_waiting_expect", "(", "self", ")", ":", "if", "self", ".", "_expect_sent", "is", "None", ":", "if", "self", ".", "environ", ".", "get", "(", "'HTTP_EXPECT'", ",", "''", ")", ".", "lower", "(", ")", "==", "'100-continue'", ":", "return", "True"...
``True`` when the client is waiting for 100 Continue.
[ "True", "when", "the", "client", "is", "waiting", "for", "100", "Continue", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/formdata.py#L82-L89
train
quantmind/pulsar
pulsar/apps/wsgi/formdata.py
MultipartPart.base64
def base64(self, charset=None): '''Data encoded as base 64''' return b64encode(self.bytes()).decode(charset or self.charset)
python
def base64(self, charset=None): '''Data encoded as base 64''' return b64encode(self.bytes()).decode(charset or self.charset)
[ "def", "base64", "(", "self", ",", "charset", "=", "None", ")", ":", "return", "b64encode", "(", "self", ".", "bytes", "(", ")", ")", ".", "decode", "(", "charset", "or", "self", ".", "charset", ")" ]
Data encoded as base 64
[ "Data", "encoded", "as", "base", "64" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/formdata.py#L318-L320
train
quantmind/pulsar
pulsar/apps/wsgi/formdata.py
MultipartPart.feed_data
def feed_data(self, data): """Feed new data into the MultiPart parser or the data stream""" if data: self._bytes.append(data) if self.parser.stream: self.parser.stream(self) else: self.parser.buffer.extend(data)
python
def feed_data(self, data): """Feed new data into the MultiPart parser or the data stream""" if data: self._bytes.append(data) if self.parser.stream: self.parser.stream(self) else: self.parser.buffer.extend(data)
[ "def", "feed_data", "(", "self", ",", "data", ")", ":", "if", "data", ":", "self", ".", "_bytes", ".", "append", "(", "data", ")", "if", "self", ".", "parser", ".", "stream", ":", "self", ".", "parser", ".", "stream", "(", "self", ")", "else", ":...
Feed new data into the MultiPart parser or the data stream
[ "Feed", "new", "data", "into", "the", "MultiPart", "parser", "or", "the", "data", "stream" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/formdata.py#L329-L336
train
quantmind/pulsar
examples/proxyserver/manage.py
server
def server(name='proxy-server', headers_middleware=None, server_software=None, **kwargs): '''Function to Create a WSGI Proxy Server.''' if headers_middleware is None: headers_middleware = [x_forwarded_for] wsgi_proxy = ProxyServerWsgiHandler(headers_middleware) kwargs['server_software...
python
def server(name='proxy-server', headers_middleware=None, server_software=None, **kwargs): '''Function to Create a WSGI Proxy Server.''' if headers_middleware is None: headers_middleware = [x_forwarded_for] wsgi_proxy = ProxyServerWsgiHandler(headers_middleware) kwargs['server_software...
[ "def", "server", "(", "name", "=", "'proxy-server'", ",", "headers_middleware", "=", "None", ",", "server_software", "=", "None", ",", "**", "kwargs", ")", ":", "if", "headers_middleware", "is", "None", ":", "headers_middleware", "=", "[", "x_forwarded_for", "...
Function to Create a WSGI Proxy Server.
[ "Function", "to", "Create", "a", "WSGI", "Proxy", "Server", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/proxyserver/manage.py#L241-L248
train
quantmind/pulsar
examples/proxyserver/manage.py
TunnelResponse.request
async def request(self): '''Perform the Http request to the upstream server ''' request_headers = self.request_headers() environ = self.environ method = environ['REQUEST_METHOD'] data = None if method in ENCODE_BODY_METHODS: data = DataIterator(self) ...
python
async def request(self): '''Perform the Http request to the upstream server ''' request_headers = self.request_headers() environ = self.environ method = environ['REQUEST_METHOD'] data = None if method in ENCODE_BODY_METHODS: data = DataIterator(self) ...
[ "async", "def", "request", "(", "self", ")", ":", "request_headers", "=", "self", ".", "request_headers", "(", ")", "environ", "=", "self", ".", "environ", "method", "=", "environ", "[", "'REQUEST_METHOD'", "]", "data", "=", "None", "if", "method", "in", ...
Perform the Http request to the upstream server
[ "Perform", "the", "Http", "request", "to", "the", "upstream", "server" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/proxyserver/manage.py#L112-L130
train
quantmind/pulsar
examples/proxyserver/manage.py
TunnelResponse.pre_request
def pre_request(self, response, exc=None): """Start the tunnel. This is a callback fired once a connection with upstream server is established. """ if response.request.method == 'CONNECT': self.start_response( '200 Connection established', ...
python
def pre_request(self, response, exc=None): """Start the tunnel. This is a callback fired once a connection with upstream server is established. """ if response.request.method == 'CONNECT': self.start_response( '200 Connection established', ...
[ "def", "pre_request", "(", "self", ",", "response", ",", "exc", "=", "None", ")", ":", "if", "response", ".", "request", ".", "method", "==", "'CONNECT'", ":", "self", ".", "start_response", "(", "'200 Connection established'", ",", "[", "(", "'content-lengt...
Start the tunnel. This is a callback fired once a connection with upstream server is established.
[ "Start", "the", "tunnel", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/proxyserver/manage.py#L157-L184
train
quantmind/pulsar
pulsar/utils/pylib/protocols.py
Protocol.connection_lost
def connection_lost(self, exc=None): """Fires the ``connection_lost`` event. """ if self._loop.get_debug(): self.producer.logger.debug('connection lost %s', self) self.event('connection_lost').fire(exc=exc)
python
def connection_lost(self, exc=None): """Fires the ``connection_lost`` event. """ if self._loop.get_debug(): self.producer.logger.debug('connection lost %s', self) self.event('connection_lost').fire(exc=exc)
[ "def", "connection_lost", "(", "self", ",", "exc", "=", "None", ")", ":", "if", "self", ".", "_loop", ".", "get_debug", "(", ")", ":", "self", ".", "producer", ".", "logger", ".", "debug", "(", "'connection lost %s'", ",", "self", ")", "self", ".", "...
Fires the ``connection_lost`` event.
[ "Fires", "the", "connection_lost", "event", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/protocols.py#L163-L168
train
quantmind/pulsar
pulsar/utils/pylib/protocols.py
ProtocolConsumer.start
def start(self, request=None): """Starts processing the request for this protocol consumer. There is no need to override this method, implement :meth:`start_request` instead. If either :attr:`connection` or :attr:`transport` are missing, a :class:`RuntimeError` occurs. ...
python
def start(self, request=None): """Starts processing the request for this protocol consumer. There is no need to override this method, implement :meth:`start_request` instead. If either :attr:`connection` or :attr:`transport` are missing, a :class:`RuntimeError` occurs. ...
[ "def", "start", "(", "self", ",", "request", "=", "None", ")", ":", "self", ".", "connection", ".", "processed", "+=", "1", "self", ".", "producer", ".", "requests_processed", "+=", "1", "self", ".", "event", "(", "'post_request'", ")", ".", "bind", "(...
Starts processing the request for this protocol consumer. There is no need to override this method, implement :meth:`start_request` instead. If either :attr:`connection` or :attr:`transport` are missing, a :class:`RuntimeError` occurs. For server side consumer, this method simp...
[ "Starts", "processing", "the", "request", "for", "this", "protocol", "consumer", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/protocols.py#L216-L237
train
quantmind/pulsar
pulsar/utils/log.py
process_global
def process_global(name, val=None, setval=False): '''Access and set global variables for the current process.''' p = current_process() if not hasattr(p, '_pulsar_globals'): p._pulsar_globals = {'lock': Lock()} if setval: p._pulsar_globals[name] = val else: return p._pulsar_gl...
python
def process_global(name, val=None, setval=False): '''Access and set global variables for the current process.''' p = current_process() if not hasattr(p, '_pulsar_globals'): p._pulsar_globals = {'lock': Lock()} if setval: p._pulsar_globals[name] = val else: return p._pulsar_gl...
[ "def", "process_global", "(", "name", ",", "val", "=", "None", ",", "setval", "=", "False", ")", ":", "p", "=", "current_process", "(", ")", "if", "not", "hasattr", "(", "p", ",", "'_pulsar_globals'", ")", ":", "p", ".", "_pulsar_globals", "=", "{", ...
Access and set global variables for the current process.
[ "Access", "and", "set", "global", "variables", "for", "the", "current", "process", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/log.py#L213-L221
train
quantmind/pulsar
pulsar/utils/httpurl.py
get_environ_proxies
def get_environ_proxies(): """Return a dict of environment proxies. From requests_.""" proxy_keys = [ 'all', 'http', 'https', 'ftp', 'socks', 'ws', 'wss', 'no' ] def get_proxy(k): return os.environ.get(k) or os.environ.get(k.upper...
python
def get_environ_proxies(): """Return a dict of environment proxies. From requests_.""" proxy_keys = [ 'all', 'http', 'https', 'ftp', 'socks', 'ws', 'wss', 'no' ] def get_proxy(k): return os.environ.get(k) or os.environ.get(k.upper...
[ "def", "get_environ_proxies", "(", ")", ":", "proxy_keys", "=", "[", "'all'", ",", "'http'", ",", "'https'", ",", "'ftp'", ",", "'socks'", ",", "'ws'", ",", "'wss'", ",", "'no'", "]", "def", "get_proxy", "(", "k", ")", ":", "return", "os", ".", "envi...
Return a dict of environment proxies. From requests_.
[ "Return", "a", "dict", "of", "environment", "proxies", ".", "From", "requests_", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/httpurl.py#L310-L328
train
quantmind/pulsar
pulsar/utils/httpurl.py
has_vary_header
def has_vary_header(response, header_query): """ Checks to see if the response has a given header name in its Vary header. """ if not response.has_header('Vary'): return False vary_headers = cc_delim_re.split(response['Vary']) existing_headers = set([header.lower() for header in vary_hea...
python
def has_vary_header(response, header_query): """ Checks to see if the response has a given header name in its Vary header. """ if not response.has_header('Vary'): return False vary_headers = cc_delim_re.split(response['Vary']) existing_headers = set([header.lower() for header in vary_hea...
[ "def", "has_vary_header", "(", "response", ",", "header_query", ")", ":", "if", "not", "response", ".", "has_header", "(", "'Vary'", ")", ":", "return", "False", "vary_headers", "=", "cc_delim_re", ".", "split", "(", "response", "[", "'Vary'", "]", ")", "e...
Checks to see if the response has a given header name in its Vary header.
[ "Checks", "to", "see", "if", "the", "response", "has", "a", "given", "header", "name", "in", "its", "Vary", "header", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/httpurl.py#L475-L483
train
quantmind/pulsar
pulsar/apps/ds/client.py
PulsarStoreClient.execute
def execute(self, request): '''Execute a new ``request``. ''' handle = None if request: request[0] = command = to_string(request[0]).lower() info = COMMANDS_INFO.get(command) if info: handle = getattr(self.store, info.method_name) ...
python
def execute(self, request): '''Execute a new ``request``. ''' handle = None if request: request[0] = command = to_string(request[0]).lower() info = COMMANDS_INFO.get(command) if info: handle = getattr(self.store, info.method_name) ...
[ "def", "execute", "(", "self", ",", "request", ")", ":", "handle", "=", "None", "if", "request", ":", "request", "[", "0", "]", "=", "command", "=", "to_string", "(", "request", "[", "0", "]", ")", ".", "lower", "(", ")", "info", "=", "COMMANDS_INF...
Execute a new ``request``.
[ "Execute", "a", "new", "request", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ds/client.py#L65-L83
train
quantmind/pulsar
pulsar/apps/http/plugins.py
handle_cookies
def handle_cookies(response, exc=None): '''Handle response cookies. ''' if exc: return headers = response.headers request = response.request client = request.client response._cookies = c = SimpleCookie() if 'set-cookie' in headers or 'set-cookie2' in headers: for cookie i...
python
def handle_cookies(response, exc=None): '''Handle response cookies. ''' if exc: return headers = response.headers request = response.request client = request.client response._cookies = c = SimpleCookie() if 'set-cookie' in headers or 'set-cookie2' in headers: for cookie i...
[ "def", "handle_cookies", "(", "response", ",", "exc", "=", "None", ")", ":", "if", "exc", ":", "return", "headers", "=", "response", ".", "headers", "request", "=", "response", ".", "request", "client", "=", "request", ".", "client", "response", ".", "_c...
Handle response cookies.
[ "Handle", "response", "cookies", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/plugins.py#L191-L206
train
quantmind/pulsar
pulsar/apps/http/plugins.py
WebSocket.on_headers
def on_headers(self, response, exc=None): '''Websocket upgrade as ``on_headers`` event.''' if response.status_code == 101: connection = response.connection request = response.request handler = request.websocket_handler if not handler: hand...
python
def on_headers(self, response, exc=None): '''Websocket upgrade as ``on_headers`` event.''' if response.status_code == 101: connection = response.connection request = response.request handler = request.websocket_handler if not handler: hand...
[ "def", "on_headers", "(", "self", ",", "response", ",", "exc", "=", "None", ")", ":", "if", "response", ".", "status_code", "==", "101", ":", "connection", "=", "response", ".", "connection", "request", "=", "response", ".", "request", "handler", "=", "r...
Websocket upgrade as ``on_headers`` event.
[ "Websocket", "upgrade", "as", "on_headers", "event", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/plugins.py#L230-L245
train
quantmind/pulsar
pulsar/utils/path.py
Path.add2python
def add2python(self, module=None, up=0, down=None, front=False, must_exist=True): '''Add a directory to the python path. :parameter module: Optional module name to try to import once we have found the directory :parameter up: number of level to go up the directory...
python
def add2python(self, module=None, up=0, down=None, front=False, must_exist=True): '''Add a directory to the python path. :parameter module: Optional module name to try to import once we have found the directory :parameter up: number of level to go up the directory...
[ "def", "add2python", "(", "self", ",", "module", "=", "None", ",", "up", "=", "0", ",", "down", "=", "None", ",", "front", "=", "False", ",", "must_exist", "=", "True", ")", ":", "if", "module", ":", "try", ":", "return", "import_module", "(", "mod...
Add a directory to the python path. :parameter module: Optional module name to try to import once we have found the directory :parameter up: number of level to go up the directory three from :attr:`local_path`. :parameter down: Optional tuple of directory names to travel...
[ "Add", "a", "directory", "to", "the", "python", "path", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/path.py#L79-L117
train
quantmind/pulsar
examples/httpbin/manage.py
HttpBin.get
def get(self, request): '''The home page of this router''' ul = Html('ul') for router in sorted(self.routes, key=lambda r: r.creation_count): a = router.link(escape(router.route.path)) a.addClass(router.name) for method in METHODS: if router.ge...
python
def get(self, request): '''The home page of this router''' ul = Html('ul') for router in sorted(self.routes, key=lambda r: r.creation_count): a = router.link(escape(router.route.path)) a.addClass(router.name) for method in METHODS: if router.ge...
[ "def", "get", "(", "self", ",", "request", ")", ":", "ul", "=", "Html", "(", "'ul'", ")", "for", "router", "in", "sorted", "(", "self", ".", "routes", ",", "key", "=", "lambda", "r", ":", "r", ".", "creation_count", ")", ":", "a", "=", "router", ...
The home page of this router
[ "The", "home", "page", "of", "this", "router" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/httpbin/manage.py#L106-L127
train
quantmind/pulsar
examples/httpbin/manage.py
HttpBin.stats
def stats(self, request): '''Live stats for the server. Try sending lots of requests ''' # scheme = 'wss' if request.is_secure else 'ws' # host = request.get('HTTP_HOST') # address = '%s://%s/stats' % (scheme, host) doc = HtmlDocument(title='Live server stats', m...
python
def stats(self, request): '''Live stats for the server. Try sending lots of requests ''' # scheme = 'wss' if request.is_secure else 'ws' # host = request.get('HTTP_HOST') # address = '%s://%s/stats' % (scheme, host) doc = HtmlDocument(title='Live server stats', m...
[ "def", "stats", "(", "self", ",", "request", ")", ":", "doc", "=", "HtmlDocument", "(", "title", "=", "'Live server stats'", ",", "media_path", "=", "'/assets/'", ")", "return", "doc", ".", "http_response", "(", "request", ")" ]
Live stats for the server. Try sending lots of requests
[ "Live", "stats", "for", "the", "server", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/httpbin/manage.py#L273-L283
train
quantmind/pulsar
pulsar/utils/system/winprocess.py
get_preparation_data
def get_preparation_data(name): ''' Return info about parent needed by child to unpickle process object. Monkey-patch from ''' d = dict( name=name, sys_path=sys.path, sys_argv=sys.argv, log_to_stderr=_log_to_stderr, orig_dir=process.ORIGINAL_DIR, ...
python
def get_preparation_data(name): ''' Return info about parent needed by child to unpickle process object. Monkey-patch from ''' d = dict( name=name, sys_path=sys.path, sys_argv=sys.argv, log_to_stderr=_log_to_stderr, orig_dir=process.ORIGINAL_DIR, ...
[ "def", "get_preparation_data", "(", "name", ")", ":", "d", "=", "dict", "(", "name", "=", "name", ",", "sys_path", "=", "sys", ".", "path", ",", "sys_argv", "=", "sys", ".", "argv", ",", "log_to_stderr", "=", "_log_to_stderr", ",", "orig_dir", "=", "pr...
Return info about parent needed by child to unpickle process object. Monkey-patch from
[ "Return", "info", "about", "parent", "needed", "by", "child", "to", "unpickle", "process", "object", ".", "Monkey", "-", "patch", "from" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/system/winprocess.py#L9-L37
train
quantmind/pulsar
examples/snippets/remote.py
remote_call
def remote_call(request, cls, method, args, kw): '''Command for executing remote calls on a remote object ''' actor = request.actor name = 'remote_%s' % cls.__name__ if not hasattr(actor, name): object = cls(actor) setattr(actor, name, object) else: object = getattr(actor...
python
def remote_call(request, cls, method, args, kw): '''Command for executing remote calls on a remote object ''' actor = request.actor name = 'remote_%s' % cls.__name__ if not hasattr(actor, name): object = cls(actor) setattr(actor, name, object) else: object = getattr(actor...
[ "def", "remote_call", "(", "request", ",", "cls", ",", "method", ",", "args", ",", "kw", ")", ":", "actor", "=", "request", ".", "actor", "name", "=", "'remote_%s'", "%", "cls", ".", "__name__", "if", "not", "hasattr", "(", "actor", ",", "name", ")",...
Command for executing remote calls on a remote object
[ "Command", "for", "executing", "remote", "calls", "on", "a", "remote", "object" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/snippets/remote.py#L8-L19
train
quantmind/pulsar
pulsar/utils/structures/skiplist.py
Skiplist.clear
def clear(self): '''Clear the container from all data.''' self._size = 0 self._level = 1 self._head = Node('HEAD', None, [None]*SKIPLIST_MAXLEVEL, [1]*SKIPLIST_MAXLEVEL)
python
def clear(self): '''Clear the container from all data.''' self._size = 0 self._level = 1 self._head = Node('HEAD', None, [None]*SKIPLIST_MAXLEVEL, [1]*SKIPLIST_MAXLEVEL)
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_size", "=", "0", "self", ".", "_level", "=", "1", "self", ".", "_head", "=", "Node", "(", "'HEAD'", ",", "None", ",", "[", "None", "]", "*", "SKIPLIST_MAXLEVEL", ",", "[", "1", "]", "*", "SK...
Clear the container from all data.
[ "Clear", "the", "container", "from", "all", "data", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L55-L61
train
quantmind/pulsar
pulsar/utils/structures/skiplist.py
Skiplist.extend
def extend(self, iterable): '''Extend this skiplist with an iterable over ``score``, ``value`` pairs. ''' i = self.insert for score_values in iterable: i(*score_values)
python
def extend(self, iterable): '''Extend this skiplist with an iterable over ``score``, ``value`` pairs. ''' i = self.insert for score_values in iterable: i(*score_values)
[ "def", "extend", "(", "self", ",", "iterable", ")", ":", "i", "=", "self", ".", "insert", "for", "score_values", "in", "iterable", ":", "i", "(", "*", "score_values", ")" ]
Extend this skiplist with an iterable over ``score``, ``value`` pairs.
[ "Extend", "this", "skiplist", "with", "an", "iterable", "over", "score", "value", "pairs", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L63-L69
train
quantmind/pulsar
pulsar/utils/structures/skiplist.py
Skiplist.remove_range
def remove_range(self, start, end, callback=None): '''Remove a range by rank. This is equivalent to perform:: del l[start:end] on a python list. It returns the number of element removed. ''' N = len(self) if start < 0: start = max(N + st...
python
def remove_range(self, start, end, callback=None): '''Remove a range by rank. This is equivalent to perform:: del l[start:end] on a python list. It returns the number of element removed. ''' N = len(self) if start < 0: start = max(N + st...
[ "def", "remove_range", "(", "self", ",", "start", ",", "end", ",", "callback", "=", "None", ")", ":", "N", "=", "len", "(", "self", ")", "if", "start", "<", "0", ":", "start", "=", "max", "(", "N", "+", "start", ",", "0", ")", "if", "start", ...
Remove a range by rank. This is equivalent to perform:: del l[start:end] on a python list. It returns the number of element removed.
[ "Remove", "a", "range", "by", "rank", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L184-L224
train
quantmind/pulsar
pulsar/utils/structures/skiplist.py
Skiplist.remove_range_by_score
def remove_range_by_score(self, minval, maxval, include_min=True, include_max=True, callback=None): '''Remove a range with scores between ``minval`` and ``maxval``. :param minval: the start value of the range to remove :param maxval: the end value of the range to r...
python
def remove_range_by_score(self, minval, maxval, include_min=True, include_max=True, callback=None): '''Remove a range with scores between ``minval`` and ``maxval``. :param minval: the start value of the range to remove :param maxval: the end value of the range to r...
[ "def", "remove_range_by_score", "(", "self", ",", "minval", ",", "maxval", ",", "include_min", "=", "True", ",", "include_max", "=", "True", ",", "callback", "=", "None", ")", ":", "node", "=", "self", ".", "_head", "chain", "=", "[", "None", "]", "*",...
Remove a range with scores between ``minval`` and ``maxval``. :param minval: the start value of the range to remove :param maxval: the end value of the range to remove :param include_min: whether or not to include ``minval`` in the values to remove :param include_max: whethe...
[ "Remove", "a", "range", "with", "scores", "between", "minval", "and", "maxval", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L226-L263
train
quantmind/pulsar
pulsar/utils/structures/skiplist.py
Skiplist.count
def count(self, minval, maxval, include_min=True, include_max=True): '''Returns the number of elements in the skiplist with a score between min and max. ''' rank1 = self.rank(minval) if rank1 < 0: rank1 = -rank1 - 1 elif not include_min: rank1 += 1...
python
def count(self, minval, maxval, include_min=True, include_max=True): '''Returns the number of elements in the skiplist with a score between min and max. ''' rank1 = self.rank(minval) if rank1 < 0: rank1 = -rank1 - 1 elif not include_min: rank1 += 1...
[ "def", "count", "(", "self", ",", "minval", ",", "maxval", ",", "include_min", "=", "True", ",", "include_max", "=", "True", ")", ":", "rank1", "=", "self", ".", "rank", "(", "minval", ")", "if", "rank1", "<", "0", ":", "rank1", "=", "-", "rank1", ...
Returns the number of elements in the skiplist with a score between min and max.
[ "Returns", "the", "number", "of", "elements", "in", "the", "skiplist", "with", "a", "score", "between", "min", "and", "max", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/structures/skiplist.py#L265-L279
train
quantmind/pulsar
pulsar/apps/wsgi/structures.py
Accept.quality
def quality(self, key): """Returns the quality of the key. .. versionadded:: 0.6 In previous versions you had to use the item-lookup syntax (eg: ``obj[key]`` instead of ``obj.quality(key)``) """ for item, quality in self: if self._value_matches(key, ite...
python
def quality(self, key): """Returns the quality of the key. .. versionadded:: 0.6 In previous versions you had to use the item-lookup syntax (eg: ``obj[key]`` instead of ``obj.quality(key)``) """ for item, quality in self: if self._value_matches(key, ite...
[ "def", "quality", "(", "self", ",", "key", ")", ":", "for", "item", ",", "quality", "in", "self", ":", "if", "self", ".", "_value_matches", "(", "key", ",", "item", ")", ":", "return", "quality", "return", "0" ]
Returns the quality of the key. .. versionadded:: 0.6 In previous versions you had to use the item-lookup syntax (eg: ``obj[key]`` instead of ``obj.quality(key)``)
[ "Returns", "the", "quality", "of", "the", "key", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/structures.py#L54-L64
train
quantmind/pulsar
pulsar/apps/wsgi/structures.py
Accept.to_header
def to_header(self): """Convert the header set into an HTTP header string.""" result = [] for value, quality in self: if quality != 1: value = '%s;q=%s' % (value, quality) result.append(value) return ','.join(result)
python
def to_header(self): """Convert the header set into an HTTP header string.""" result = [] for value, quality in self: if quality != 1: value = '%s;q=%s' % (value, quality) result.append(value) return ','.join(result)
[ "def", "to_header", "(", "self", ")", ":", "result", "=", "[", "]", "for", "value", ",", "quality", "in", "self", ":", "if", "quality", "!=", "1", ":", "value", "=", "'%s;q=%s'", "%", "(", "value", ",", "quality", ")", "result", ".", "append", "(",...
Convert the header set into an HTTP header string.
[ "Convert", "the", "header", "set", "into", "an", "HTTP", "header", "string", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/structures.py#L109-L116
train
quantmind/pulsar
pulsar/apps/wsgi/structures.py
Accept.best_match
def best_match(self, matches, default=None): """Returns the best match from a list of possible matches based on the quality of the client. If two items have the same quality, the one is returned that comes first. :param matches: a list of matches to check for :param default: th...
python
def best_match(self, matches, default=None): """Returns the best match from a list of possible matches based on the quality of the client. If two items have the same quality, the one is returned that comes first. :param matches: a list of matches to check for :param default: th...
[ "def", "best_match", "(", "self", ",", "matches", ",", "default", "=", "None", ")", ":", "if", "matches", ":", "best_quality", "=", "-", "1", "result", "=", "default", "for", "client_item", ",", "quality", "in", "self", ":", "for", "server_item", "in", ...
Returns the best match from a list of possible matches based on the quality of the client. If two items have the same quality, the one is returned that comes first. :param matches: a list of matches to check for :param default: the value that is returned if none match
[ "Returns", "the", "best", "match", "from", "a", "list", "of", "possible", "matches", "based", "on", "the", "quality", "of", "the", "client", ".", "If", "two", "items", "have", "the", "same", "quality", "the", "one", "is", "returned", "that", "comes", "fi...
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/structures.py#L121-L141
train
quantmind/pulsar
pulsar/utils/system/__init__.py
convert_bytes
def convert_bytes(b): '''Convert a number of bytes into a human readable memory usage, bytes, kilo, mega, giga, tera, peta, exa, zetta, yotta''' if b is None: return '#NA' for s in reversed(memory_symbols): if b >= memory_size[s]: value = float(b) / memory_size[s] ret...
python
def convert_bytes(b): '''Convert a number of bytes into a human readable memory usage, bytes, kilo, mega, giga, tera, peta, exa, zetta, yotta''' if b is None: return '#NA' for s in reversed(memory_symbols): if b >= memory_size[s]: value = float(b) / memory_size[s] ret...
[ "def", "convert_bytes", "(", "b", ")", ":", "if", "b", "is", "None", ":", "return", "'#NA'", "for", "s", "in", "reversed", "(", "memory_symbols", ")", ":", "if", "b", ">=", "memory_size", "[", "s", "]", ":", "value", "=", "float", "(", "b", ")", ...
Convert a number of bytes into a human readable memory usage, bytes, kilo, mega, giga, tera, peta, exa, zetta, yotta
[ "Convert", "a", "number", "of", "bytes", "into", "a", "human", "readable", "memory", "usage", "bytes", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/system/__init__.py#L32-L41
train
quantmind/pulsar
pulsar/utils/system/__init__.py
process_info
def process_info(pid=None): '''Returns a dictionary of system information for the process ``pid``. It uses the psutil_ module for the purpose. If psutil_ is not available it returns an empty dictionary. .. _psutil: http://code.google.com/p/psutil/ ''' if psutil is None: # pragma nocover ...
python
def process_info(pid=None): '''Returns a dictionary of system information for the process ``pid``. It uses the psutil_ module for the purpose. If psutil_ is not available it returns an empty dictionary. .. _psutil: http://code.google.com/p/psutil/ ''' if psutil is None: # pragma nocover ...
[ "def", "process_info", "(", "pid", "=", "None", ")", ":", "if", "psutil", "is", "None", ":", "return", "{", "}", "pid", "=", "pid", "or", "os", ".", "getpid", "(", ")", "try", ":", "p", "=", "psutil", ".", "Process", "(", "pid", ")", "except", ...
Returns a dictionary of system information for the process ``pid``. It uses the psutil_ module for the purpose. If psutil_ is not available it returns an empty dictionary. .. _psutil: http://code.google.com/p/psutil/
[ "Returns", "a", "dictionary", "of", "system", "information", "for", "the", "process", "pid", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/system/__init__.py#L44-L66
train
quantmind/pulsar
pulsar/async/protocols.py
TcpServer.start_serving
async def start_serving(self, address=None, sockets=None, backlog=100, sslcontext=None): """Start serving. :param address: optional address to bind to :param sockets: optional list of sockets to bind to :param backlog: Number of maximum connections :p...
python
async def start_serving(self, address=None, sockets=None, backlog=100, sslcontext=None): """Start serving. :param address: optional address to bind to :param sockets: optional list of sockets to bind to :param backlog: Number of maximum connections :p...
[ "async", "def", "start_serving", "(", "self", ",", "address", "=", "None", ",", "sockets", "=", "None", ",", "backlog", "=", "100", ",", "sslcontext", "=", "None", ")", ":", "if", "self", ".", "_server", ":", "raise", "RuntimeError", "(", "'Already servi...
Start serving. :param address: optional address to bind to :param sockets: optional list of sockets to bind to :param backlog: Number of maximum connections :param sslcontext: optional SSLContext object
[ "Start", "serving", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/protocols.py#L212-L243
train
quantmind/pulsar
pulsar/async/protocols.py
TcpServer._close_connections
def _close_connections(self, connection=None, timeout=5): """Close ``connection`` if specified, otherwise close all connections. Return a list of :class:`.Future` called back once the connection/s are closed. """ all = [] if connection: waiter = connection.ev...
python
def _close_connections(self, connection=None, timeout=5): """Close ``connection`` if specified, otherwise close all connections. Return a list of :class:`.Future` called back once the connection/s are closed. """ all = [] if connection: waiter = connection.ev...
[ "def", "_close_connections", "(", "self", ",", "connection", "=", "None", ",", "timeout", "=", "5", ")", ":", "all", "=", "[", "]", "if", "connection", ":", "waiter", "=", "connection", ".", "event", "(", "'connection_lost'", ")", ".", "waiter", "(", "...
Close ``connection`` if specified, otherwise close all connections. Return a list of :class:`.Future` called back once the connection/s are closed.
[ "Close", "connection", "if", "specified", "otherwise", "close", "all", "connections", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/protocols.py#L282-L304
train
quantmind/pulsar
pulsar/async/protocols.py
DatagramServer.start_serving
async def start_serving(self, address=None, sockets=None, **kw): """create the server endpoint. """ if self._server: raise RuntimeError('Already serving') server = DGServer(self._loop) loop = self._loop if sockets: for sock in sockets: ...
python
async def start_serving(self, address=None, sockets=None, **kw): """create the server endpoint. """ if self._server: raise RuntimeError('Already serving') server = DGServer(self._loop) loop = self._loop if sockets: for sock in sockets: ...
[ "async", "def", "start_serving", "(", "self", ",", "address", "=", "None", ",", "sockets", "=", "None", ",", "**", "kw", ")", ":", "if", "self", ".", "_server", ":", "raise", "RuntimeError", "(", "'Already serving'", ")", "server", "=", "DGServer", "(", ...
create the server endpoint.
[ "create", "the", "server", "endpoint", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/protocols.py#L333-L351
train
quantmind/pulsar
pulsar/apps/socket/__init__.py
SocketServer.monitor_start
async def monitor_start(self, monitor): '''Create the socket listening to the ``bind`` address. If the platform does not support multiprocessing sockets set the number of workers to 0. ''' cfg = self.cfg if (not platform.has_multiprocessing_socket or cfg....
python
async def monitor_start(self, monitor): '''Create the socket listening to the ``bind`` address. If the platform does not support multiprocessing sockets set the number of workers to 0. ''' cfg = self.cfg if (not platform.has_multiprocessing_socket or cfg....
[ "async", "def", "monitor_start", "(", "self", ",", "monitor", ")", ":", "cfg", "=", "self", ".", "cfg", "if", "(", "not", "platform", ".", "has_multiprocessing_socket", "or", "cfg", ".", "concurrency", "==", "'thread'", ")", ":", "cfg", ".", "set", "(", ...
Create the socket listening to the ``bind`` address. If the platform does not support multiprocessing sockets set the number of workers to 0.
[ "Create", "the", "socket", "listening", "to", "the", "bind", "address", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/socket/__init__.py#L256-L273
train
quantmind/pulsar
pulsar/apps/socket/__init__.py
SocketServer.create_server
async def create_server(self, worker, protocol_factory, address=None, sockets=None, idx=0): '''Create the Server which will listen for requests. :return: a :class:`.TcpServer`. ''' cfg = self.cfg max_requests = cfg.max_requests if max_requests...
python
async def create_server(self, worker, protocol_factory, address=None, sockets=None, idx=0): '''Create the Server which will listen for requests. :return: a :class:`.TcpServer`. ''' cfg = self.cfg max_requests = cfg.max_requests if max_requests...
[ "async", "def", "create_server", "(", "self", ",", "worker", ",", "protocol_factory", ",", "address", "=", "None", ",", "sockets", "=", "None", ",", "idx", "=", "0", ")", ":", "cfg", "=", "self", ".", "cfg", "max_requests", "=", "cfg", ".", "max_reques...
Create the Server which will listen for requests. :return: a :class:`.TcpServer`.
[ "Create", "the", "Server", "which", "will", "listen", "for", "requests", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/socket/__init__.py#L306-L338
train
quantmind/pulsar
pulsar/apps/data/redis/pubsub.py
RedisPubSub.channels
def channels(self, pattern=None): '''Lists the currently active channels matching ``pattern`` ''' if pattern: return self.store.execute('PUBSUB', 'CHANNELS', pattern) else: return self.store.execute('PUBSUB', 'CHANNELS')
python
def channels(self, pattern=None): '''Lists the currently active channels matching ``pattern`` ''' if pattern: return self.store.execute('PUBSUB', 'CHANNELS', pattern) else: return self.store.execute('PUBSUB', 'CHANNELS')
[ "def", "channels", "(", "self", ",", "pattern", "=", "None", ")", ":", "if", "pattern", ":", "return", "self", ".", "store", ".", "execute", "(", "'PUBSUB'", ",", "'CHANNELS'", ",", "pattern", ")", "else", ":", "return", "self", ".", "store", ".", "e...
Lists the currently active channels matching ``pattern``
[ "Lists", "the", "currently", "active", "channels", "matching", "pattern" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/pubsub.py#L45-L51
train
quantmind/pulsar
pulsar/apps/data/redis/pubsub.py
RedisChannels.lock
def lock(self, name, **kwargs): """Global distributed lock """ return self.pubsub.store.client().lock(self.prefixed(name), **kwargs)
python
def lock(self, name, **kwargs): """Global distributed lock """ return self.pubsub.store.client().lock(self.prefixed(name), **kwargs)
[ "def", "lock", "(", "self", ",", "name", ",", "**", "kwargs", ")", ":", "return", "self", ".", "pubsub", ".", "store", ".", "client", "(", ")", ".", "lock", "(", "self", ".", "prefixed", "(", "name", ")", ",", "**", "kwargs", ")" ]
Global distributed lock
[ "Global", "distributed", "lock" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/pubsub.py#L104-L107
train
quantmind/pulsar
pulsar/apps/data/redis/pubsub.py
RedisChannels.publish
async def publish(self, channel, event, data=None): """Publish a new ``event`` on a ``channel`` :param channel: channel name :param event: event name :param data: optional payload to include in the event :return: a coroutine and therefore it must be awaited """ m...
python
async def publish(self, channel, event, data=None): """Publish a new ``event`` on a ``channel`` :param channel: channel name :param event: event name :param data: optional payload to include in the event :return: a coroutine and therefore it must be awaited """ m...
[ "async", "def", "publish", "(", "self", ",", "channel", ",", "event", ",", "data", "=", "None", ")", ":", "msg", "=", "{", "'event'", ":", "event", ",", "'channel'", ":", "channel", "}", "if", "data", ":", "msg", "[", "'data'", "]", "=", "data", ...
Publish a new ``event`` on a ``channel`` :param channel: channel name :param event: event name :param data: optional payload to include in the event :return: a coroutine and therefore it must be awaited
[ "Publish", "a", "new", "event", "on", "a", "channel" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/pubsub.py#L109-L130
train
quantmind/pulsar
pulsar/apps/data/redis/pubsub.py
RedisChannels.close
async def close(self): """Close channels and underlying pubsub handler :return: a coroutine and therefore it must be awaited """ push_connection = self.pubsub.push_connection self.status = self.statusType.closed if push_connection: push_connection.event('conn...
python
async def close(self): """Close channels and underlying pubsub handler :return: a coroutine and therefore it must be awaited """ push_connection = self.pubsub.push_connection self.status = self.statusType.closed if push_connection: push_connection.event('conn...
[ "async", "def", "close", "(", "self", ")", ":", "push_connection", "=", "self", ".", "pubsub", ".", "push_connection", "self", ".", "status", "=", "self", ".", "statusType", ".", "closed", "if", "push_connection", ":", "push_connection", ".", "event", "(", ...
Close channels and underlying pubsub handler :return: a coroutine and therefore it must be awaited
[ "Close", "channels", "and", "underlying", "pubsub", "handler" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/pubsub.py#L140-L151
train
quantmind/pulsar
pulsar/apps/http/client.py
RequestBase.origin_req_host
def origin_req_host(self): """Required by Cookies handlers """ if self.history: return self.history[0].request.origin_req_host else: return scheme_host_port(self.url)[1]
python
def origin_req_host(self): """Required by Cookies handlers """ if self.history: return self.history[0].request.origin_req_host else: return scheme_host_port(self.url)[1]
[ "def", "origin_req_host", "(", "self", ")", ":", "if", "self", ".", "history", ":", "return", "self", ".", "history", "[", "0", "]", ".", "request", ".", "origin_req_host", "else", ":", "return", "scheme_host_port", "(", "self", ".", "url", ")", "[", "...
Required by Cookies handlers
[ "Required", "by", "Cookies", "handlers" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L119-L125
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpRequest.get_header
def get_header(self, header_name, default=None): """Retrieve ``header_name`` from this request headers. """ return self.headers.get( header_name, self.unredirected_headers.get(header_name, default))
python
def get_header(self, header_name, default=None): """Retrieve ``header_name`` from this request headers. """ return self.headers.get( header_name, self.unredirected_headers.get(header_name, default))
[ "def", "get_header", "(", "self", ",", "header_name", ",", "default", "=", "None", ")", ":", "return", "self", ".", "headers", ".", "get", "(", "header_name", ",", "self", ".", "unredirected_headers", ".", "get", "(", "header_name", ",", "default", ")", ...
Retrieve ``header_name`` from this request headers.
[ "Retrieve", "header_name", "from", "this", "request", "headers", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L325-L329
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpRequest.remove_header
def remove_header(self, header_name): """Remove ``header_name`` from this request. """ val1 = self.headers.pop(header_name, None) val2 = self.unredirected_headers.pop(header_name, None) return val1 or val2
python
def remove_header(self, header_name): """Remove ``header_name`` from this request. """ val1 = self.headers.pop(header_name, None) val2 = self.unredirected_headers.pop(header_name, None) return val1 or val2
[ "def", "remove_header", "(", "self", ",", "header_name", ")", ":", "val1", "=", "self", ".", "headers", ".", "pop", "(", "header_name", ",", "None", ")", "val2", "=", "self", ".", "unredirected_headers", ".", "pop", "(", "header_name", ",", "None", ")", ...
Remove ``header_name`` from this request.
[ "Remove", "header_name", "from", "this", "request", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L331-L336
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpResponse.raw
def raw(self): """A raw asynchronous Http response """ if self._raw is None: self._raw = HttpStream(self) return self._raw
python
def raw(self): """A raw asynchronous Http response """ if self._raw is None: self._raw = HttpStream(self) return self._raw
[ "def", "raw", "(", "self", ")", ":", "if", "self", ".", "_raw", "is", "None", ":", "self", ".", "_raw", "=", "HttpStream", "(", "self", ")", "return", "self", ".", "_raw" ]
A raw asynchronous Http response
[ "A", "raw", "asynchronous", "Http", "response" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L539-L544
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpResponse.links
def links(self): """Returns the parsed header links of the response, if any """ headers = self.headers or {} header = headers.get('link') li = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel')...
python
def links(self): """Returns the parsed header links of the response, if any """ headers = self.headers or {} header = headers.get('link') li = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel')...
[ "def", "links", "(", "self", ")", ":", "headers", "=", "self", ".", "headers", "or", "{", "}", "header", "=", "headers", ".", "get", "(", "'link'", ")", "li", "=", "{", "}", "if", "header", ":", "links", "=", "parse_header_links", "(", "header", ")...
Returns the parsed header links of the response, if any
[ "Returns", "the", "parsed", "header", "links", "of", "the", "response", "if", "any" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L547-L558
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpResponse.text
def text(self): """Decode content as a string. """ data = self.content return data.decode(self.encoding or 'utf-8') if data else ''
python
def text(self): """Decode content as a string. """ data = self.content return data.decode(self.encoding or 'utf-8') if data else ''
[ "def", "text", "(", "self", ")", ":", "data", "=", "self", ".", "content", "return", "data", ".", "decode", "(", "self", ".", "encoding", "or", "'utf-8'", ")", "if", "data", "else", "''" ]
Decode content as a string.
[ "Decode", "content", "as", "a", "string", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L565-L569
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpResponse.decode_content
def decode_content(self): """Return the best possible representation of the response body. """ ct = self.headers.get('content-type') if ct: ct, options = parse_options_header(ct) charset = options.get('charset') if ct in JSON_CONTENT_TYPES: ...
python
def decode_content(self): """Return the best possible representation of the response body. """ ct = self.headers.get('content-type') if ct: ct, options = parse_options_header(ct) charset = options.get('charset') if ct in JSON_CONTENT_TYPES: ...
[ "def", "decode_content", "(", "self", ")", ":", "ct", "=", "self", ".", "headers", ".", "get", "(", "'content-type'", ")", "if", "ct", ":", "ct", ",", "options", "=", "parse_options_header", "(", "ct", ")", "charset", "=", "options", ".", "get", "(", ...
Return the best possible representation of the response body.
[ "Return", "the", "best", "possible", "representation", "of", "the", "response", "body", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L576-L590
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpClient.request
def request(self, method, url, **params): """Constructs and sends a request to a remote server. It returns a :class:`.Future` which results in a :class:`.HttpResponse` object. :param method: request method for the :class:`HttpRequest`. :param url: URL for the :class:`HttpReques...
python
def request(self, method, url, **params): """Constructs and sends a request to a remote server. It returns a :class:`.Future` which results in a :class:`.HttpResponse` object. :param method: request method for the :class:`HttpRequest`. :param url: URL for the :class:`HttpReques...
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "**", "params", ")", ":", "response", "=", "self", ".", "_request", "(", "method", ",", "url", ",", "**", "params", ")", "if", "not", "self", ".", "_loop", ".", "is_running", "(", ")", ...
Constructs and sends a request to a remote server. It returns a :class:`.Future` which results in a :class:`.HttpResponse` object. :param method: request method for the :class:`HttpRequest`. :param url: URL for the :class:`HttpRequest`. :param params: optional parameters for th...
[ "Constructs", "and", "sends", "a", "request", "to", "a", "remote", "server", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L864-L881
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpClient.ssl_context
def ssl_context(self, verify=True, cert_reqs=None, check_hostname=False, certfile=None, keyfile=None, cafile=None, capath=None, cadata=None, **kw): """Create a SSL context object. This method should not be called by from user code """ assert ssl, ...
python
def ssl_context(self, verify=True, cert_reqs=None, check_hostname=False, certfile=None, keyfile=None, cafile=None, capath=None, cadata=None, **kw): """Create a SSL context object. This method should not be called by from user code """ assert ssl, ...
[ "def", "ssl_context", "(", "self", ",", "verify", "=", "True", ",", "cert_reqs", "=", "None", ",", "check_hostname", "=", "False", ",", "certfile", "=", "None", ",", "keyfile", "=", "None", ",", "cafile", "=", "None", ",", "capath", "=", "None", ",", ...
Create a SSL context object. This method should not be called by from user code
[ "Create", "a", "SSL", "context", "object", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L972-L999
train
quantmind/pulsar
pulsar/apps/http/client.py
HttpClient.create_tunnel_connection
async def create_tunnel_connection(self, req): """Create a tunnel connection """ tunnel_address = req.tunnel_address connection = await self.create_connection(tunnel_address) response = connection.current_consumer() for event in response.events().values(): eve...
python
async def create_tunnel_connection(self, req): """Create a tunnel connection """ tunnel_address = req.tunnel_address connection = await self.create_connection(tunnel_address) response = connection.current_consumer() for event in response.events().values(): eve...
[ "async", "def", "create_tunnel_connection", "(", "self", ",", "req", ")", ":", "tunnel_address", "=", "req", ".", "tunnel_address", "connection", "=", "await", "self", ".", "create_connection", "(", "tunnel_address", ")", "response", "=", "connection", ".", "cur...
Create a tunnel connection
[ "Create", "a", "tunnel", "connection" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L1004-L1032
train
quantmind/pulsar
pulsar/apps/__init__.py
Configurator.python_path
def python_path(self, script): """Called during initialisation to obtain the ``script`` name. If ``script`` does not evaluate to ``True`` it is evaluated from the ``__main__`` import. Returns the real path of the python script which runs the application. """ if not scrip...
python
def python_path(self, script): """Called during initialisation to obtain the ``script`` name. If ``script`` does not evaluate to ``True`` it is evaluated from the ``__main__`` import. Returns the real path of the python script which runs the application. """ if not scrip...
[ "def", "python_path", "(", "self", ",", "script", ")", ":", "if", "not", "script", ":", "try", ":", "import", "__main__", "script", "=", "getfile", "(", "__main__", ")", "except", "Exception", ":", "return", "script", "=", "os", ".", "path", ".", "real...
Called during initialisation to obtain the ``script`` name. If ``script`` does not evaluate to ``True`` it is evaluated from the ``__main__`` import. Returns the real path of the python script which runs the application.
[ "Called", "during", "initialisation", "to", "obtain", "the", "script", "name", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/__init__.py#L291-L309
train
quantmind/pulsar
pulsar/apps/__init__.py
Configurator.start
def start(self, exit=True): """Invoked the application callable method and start the ``arbiter`` if it wasn't already started. It returns a :class:`~asyncio.Future` called back once the application/applications are running. It returns ``None`` if called more than once. "...
python
def start(self, exit=True): """Invoked the application callable method and start the ``arbiter`` if it wasn't already started. It returns a :class:`~asyncio.Future` called back once the application/applications are running. It returns ``None`` if called more than once. "...
[ "def", "start", "(", "self", ",", "exit", "=", "True", ")", ":", "on_start", "=", "self", "(", ")", "actor", "=", "arbiter", "(", ")", "if", "actor", "and", "on_start", ":", "actor", ".", "start", "(", "exit", "=", "exit", ")", "if", "actor", "."...
Invoked the application callable method and start the ``arbiter`` if it wasn't already started. It returns a :class:`~asyncio.Future` called back once the application/applications are running. It returns ``None`` if called more than once.
[ "Invoked", "the", "application", "callable", "method", "and", "start", "the", "arbiter", "if", "it", "wasn", "t", "already", "started", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/__init__.py#L355-L369
train
quantmind/pulsar
pulsar/apps/__init__.py
Application.stop
def stop(self, actor=None): """Stop the application """ if actor is None: actor = get_actor() if actor and actor.is_arbiter(): monitor = actor.get_actor(self.name) if monitor: return monitor.stop() raise RuntimeError('Cannot sto...
python
def stop(self, actor=None): """Stop the application """ if actor is None: actor = get_actor() if actor and actor.is_arbiter(): monitor = actor.get_actor(self.name) if monitor: return monitor.stop() raise RuntimeError('Cannot sto...
[ "def", "stop", "(", "self", ",", "actor", "=", "None", ")", ":", "if", "actor", "is", "None", ":", "actor", "=", "get_actor", "(", ")", "if", "actor", "and", "actor", ".", "is_arbiter", "(", ")", ":", "monitor", "=", "actor", ".", "get_actor", "(",...
Stop the application
[ "Stop", "the", "application" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/__init__.py#L493-L502
train
quantmind/pulsar
pulsar/utils/system/posixsystem.py
set_owner_process
def set_owner_process(uid, gid): """ set user and group of workers processes """ if gid: try: os.setgid(gid) except OverflowError: # versions of python < 2.6.2 don't manage unsigned int for # groups like on osx or fedora os.setgid(-ctypes.c_int(-gi...
python
def set_owner_process(uid, gid): """ set user and group of workers processes """ if gid: try: os.setgid(gid) except OverflowError: # versions of python < 2.6.2 don't manage unsigned int for # groups like on osx or fedora os.setgid(-ctypes.c_int(-gi...
[ "def", "set_owner_process", "(", "uid", ",", "gid", ")", ":", "if", "gid", ":", "try", ":", "os", ".", "setgid", "(", "gid", ")", "except", "OverflowError", ":", "os", ".", "setgid", "(", "-", "ctypes", ".", "c_int", "(", "-", "gid", ")", ".", "v...
set user and group of workers processes
[ "set", "user", "and", "group", "of", "workers", "processes" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/system/posixsystem.py#L77-L87
train
quantmind/pulsar
pulsar/apps/greenio/utils.py
wait
def wait(value, must_be_child=False): '''Wait for a possible asynchronous value to complete. ''' current = getcurrent() parent = current.parent if must_be_child and not parent: raise MustBeInChildGreenlet('Cannot wait on main greenlet') return parent.switch(value) if parent else value
python
def wait(value, must_be_child=False): '''Wait for a possible asynchronous value to complete. ''' current = getcurrent() parent = current.parent if must_be_child and not parent: raise MustBeInChildGreenlet('Cannot wait on main greenlet') return parent.switch(value) if parent else value
[ "def", "wait", "(", "value", ",", "must_be_child", "=", "False", ")", ":", "current", "=", "getcurrent", "(", ")", "parent", "=", "current", ".", "parent", "if", "must_be_child", "and", "not", "parent", ":", "raise", "MustBeInChildGreenlet", "(", "'Cannot wa...
Wait for a possible asynchronous value to complete.
[ "Wait", "for", "a", "possible", "asynchronous", "value", "to", "complete", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/greenio/utils.py#L17-L24
train
quantmind/pulsar
pulsar/apps/greenio/utils.py
run_in_greenlet
def run_in_greenlet(callable): """Decorator to run a ``callable`` on a new greenlet. A ``callable`` decorated with this decorator returns a coroutine """ @wraps(callable) async def _(*args, **kwargs): green = greenlet(callable) # switch to the new greenlet result = green.swi...
python
def run_in_greenlet(callable): """Decorator to run a ``callable`` on a new greenlet. A ``callable`` decorated with this decorator returns a coroutine """ @wraps(callable) async def _(*args, **kwargs): green = greenlet(callable) # switch to the new greenlet result = green.swi...
[ "def", "run_in_greenlet", "(", "callable", ")", ":", "@", "wraps", "(", "callable", ")", "async", "def", "_", "(", "*", "args", ",", "**", "kwargs", ")", ":", "green", "=", "greenlet", "(", "callable", ")", "result", "=", "green", ".", "switch", "(",...
Decorator to run a ``callable`` on a new greenlet. A ``callable`` decorated with this decorator returns a coroutine
[ "Decorator", "to", "run", "a", "callable", "on", "a", "new", "greenlet", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/greenio/utils.py#L27-L48
train
litaotao/IPython-Dashboard
dashboard/server/utils.py
build_response
def build_response(content, code=200): """Build response, add headers""" response = make_response( jsonify(content), content['code'] ) response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Headers'] = \ 'Origin, X-Requested-With, Content-Type, Accept, A...
python
def build_response(content, code=200): """Build response, add headers""" response = make_response( jsonify(content), content['code'] ) response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Headers'] = \ 'Origin, X-Requested-With, Content-Type, Accept, A...
[ "def", "build_response", "(", "content", ",", "code", "=", "200", ")", ":", "response", "=", "make_response", "(", "jsonify", "(", "content", ")", ",", "content", "[", "'code'", "]", ")", "response", ".", "headers", "[", "'Access-Control-Allow-Origin'", "]",...
Build response, add headers
[ "Build", "response", "add", "headers" ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/utils.py#L18-L24
train
litaotao/IPython-Dashboard
dashboard/server/resources/sql.py
SqlData.post
def post(self): '''return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result. ''' ## format sql data = request.get_json() options, sql_raw = dat...
python
def post(self): '''return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result. ''' ## format sql data = request.get_json() options, sql_raw = dat...
[ "def", "post", "(", "self", ")", ":", "data", "=", "request", ".", "get_json", "(", ")", "options", ",", "sql_raw", "=", "data", ".", "get", "(", "'options'", ")", ",", "data", ".", "get", "(", "'sql_raw'", ")", "if", "options", "==", "'format'", "...
return executed sql result to client. post data format: {"options": ['all', 'last', 'first', 'format'], "sql_raw": "raw sql ..."} Returns: sql result.
[ "return", "executed", "sql", "result", "to", "client", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/sql.py#L40-L75
train
litaotao/IPython-Dashboard
dashboard/server/resources/home.py
DashListData.get
def get(self, page=0, size=10): """Get dashboard meta info from in page `page` and page size is `size`. Args: page: page number. size: size number. Returns: list of dict containing the dash_id and accordingly meta info. maybe empty list [] when p...
python
def get(self, page=0, size=10): """Get dashboard meta info from in page `page` and page size is `size`. Args: page: page number. size: size number. Returns: list of dict containing the dash_id and accordingly meta info. maybe empty list [] when p...
[ "def", "get", "(", "self", ",", "page", "=", "0", ",", "size", "=", "10", ")", ":", "dash_list", "=", "r_db", ".", "zrevrange", "(", "config", ".", "DASH_ID_KEY", ",", "0", ",", "-", "1", ",", "True", ")", "id_list", "=", "dash_list", "[", "page"...
Get dashboard meta info from in page `page` and page size is `size`. Args: page: page number. size: size number. Returns: list of dict containing the dash_id and accordingly meta info. maybe empty list [] when page * size > total dashes in db. that's rea...
[ "Get", "dashboard", "meta", "info", "from", "in", "page", "page", "and", "page", "size", "is", "size", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/home.py#L72-L91
train
litaotao/IPython-Dashboard
dashboard/server/resources/storage.py
KeyList.get
def get(self): """Get key list in storage. """ keys = r_kv.keys() keys.sort() return build_response(dict(data=keys, code=200))
python
def get(self): """Get key list in storage. """ keys = r_kv.keys() keys.sort() return build_response(dict(data=keys, code=200))
[ "def", "get", "(", "self", ")", ":", "keys", "=", "r_kv", ".", "keys", "(", ")", "keys", ".", "sort", "(", ")", "return", "build_response", "(", "dict", "(", "data", "=", "keys", ",", "code", "=", "200", ")", ")" ]
Get key list in storage.
[ "Get", "key", "list", "in", "storage", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/storage.py#L23-L28
train
litaotao/IPython-Dashboard
dashboard/server/resources/storage.py
Key.get
def get(self, key): """Get a key-value from storage according to the key name. """ data = r_kv.get(key) # data = json.dumps(data) if isinstance(data, str) else data # data = json.loads(data) if data else {} return build_response(dict(data=data, code=200))
python
def get(self, key): """Get a key-value from storage according to the key name. """ data = r_kv.get(key) # data = json.dumps(data) if isinstance(data, str) else data # data = json.loads(data) if data else {} return build_response(dict(data=data, code=200))
[ "def", "get", "(", "self", ",", "key", ")", ":", "data", "=", "r_kv", ".", "get", "(", "key", ")", "return", "build_response", "(", "dict", "(", "data", "=", "data", ",", "code", "=", "200", ")", ")" ]
Get a key-value from storage according to the key name.
[ "Get", "a", "key", "-", "value", "from", "storage", "according", "to", "the", "key", "name", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/storage.py#L40-L47
train
litaotao/IPython-Dashboard
dashboard/server/resources/dash.py
Dash.get
def get(self, dash_id): """Just return the dashboard id in the rendering html. JS will do other work [ajax and rendering] according to the dash_id. Args: dash_id: dashboard id. Returns: rendered html. """ return make_response(render_template('da...
python
def get(self, dash_id): """Just return the dashboard id in the rendering html. JS will do other work [ajax and rendering] according to the dash_id. Args: dash_id: dashboard id. Returns: rendered html. """ return make_response(render_template('da...
[ "def", "get", "(", "self", ",", "dash_id", ")", ":", "return", "make_response", "(", "render_template", "(", "'dashboard.html'", ",", "dash_id", "=", "dash_id", ",", "api_root", "=", "config", ".", "app_host", ")", ")" ]
Just return the dashboard id in the rendering html. JS will do other work [ajax and rendering] according to the dash_id. Args: dash_id: dashboard id. Returns: rendered html.
[ "Just", "return", "the", "dashboard", "id", "in", "the", "rendering", "html", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/dash.py#L25-L36
train
litaotao/IPython-Dashboard
dashboard/server/resources/dash.py
DashData.get
def get(self, dash_id): """Read dashboard content. Args: dash_id: dashboard id. Returns: A dict containing the content of that dashboard, not include the meta info. """ data = json.loads(r_db.hmget(config.DASH_CONTENT_KEY, dash_id)[0]) return bui...
python
def get(self, dash_id): """Read dashboard content. Args: dash_id: dashboard id. Returns: A dict containing the content of that dashboard, not include the meta info. """ data = json.loads(r_db.hmget(config.DASH_CONTENT_KEY, dash_id)[0]) return bui...
[ "def", "get", "(", "self", ",", "dash_id", ")", ":", "data", "=", "json", ".", "loads", "(", "r_db", ".", "hmget", "(", "config", ".", "DASH_CONTENT_KEY", ",", "dash_id", ")", "[", "0", "]", ")", "return", "build_response", "(", "dict", "(", "data", ...
Read dashboard content. Args: dash_id: dashboard id. Returns: A dict containing the content of that dashboard, not include the meta info.
[ "Read", "dashboard", "content", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/dash.py#L46-L56
train
litaotao/IPython-Dashboard
dashboard/server/resources/dash.py
DashData.put
def put(self, dash_id=0): """Update a dash meta and content, return updated dash content. Args: dash_id: dashboard id. Returns: A dict containing the updated content of that dashboard, not include the meta info. """ data = request.get_json() upda...
python
def put(self, dash_id=0): """Update a dash meta and content, return updated dash content. Args: dash_id: dashboard id. Returns: A dict containing the updated content of that dashboard, not include the meta info. """ data = request.get_json() upda...
[ "def", "put", "(", "self", ",", "dash_id", "=", "0", ")", ":", "data", "=", "request", ".", "get_json", "(", ")", "updated", "=", "self", ".", "_update_dash", "(", "dash_id", ",", "data", ")", "return", "build_response", "(", "dict", "(", "data", "="...
Update a dash meta and content, return updated dash content. Args: dash_id: dashboard id. Returns: A dict containing the updated content of that dashboard, not include the meta info.
[ "Update", "a", "dash", "meta", "and", "content", "return", "updated", "dash", "content", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/dash.py#L58-L69
train
litaotao/IPython-Dashboard
dashboard/server/resources/dash.py
DashData.delete
def delete(self, dash_id): """Delete a dash meta and content, return updated dash content. Actually, just remove it to a specfied place in database. Args: dash_id: dashboard id. Returns: Redirect to home page. """ removed_info = dict( ...
python
def delete(self, dash_id): """Delete a dash meta and content, return updated dash content. Actually, just remove it to a specfied place in database. Args: dash_id: dashboard id. Returns: Redirect to home page. """ removed_info = dict( ...
[ "def", "delete", "(", "self", ",", "dash_id", ")", ":", "removed_info", "=", "dict", "(", "time_modified", "=", "r_db", ".", "zscore", "(", "config", ".", "DASH_ID_KEY", ",", "dash_id", ")", ",", "meta", "=", "r_db", ".", "hget", "(", "config", ".", ...
Delete a dash meta and content, return updated dash content. Actually, just remove it to a specfied place in database. Args: dash_id: dashboard id. Returns: Redirect to home page.
[ "Delete", "a", "dash", "meta", "and", "content", "return", "updated", "dash", "content", "." ]
b28a6b447c86bcec562e554efe96c64660ddf7a2
https://github.com/litaotao/IPython-Dashboard/blob/b28a6b447c86bcec562e554efe96c64660ddf7a2/dashboard/server/resources/dash.py#L71-L89
train
totalgood/nlpia
src/nlpia/translate.py
main
def main( lang='deu', n=900, epochs=50, batch_size=64, num_neurons=256, encoder_input_data=None, decoder_input_data=None, decoder_target_data=None, checkpoint_dir=os.path.join(BIGDATA_PATH, 'checkpoints'), ): """ Train an LSTM encoder-decoder squence-to-sequence model...
python
def main( lang='deu', n=900, epochs=50, batch_size=64, num_neurons=256, encoder_input_data=None, decoder_input_data=None, decoder_target_data=None, checkpoint_dir=os.path.join(BIGDATA_PATH, 'checkpoints'), ): """ Train an LSTM encoder-decoder squence-to-sequence model...
[ "def", "main", "(", "lang", "=", "'deu'", ",", "n", "=", "900", ",", "epochs", "=", "50", ",", "batch_size", "=", "64", ",", "num_neurons", "=", "256", ",", "encoder_input_data", "=", "None", ",", "decoder_input_data", "=", "None", ",", "decoder_target_d...
Train an LSTM encoder-decoder squence-to-sequence model on Anki flashcards for international translation >>> model = main('spa', n=400, epochs=3, batch_size=128, num_neurons=32) Train on 360 samples, validate on 40 samples Epoch 1/3 ... >>> len(model.get_weights()) 8 # 64 common characters...
[ "Train", "an", "LSTM", "encoder", "-", "decoder", "squence", "-", "to", "-", "sequence", "model", "on", "Anki", "flashcards", "for", "international", "translation" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/translate.py#L202-L248
train
totalgood/nlpia
src/nlpia/book/forum/boltz.py
BoltzmanMachine.energy
def energy(self, v, h=None): """Compute the global energy for the current joint state of all nodes >>> q11_4 = BoltzmanMachine(bv=[0., 0.], bh=[-2.], Whh=np.zeros((1, 1)), Wvv=np.zeros((2, 2)), Wvh=[[3.], [-1.]]) >>> q11_4.configurations() >>> v1v2h = product([0, 1], [0, 1], [0, 1]) ...
python
def energy(self, v, h=None): """Compute the global energy for the current joint state of all nodes >>> q11_4 = BoltzmanMachine(bv=[0., 0.], bh=[-2.], Whh=np.zeros((1, 1)), Wvv=np.zeros((2, 2)), Wvh=[[3.], [-1.]]) >>> q11_4.configurations() >>> v1v2h = product([0, 1], [0, 1], [0, 1]) ...
[ "def", "energy", "(", "self", ",", "v", ",", "h", "=", "None", ")", ":", "h", "=", "np", ".", "zeros", "(", "self", ".", "Nh", ")", "if", "h", "is", "None", "else", "h", "negE", "=", "np", ".", "dot", "(", "v", ",", "self", ".", "bv", ")"...
Compute the global energy for the current joint state of all nodes >>> q11_4 = BoltzmanMachine(bv=[0., 0.], bh=[-2.], Whh=np.zeros((1, 1)), Wvv=np.zeros((2, 2)), Wvh=[[3.], [-1.]]) >>> q11_4.configurations() >>> v1v2h = product([0, 1], [0, 1], [0, 1]) >>> E = np.array([q11_4.energy(v=x...
[ "Compute", "the", "global", "energy", "for", "the", "current", "joint", "state", "of", "all", "nodes" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/forum/boltz.py#L103-L133
train
totalgood/nlpia
src/nlpia/book/forum/boltz.py
Hopfield.energy
def energy(self): r""" Compute the global energy for the current joint state of all nodes - sum(s[i] * b[i]) - sum([s[i]*s[j]*W[i,j] for (i, j) in product(range(N), range(N)) if i<j)]) E = − ∑ s i b i − ∑ i i< j s i s j w ij """ s, b, W, N = self.state, self.b, ...
python
def energy(self): r""" Compute the global energy for the current joint state of all nodes - sum(s[i] * b[i]) - sum([s[i]*s[j]*W[i,j] for (i, j) in product(range(N), range(N)) if i<j)]) E = − ∑ s i b i − ∑ i i< j s i s j w ij """ s, b, W, N = self.state, self.b, ...
[ "def", "energy", "(", "self", ")", ":", "r", "s", ",", "b", ",", "W", ",", "N", "=", "self", ".", "state", ",", "self", ".", "b", ",", "self", ".", "W", ",", "self", ".", "N", "self", ".", "E", "=", "-", "sum", "(", "s", "*", "b", ")", ...
r""" Compute the global energy for the current joint state of all nodes - sum(s[i] * b[i]) - sum([s[i]*s[j]*W[i,j] for (i, j) in product(range(N), range(N)) if i<j)]) E = − ∑ s i b i − ∑ i i< j s i s j w ij
[ "r", "Compute", "the", "global", "energy", "for", "the", "current", "joint", "state", "of", "all", "nodes" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/forum/boltz.py#L210-L226
train
totalgood/nlpia
src/nlpia/translators.py
HyperlinkStyleCorrector.translate
def translate(self, text, to_template='{name} ({url})', from_template=None, name_matcher=None, url_matcher=None): """ Translate hyperinks into printable book style for Manning Publishing >>> translator = HyperlinkStyleCorrector() >>> adoc = 'See http://totalgood.com[Total Good] about that.' ...
python
def translate(self, text, to_template='{name} ({url})', from_template=None, name_matcher=None, url_matcher=None): """ Translate hyperinks into printable book style for Manning Publishing >>> translator = HyperlinkStyleCorrector() >>> adoc = 'See http://totalgood.com[Total Good] about that.' ...
[ "def", "translate", "(", "self", ",", "text", ",", "to_template", "=", "'{name} ({url})'", ",", "from_template", "=", "None", ",", "name_matcher", "=", "None", ",", "url_matcher", "=", "None", ")", ":", "return", "self", ".", "replace", "(", "text", ",", ...
Translate hyperinks into printable book style for Manning Publishing >>> translator = HyperlinkStyleCorrector() >>> adoc = 'See http://totalgood.com[Total Good] about that.' >>> translator.translate(adoc) 'See Total Good (http://totalgood.com) about that.'
[ "Translate", "hyperinks", "into", "printable", "book", "style", "for", "Manning", "Publishing" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/translators.py#L235-L244
train
totalgood/nlpia
src/nlpia/scripts/cleandialog.py
main
def main(dialogpath=None): """ Parse the state transition graph for a set of dialog-definition tables to find an fix deadends """ if dialogpath is None: args = parse_args() dialogpath = os.path.abspath(os.path.expanduser(args.dialogpath)) else: dialogpath = os.path.abspath(os.path.ex...
python
def main(dialogpath=None): """ Parse the state transition graph for a set of dialog-definition tables to find an fix deadends """ if dialogpath is None: args = parse_args() dialogpath = os.path.abspath(os.path.expanduser(args.dialogpath)) else: dialogpath = os.path.abspath(os.path.ex...
[ "def", "main", "(", "dialogpath", "=", "None", ")", ":", "if", "dialogpath", "is", "None", ":", "args", "=", "parse_args", "(", ")", "dialogpath", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "args", ".", ...
Parse the state transition graph for a set of dialog-definition tables to find an fix deadends
[ "Parse", "the", "state", "transition", "graph", "for", "a", "set", "of", "dialog", "-", "definition", "tables", "to", "find", "an", "fix", "deadends" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/scripts/cleandialog.py#L24-L31
train
totalgood/nlpia
src/nlpia/book/scripts/create_raw_ubuntu_dataset.py
prepare_data_maybe_download
def prepare_data_maybe_download(directory): """ Download and unpack dialogs if necessary. """ filename = 'ubuntu_dialogs.tgz' url = 'http://cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ubuntu_dialogs.tgz' dialogs_path = os.path.join(directory, 'dialogs') # test it there are some dialogs...
python
def prepare_data_maybe_download(directory): """ Download and unpack dialogs if necessary. """ filename = 'ubuntu_dialogs.tgz' url = 'http://cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ubuntu_dialogs.tgz' dialogs_path = os.path.join(directory, 'dialogs') # test it there are some dialogs...
[ "def", "prepare_data_maybe_download", "(", "directory", ")", ":", "filename", "=", "'ubuntu_dialogs.tgz'", "url", "=", "'http://cs.mcgill.ca/~jpineau/datasets/ubuntu-corpus-1.0/ubuntu_dialogs.tgz'", "dialogs_path", "=", "os", ".", "path", ".", "join", "(", "directory", ",",...
Download and unpack dialogs if necessary.
[ "Download", "and", "unpack", "dialogs", "if", "necessary", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/scripts/create_raw_ubuntu_dataset.py#L252-L277
train
totalgood/nlpia
src/nlpia/skeleton.py
fib
def fib(n): """Fibonacci example function Args: n (int): integer Returns: int: n-th Fibonacci number """ assert n > 0 a, b = 1, 1 for i in range(n - 1): a, b = b, a + b return a
python
def fib(n): """Fibonacci example function Args: n (int): integer Returns: int: n-th Fibonacci number """ assert n > 0 a, b = 1, 1 for i in range(n - 1): a, b = b, a + b return a
[ "def", "fib", "(", "n", ")", ":", "assert", "n", ">", "0", "a", ",", "b", "=", "1", ",", "1", "for", "i", "in", "range", "(", "n", "-", "1", ")", ":", "a", ",", "b", "=", "b", ",", "a", "+", "b", "return", "a" ]
Fibonacci example function Args: n (int): integer Returns: int: n-th Fibonacci number
[ "Fibonacci", "example", "function" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/skeleton.py#L37-L50
train
totalgood/nlpia
src/nlpia/skeleton.py
main
def main(args): """Main entry point allowing external calls Args: args ([str]): command line parameter list """ args = parse_args(args) setup_logging(args.loglevel) _logger.debug("Starting crazy calculations...") print("The {}-th Fibonacci number is {}".format(args.n, fib(args.n))) ...
python
def main(args): """Main entry point allowing external calls Args: args ([str]): command line parameter list """ args = parse_args(args) setup_logging(args.loglevel) _logger.debug("Starting crazy calculations...") print("The {}-th Fibonacci number is {}".format(args.n, fib(args.n))) ...
[ "def", "main", "(", "args", ")", ":", "args", "=", "parse_args", "(", "args", ")", "setup_logging", "(", "args", ".", "loglevel", ")", "_logger", ".", "debug", "(", "\"Starting crazy calculations...\"", ")", "print", "(", "\"The {}-th Fibonacci number is {}\"", ...
Main entry point allowing external calls Args: args ([str]): command line parameter list
[ "Main", "entry", "point", "allowing", "external", "calls" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/skeleton.py#L101-L111
train
totalgood/nlpia
src/nlpia/features.py
optimize_feature_power
def optimize_feature_power(df, output_column_name=None, exponents=[2., 1., .8, .5, .25, .1, .01]): """ Plot the correlation coefficient for various exponential scalings of input features >>> np.random.seed(314159) >>> df = pd.DataFrame() >>> df['output'] = np.random.randn(1000) >>> df['x10'] = df.o...
python
def optimize_feature_power(df, output_column_name=None, exponents=[2., 1., .8, .5, .25, .1, .01]): """ Plot the correlation coefficient for various exponential scalings of input features >>> np.random.seed(314159) >>> df = pd.DataFrame() >>> df['output'] = np.random.randn(1000) >>> df['x10'] = df.o...
[ "def", "optimize_feature_power", "(", "df", ",", "output_column_name", "=", "None", ",", "exponents", "=", "[", "2.", ",", "1.", ",", ".8", ",", ".5", ",", ".25", ",", ".1", ",", ".01", "]", ")", ":", "output_column_name", "=", "list", "(", "df", "."...
Plot the correlation coefficient for various exponential scalings of input features >>> np.random.seed(314159) >>> df = pd.DataFrame() >>> df['output'] = np.random.randn(1000) >>> df['x10'] = df.output * 10 >>> df['sq'] = df.output ** 2 >>> df['sqrt'] = df.output ** .5 >>> optimize_feature_...
[ "Plot", "the", "correlation", "coefficient", "for", "various", "exponential", "scalings", "of", "input", "features" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/features.py#L5-L38
train
totalgood/nlpia
src/nlpia/highd.py
representative_sample
def representative_sample(X, num_samples, save=False): """Sample vectors in X, preferring edge cases and vectors farthest from other vectors in sample set """ X = X.values if hasattr(X, 'values') else np.array(X) N, M = X.shape rownums = np.arange(N) np.random.shuffle(rownums) idx = Annoy...
python
def representative_sample(X, num_samples, save=False): """Sample vectors in X, preferring edge cases and vectors farthest from other vectors in sample set """ X = X.values if hasattr(X, 'values') else np.array(X) N, M = X.shape rownums = np.arange(N) np.random.shuffle(rownums) idx = Annoy...
[ "def", "representative_sample", "(", "X", ",", "num_samples", ",", "save", "=", "False", ")", ":", "X", "=", "X", ".", "values", "if", "hasattr", "(", "X", ",", "'values'", ")", "else", "np", ".", "array", "(", "X", ")", "N", ",", "M", "=", "X", ...
Sample vectors in X, preferring edge cases and vectors farthest from other vectors in sample set
[ "Sample", "vectors", "in", "X", "preferring", "edge", "cases", "and", "vectors", "farthest", "from", "other", "vectors", "in", "sample", "set" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/highd.py#L28-L68
train
totalgood/nlpia
src/nlpia/book/examples/ch03-2.py
cosine_sim
def cosine_sim(vec1, vec2): """ Since our vectors are dictionaries, lets convert them to lists for easier mathing. """ vec1 = [val for val in vec1.values()] vec2 = [val for val in vec2.values()] dot_prod = 0 for i, v in enumerate(vec1): dot_prod += v * vec2[i] mag_1...
python
def cosine_sim(vec1, vec2): """ Since our vectors are dictionaries, lets convert them to lists for easier mathing. """ vec1 = [val for val in vec1.values()] vec2 = [val for val in vec2.values()] dot_prod = 0 for i, v in enumerate(vec1): dot_prod += v * vec2[i] mag_1...
[ "def", "cosine_sim", "(", "vec1", ",", "vec2", ")", ":", "vec1", "=", "[", "val", "for", "val", "in", "vec1", ".", "values", "(", ")", "]", "vec2", "=", "[", "val", "for", "val", "in", "vec2", ".", "values", "(", ")", "]", "dot_prod", "=", "0",...
Since our vectors are dictionaries, lets convert them to lists for easier mathing.
[ "Since", "our", "vectors", "are", "dictionaries", "lets", "convert", "them", "to", "lists", "for", "easier", "mathing", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch03-2.py#L141-L155
train
totalgood/nlpia
src/nlpia/models.py
LinearRegressor.fit
def fit(self, X, y): """ Compute average slope and intercept for all X, y pairs Arguments: X (np.array): model input (independent variable) y (np.array): model output (dependent variable) Returns: Linear Regression instance with `slope` and `intercept` attributes ...
python
def fit(self, X, y): """ Compute average slope and intercept for all X, y pairs Arguments: X (np.array): model input (independent variable) y (np.array): model output (dependent variable) Returns: Linear Regression instance with `slope` and `intercept` attributes ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "n", "=", "float", "(", "len", "(", "X", ")", ")", "sum_x", "=", "X", ".", "sum", "(", ")", "sum_y", "=", "y", ".", "sum", "(", ")", "sum_xy", "=", "(", "X", "*", "y", ")", ".", ...
Compute average slope and intercept for all X, y pairs Arguments: X (np.array): model input (independent variable) y (np.array): model output (dependent variable) Returns: Linear Regression instance with `slope` and `intercept` attributes References: Ba...
[ "Compute", "average", "slope", "and", "intercept", "for", "all", "X", "y", "pairs" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/models.py#L15-L54
train
totalgood/nlpia
src/nlpia/web.py
looks_like_url
def looks_like_url(url): """ Simplified check to see if the text appears to be a URL. Similar to `urlparse` but much more basic. Returns: True if the url str appears to be valid. False otherwise. >>> url = looks_like_url("totalgood.org") >>> bool(url) True """ if not isins...
python
def looks_like_url(url): """ Simplified check to see if the text appears to be a URL. Similar to `urlparse` but much more basic. Returns: True if the url str appears to be valid. False otherwise. >>> url = looks_like_url("totalgood.org") >>> bool(url) True """ if not isins...
[ "def", "looks_like_url", "(", "url", ")", ":", "if", "not", "isinstance", "(", "url", ",", "basestring", ")", ":", "return", "False", "if", "not", "isinstance", "(", "url", ",", "basestring", ")", "or", "len", "(", "url", ")", ">=", "1024", "or", "no...
Simplified check to see if the text appears to be a URL. Similar to `urlparse` but much more basic. Returns: True if the url str appears to be valid. False otherwise. >>> url = looks_like_url("totalgood.org") >>> bool(url) True
[ "Simplified", "check", "to", "see", "if", "the", "text", "appears", "to", "be", "a", "URL", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/web.py#L68-L85
train
totalgood/nlpia
src/nlpia/web.py
try_parse_url
def try_parse_url(url): """ User urlparse to try to parse URL returning None on exception """ if len(url.strip()) < 4: logger.info('URL too short: {}'.format(url)) return None try: parsed_url = urlparse(url) except ValueError: logger.info('Parse URL ValueError: {}'.format...
python
def try_parse_url(url): """ User urlparse to try to parse URL returning None on exception """ if len(url.strip()) < 4: logger.info('URL too short: {}'.format(url)) return None try: parsed_url = urlparse(url) except ValueError: logger.info('Parse URL ValueError: {}'.format...
[ "def", "try_parse_url", "(", "url", ")", ":", "if", "len", "(", "url", ".", "strip", "(", ")", ")", "<", "4", ":", "logger", ".", "info", "(", "'URL too short: {}'", ".", "format", "(", "url", ")", ")", "return", "None", "try", ":", "parsed_url", "...
User urlparse to try to parse URL returning None on exception
[ "User", "urlparse", "to", "try", "to", "parse", "URL", "returning", "None", "on", "exception" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/web.py#L88-L108
train
totalgood/nlpia
src/nlpia/web.py
get_url_filemeta
def get_url_filemeta(url): """ Request HTML for the page at the URL indicated and return the url, filename, and remote size TODO: just add remote_size and basename and filename attributes to the urlparse object instead of returning a dict >>> sorted(get_url_filemeta('mozilla.com').items()) [...
python
def get_url_filemeta(url): """ Request HTML for the page at the URL indicated and return the url, filename, and remote size TODO: just add remote_size and basename and filename attributes to the urlparse object instead of returning a dict >>> sorted(get_url_filemeta('mozilla.com').items()) [...
[ "def", "get_url_filemeta", "(", "url", ")", ":", "parsed_url", "=", "try_parse_url", "(", "url", ")", "if", "parsed_url", "is", "None", ":", "return", "None", "if", "parsed_url", ".", "scheme", ".", "startswith", "(", "'ftp'", ")", ":", "return", "get_ftp_...
Request HTML for the page at the URL indicated and return the url, filename, and remote size TODO: just add remote_size and basename and filename attributes to the urlparse object instead of returning a dict >>> sorted(get_url_filemeta('mozilla.com').items()) [('filename', ''), ('hostname',...
[ "Request", "HTML", "for", "the", "page", "at", "the", "URL", "indicated", "and", "return", "the", "url", "filename", "and", "remote", "size" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/web.py#L111-L152
train
totalgood/nlpia
src/nlpia/web.py
save_response_content
def save_response_content(response, filename='data.csv', destination=os.path.curdir, chunksize=32768): """ For streaming response from requests, download the content one CHUNK at a time """ chunksize = chunksize or 32768 if os.path.sep in filename: full_destination_path = filename else: ...
python
def save_response_content(response, filename='data.csv', destination=os.path.curdir, chunksize=32768): """ For streaming response from requests, download the content one CHUNK at a time """ chunksize = chunksize or 32768 if os.path.sep in filename: full_destination_path = filename else: ...
[ "def", "save_response_content", "(", "response", ",", "filename", "=", "'data.csv'", ",", "destination", "=", "os", ".", "path", ".", "curdir", ",", "chunksize", "=", "32768", ")", ":", "chunksize", "=", "chunksize", "or", "32768", "if", "os", ".", "path",...
For streaming response from requests, download the content one CHUNK at a time
[ "For", "streaming", "response", "from", "requests", "download", "the", "content", "one", "CHUNK", "at", "a", "time" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/web.py#L209-L221
train
totalgood/nlpia
src/nlpia/web.py
download_file_from_google_drive
def download_file_from_google_drive(driveid, filename=None, destination=os.path.curdir): """ Download script for google drive shared links Thank you @turdus-merula and Andrew Hundt! https://stackoverflow.com/a/39225039/623735 """ if '&id=' in driveid: # https://drive.google.com/uc?export=...
python
def download_file_from_google_drive(driveid, filename=None, destination=os.path.curdir): """ Download script for google drive shared links Thank you @turdus-merula and Andrew Hundt! https://stackoverflow.com/a/39225039/623735 """ if '&id=' in driveid: # https://drive.google.com/uc?export=...
[ "def", "download_file_from_google_drive", "(", "driveid", ",", "filename", "=", "None", ",", "destination", "=", "os", ".", "path", ".", "curdir", ")", ":", "if", "'&id='", "in", "driveid", ":", "driveid", "=", "driveid", ".", "split", "(", "'&id='", ")", ...
Download script for google drive shared links Thank you @turdus-merula and Andrew Hundt! https://stackoverflow.com/a/39225039/623735
[ "Download", "script", "for", "google", "drive", "shared", "links" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/web.py#L224-L252
train
totalgood/nlpia
src/nlpia/book/examples/ch11_greetings.py
find_greeting
def find_greeting(s): """ Return the the greeting string Hi, Hello, or Yo if it occurs at the beginning of a string >>> find_greeting('Hi Mr. Turing!') 'Hi' >>> find_greeting('Hello, Rosa.') 'Hello' >>> find_greeting("Yo, what's up?") 'Yo' >>> find_greeting("Hello") 'Hello' >>> ...
python
def find_greeting(s): """ Return the the greeting string Hi, Hello, or Yo if it occurs at the beginning of a string >>> find_greeting('Hi Mr. Turing!') 'Hi' >>> find_greeting('Hello, Rosa.') 'Hello' >>> find_greeting("Yo, what's up?") 'Yo' >>> find_greeting("Hello") 'Hello' >>> ...
[ "def", "find_greeting", "(", "s", ")", ":", "if", "s", "[", "0", "]", "==", "'H'", ":", "if", "s", "[", ":", "3", "]", "in", "[", "'Hi'", ",", "'Hi '", ",", "'Hi,'", ",", "'Hi!'", "]", ":", "return", "s", "[", ":", "2", "]", "elif", "s", ...
Return the the greeting string Hi, Hello, or Yo if it occurs at the beginning of a string >>> find_greeting('Hi Mr. Turing!') 'Hi' >>> find_greeting('Hello, Rosa.') 'Hello' >>> find_greeting("Yo, what's up?") 'Yo' >>> find_greeting("Hello") 'Hello' >>> print(find_greeting("hello")) ...
[ "Return", "the", "the", "greeting", "string", "Hi", "Hello", "or", "Yo", "if", "it", "occurs", "at", "the", "beginning", "of", "a", "string" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch11_greetings.py#L4-L28
train
totalgood/nlpia
src/nlpia/scripts/hunspell_to_json.py
file_to_list
def file_to_list(in_file): ''' Reads file into list ''' lines = [] for line in in_file: # Strip new line line = line.strip('\n') # Ignore empty lines if line != '': # Ignore comments if line[0] != '#': lines.append(line) return li...
python
def file_to_list(in_file): ''' Reads file into list ''' lines = [] for line in in_file: # Strip new line line = line.strip('\n') # Ignore empty lines if line != '': # Ignore comments if line[0] != '#': lines.append(line) return li...
[ "def", "file_to_list", "(", "in_file", ")", ":", "lines", "=", "[", "]", "for", "line", "in", "in_file", ":", "line", "=", "line", ".", "strip", "(", "'\\n'", ")", "if", "line", "!=", "''", ":", "if", "line", "[", "0", "]", "!=", "'#'", ":", "l...
Reads file into list
[ "Reads", "file", "into", "list" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/scripts/hunspell_to_json.py#L39-L52
train
totalgood/nlpia
src/nlpia/scripts/hunspell_to_json.py
CompoundRule.add_flag_values
def add_flag_values(self, entry, flag): ''' Adds flag value to applicable compounds ''' if flag in self.flags: self.flags[flag].append(entry)
python
def add_flag_values(self, entry, flag): ''' Adds flag value to applicable compounds ''' if flag in self.flags: self.flags[flag].append(entry)
[ "def", "add_flag_values", "(", "self", ",", "entry", ",", "flag", ")", ":", "if", "flag", "in", "self", ".", "flags", ":", "self", ".", "flags", "[", "flag", "]", ".", "append", "(", "entry", ")" ]
Adds flag value to applicable compounds
[ "Adds", "flag", "value", "to", "applicable", "compounds" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/scripts/hunspell_to_json.py#L110-L113
train
totalgood/nlpia
src/nlpia/scripts/hunspell_to_json.py
CompoundRule.get_regex
def get_regex(self): ''' Generates and returns compound regular expression ''' regex = '' for flag in self.compound: if flag == '?' or flag == '*': regex += flag else: regex += '(' + '|'.join(self.flags[flag]) + ')' return regex
python
def get_regex(self): ''' Generates and returns compound regular expression ''' regex = '' for flag in self.compound: if flag == '?' or flag == '*': regex += flag else: regex += '(' + '|'.join(self.flags[flag]) + ')' return regex
[ "def", "get_regex", "(", "self", ")", ":", "regex", "=", "''", "for", "flag", "in", "self", ".", "compound", ":", "if", "flag", "==", "'?'", "or", "flag", "==", "'*'", ":", "regex", "+=", "flag", "else", ":", "regex", "+=", "'('", "+", "'|'", "."...
Generates and returns compound regular expression
[ "Generates", "and", "returns", "compound", "regular", "expression" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/scripts/hunspell_to_json.py#L115-L124
train
totalgood/nlpia
src/nlpia/scripts/hunspell_to_json.py
DICT.__parse_dict
def __parse_dict(self): ''' Parses dictionary with according rules ''' i = 0 lines = self.lines for line in lines: line = line.split('/') word = line[0] flags = line[1] if len(line) > 1 else None # Base Word self.num_words += ...
python
def __parse_dict(self): ''' Parses dictionary with according rules ''' i = 0 lines = self.lines for line in lines: line = line.split('/') word = line[0] flags = line[1] if len(line) > 1 else None # Base Word self.num_words += ...
[ "def", "__parse_dict", "(", "self", ")", ":", "i", "=", "0", "lines", "=", "self", ".", "lines", "for", "line", "in", "lines", ":", "line", "=", "line", ".", "split", "(", "'/'", ")", "word", "=", "line", "[", "0", "]", "flags", "=", "line", "[...
Parses dictionary with according rules
[ "Parses", "dictionary", "with", "according", "rules" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/scripts/hunspell_to_json.py#L282-L343
train
totalgood/nlpia
src/nlpia/loaders.py
load_imdb_df
def load_imdb_df(dirpath=os.path.join(BIGDATA_PATH, 'aclImdb'), subdirectories=(('train', 'test'), ('pos', 'neg', 'unsup'))): """ Walk directory tree starting at `path` to compile a DataFrame of movie review text labeled with their 1-10 star ratings Returns: DataFrame: columns=['url', 'rating', 'text'], ...
python
def load_imdb_df(dirpath=os.path.join(BIGDATA_PATH, 'aclImdb'), subdirectories=(('train', 'test'), ('pos', 'neg', 'unsup'))): """ Walk directory tree starting at `path` to compile a DataFrame of movie review text labeled with their 1-10 star ratings Returns: DataFrame: columns=['url', 'rating', 'text'], ...
[ "def", "load_imdb_df", "(", "dirpath", "=", "os", ".", "path", ".", "join", "(", "BIGDATA_PATH", ",", "'aclImdb'", ")", ",", "subdirectories", "=", "(", "(", "'train'", ",", "'test'", ")", ",", "(", "'pos'", ",", "'neg'", ",", "'unsup'", ")", ")", ")...
Walk directory tree starting at `path` to compile a DataFrame of movie review text labeled with their 1-10 star ratings Returns: DataFrame: columns=['url', 'rating', 'text'], index=MultiIndex(['train_test', 'pos_neg_unsup', 'id']) TODO: Make this more robust/general by allowing the subdirectories ...
[ "Walk", "directory", "tree", "starting", "at", "path", "to", "compile", "a", "DataFrame", "of", "movie", "review", "text", "labeled", "with", "their", "1", "-", "10", "star", "ratings" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L108-L155
train
totalgood/nlpia
src/nlpia/loaders.py
load_glove
def load_glove(filepath, batch_size=1000, limit=None, verbose=True): r""" Load a pretrained GloVE word vector model First header line of GloVE text file should look like: 400000 50\n First vector of GloVE text file should look like: the .12 .22 .32 .42 ... .42 >>> wv = load_glove(os.pa...
python
def load_glove(filepath, batch_size=1000, limit=None, verbose=True): r""" Load a pretrained GloVE word vector model First header line of GloVE text file should look like: 400000 50\n First vector of GloVE text file should look like: the .12 .22 .32 .42 ... .42 >>> wv = load_glove(os.pa...
[ "def", "load_glove", "(", "filepath", ",", "batch_size", "=", "1000", ",", "limit", "=", "None", ",", "verbose", "=", "True", ")", ":", "r", "num_dim", "=", "isglove", "(", "filepath", ")", "tqdm_prog", "=", "tqdm", "if", "verbose", "else", "no_tqdm", ...
r""" Load a pretrained GloVE word vector model First header line of GloVE text file should look like: 400000 50\n First vector of GloVE text file should look like: the .12 .22 .32 .42 ... .42 >>> wv = load_glove(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> wv.most_similar('and')[:...
[ "r", "Load", "a", "pretrained", "GloVE", "word", "vector", "model" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L158-L204
train
totalgood/nlpia
src/nlpia/loaders.py
load_glove_df
def load_glove_df(filepath, **kwargs): """ Load a GloVE-format text file into a dataframe >>> df = load_glove_df(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> df.index[:3] Index(['the', ',', '.'], dtype='object', name=0) >>> df.iloc[0][:3] 1 0.41800 2 0.24968 3 -0.41242 ...
python
def load_glove_df(filepath, **kwargs): """ Load a GloVE-format text file into a dataframe >>> df = load_glove_df(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> df.index[:3] Index(['the', ',', '.'], dtype='object', name=0) >>> df.iloc[0][:3] 1 0.41800 2 0.24968 3 -0.41242 ...
[ "def", "load_glove_df", "(", "filepath", ",", "**", "kwargs", ")", ":", "pdkwargs", "=", "dict", "(", "index_col", "=", "0", ",", "header", "=", "None", ",", "sep", "=", "r'\\s'", ",", "skiprows", "=", "[", "0", "]", ",", "verbose", "=", "False", "...
Load a GloVE-format text file into a dataframe >>> df = load_glove_df(os.path.join(BIGDATA_PATH, 'glove_test.txt')) >>> df.index[:3] Index(['the', ',', '.'], dtype='object', name=0) >>> df.iloc[0][:3] 1 0.41800 2 0.24968 3 -0.41242 Name: the, dtype: float64
[ "Load", "a", "GloVE", "-", "format", "text", "file", "into", "a", "dataframe" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L207-L221
train
totalgood/nlpia
src/nlpia/loaders.py
get_en2fr
def get_en2fr(url='http://www.manythings.org/anki/fra-eng.zip'): """ Download and parse English->French translation dataset used in Keras seq2seq example """ download_unzip(url) return pd.read_table(url, compression='zip', header=None, skip_blank_lines=True, sep='\t', skiprows=0, names='en fr'.split())
python
def get_en2fr(url='http://www.manythings.org/anki/fra-eng.zip'): """ Download and parse English->French translation dataset used in Keras seq2seq example """ download_unzip(url) return pd.read_table(url, compression='zip', header=None, skip_blank_lines=True, sep='\t', skiprows=0, names='en fr'.split())
[ "def", "get_en2fr", "(", "url", "=", "'http://www.manythings.org/anki/fra-eng.zip'", ")", ":", "download_unzip", "(", "url", ")", "return", "pd", ".", "read_table", "(", "url", ",", "compression", "=", "'zip'", ",", "header", "=", "None", ",", "skip_blank_lines"...
Download and parse English->French translation dataset used in Keras seq2seq example
[ "Download", "and", "parse", "English", "-", ">", "French", "translation", "dataset", "used", "in", "Keras", "seq2seq", "example" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L233-L236
train
totalgood/nlpia
src/nlpia/loaders.py
load_anki_df
def load_anki_df(language='deu'): """ Load into a DataFrame statements in one language along with their translation into English >>> get_data('zsm').head(1) eng zsm 0 Are you new? Awak baru? """ if os.path.isfile(langua...
python
def load_anki_df(language='deu'): """ Load into a DataFrame statements in one language along with their translation into English >>> get_data('zsm').head(1) eng zsm 0 Are you new? Awak baru? """ if os.path.isfile(langua...
[ "def", "load_anki_df", "(", "language", "=", "'deu'", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "language", ")", ":", "filepath", "=", "language", "lang", "=", "re", ".", "search", "(", "'[a-z]{3}-eng/'", ",", "filepath", ")", ".", "group"...
Load into a DataFrame statements in one language along with their translation into English >>> get_data('zsm').head(1) eng zsm 0 Are you new? Awak baru?
[ "Load", "into", "a", "DataFrame", "statements", "in", "one", "language", "along", "with", "their", "translation", "into", "English" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L239-L254
train
totalgood/nlpia
src/nlpia/loaders.py
generate_big_urls_glove
def generate_big_urls_glove(bigurls=None): """ Generate a dictionary of URLs for various combinations of GloVe training set sizes and dimensionality """ bigurls = bigurls or {} for num_dim in (50, 100, 200, 300): # not all of these dimensionality, and training set size combinations were trained by S...
python
def generate_big_urls_glove(bigurls=None): """ Generate a dictionary of URLs for various combinations of GloVe training set sizes and dimensionality """ bigurls = bigurls or {} for num_dim in (50, 100, 200, 300): # not all of these dimensionality, and training set size combinations were trained by S...
[ "def", "generate_big_urls_glove", "(", "bigurls", "=", "None", ")", ":", "bigurls", "=", "bigurls", "or", "{", "}", "for", "num_dim", "in", "(", "50", ",", "100", ",", "200", ",", "300", ")", ":", "for", "suffixes", ",", "num_words", "in", "zip", "("...
Generate a dictionary of URLs for various combinations of GloVe training set sizes and dimensionality
[ "Generate", "a", "dictionary", "of", "URLs", "for", "various", "combinations", "of", "GloVe", "training", "set", "sizes", "and", "dimensionality" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L381-L403
train
totalgood/nlpia
src/nlpia/loaders.py
normalize_ext_rename
def normalize_ext_rename(filepath): """ normalize file ext like '.tgz' -> '.tar.gz' and '300d.txt' -> '300d.glove.txt' and rename the file >>> pth = os.path.join(DATA_PATH, 'sms_slang_dict.txt') >>> pth == normalize_ext_rename(pth) True """ logger.debug('normalize_ext.filepath=' + str(filepath)...
python
def normalize_ext_rename(filepath): """ normalize file ext like '.tgz' -> '.tar.gz' and '300d.txt' -> '300d.glove.txt' and rename the file >>> pth = os.path.join(DATA_PATH, 'sms_slang_dict.txt') >>> pth == normalize_ext_rename(pth) True """ logger.debug('normalize_ext.filepath=' + str(filepath)...
[ "def", "normalize_ext_rename", "(", "filepath", ")", ":", "logger", ".", "debug", "(", "'normalize_ext.filepath='", "+", "str", "(", "filepath", ")", ")", "new_file_path", "=", "normalize_ext", "(", "filepath", ")", "logger", ".", "debug", "(", "'download_unzip....
normalize file ext like '.tgz' -> '.tar.gz' and '300d.txt' -> '300d.glove.txt' and rename the file >>> pth = os.path.join(DATA_PATH, 'sms_slang_dict.txt') >>> pth == normalize_ext_rename(pth) True
[ "normalize", "file", "ext", "like", ".", "tgz", "-", ">", ".", "tar", ".", "gz", "and", "300d", ".", "txt", "-", ">", "300d", ".", "glove", ".", "txt", "and", "rename", "the", "file" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L506-L519
train
totalgood/nlpia
src/nlpia/loaders.py
untar
def untar(fname, verbose=True): """ Uunzip and untar a tar.gz file into a subdir of the BIGDATA_PATH directory """ if fname.lower().endswith(".tar.gz"): dirpath = os.path.join(BIGDATA_PATH, os.path.basename(fname)[:-7]) if os.path.isdir(dirpath): return dirpath with tarfile.o...
python
def untar(fname, verbose=True): """ Uunzip and untar a tar.gz file into a subdir of the BIGDATA_PATH directory """ if fname.lower().endswith(".tar.gz"): dirpath = os.path.join(BIGDATA_PATH, os.path.basename(fname)[:-7]) if os.path.isdir(dirpath): return dirpath with tarfile.o...
[ "def", "untar", "(", "fname", ",", "verbose", "=", "True", ")", ":", "if", "fname", ".", "lower", "(", ")", ".", "endswith", "(", "\".tar.gz\"", ")", ":", "dirpath", "=", "os", ".", "path", ".", "join", "(", "BIGDATA_PATH", ",", "os", ".", "path", ...
Uunzip and untar a tar.gz file into a subdir of the BIGDATA_PATH directory
[ "Uunzip", "and", "untar", "a", "tar", ".", "gz", "file", "into", "a", "subdir", "of", "the", "BIGDATA_PATH", "directory" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L522-L536
train
totalgood/nlpia
src/nlpia/loaders.py
endswith_strip
def endswith_strip(s, endswith='.txt', ignorecase=True): """ Strip a suffix from the end of a string >>> endswith_strip('http://TotalGood.com', '.COM') 'http://TotalGood' >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False) 'http://TotalGood.com' """ if ignorecase: ...
python
def endswith_strip(s, endswith='.txt', ignorecase=True): """ Strip a suffix from the end of a string >>> endswith_strip('http://TotalGood.com', '.COM') 'http://TotalGood' >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False) 'http://TotalGood.com' """ if ignorecase: ...
[ "def", "endswith_strip", "(", "s", ",", "endswith", "=", "'.txt'", ",", "ignorecase", "=", "True", ")", ":", "if", "ignorecase", ":", "if", "s", ".", "lower", "(", ")", ".", "endswith", "(", "endswith", ".", "lower", "(", ")", ")", ":", "return", "...
Strip a suffix from the end of a string >>> endswith_strip('http://TotalGood.com', '.COM') 'http://TotalGood' >>> endswith_strip('http://TotalGood.com', endswith='.COM', ignorecase=False) 'http://TotalGood.com'
[ "Strip", "a", "suffix", "from", "the", "end", "of", "a", "string" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L570-L584
train
totalgood/nlpia
src/nlpia/loaders.py
startswith_strip
def startswith_strip(s, startswith='http://', ignorecase=True): """ Strip a prefix from the beginning of a string >>> startswith_strip('HTtp://TotalGood.com', 'HTTP://') 'TotalGood.com' >>> startswith_strip('HTtp://TotalGood.com', startswith='HTTP://', ignorecase=False) 'HTtp://TotalGood.com' "...
python
def startswith_strip(s, startswith='http://', ignorecase=True): """ Strip a prefix from the beginning of a string >>> startswith_strip('HTtp://TotalGood.com', 'HTTP://') 'TotalGood.com' >>> startswith_strip('HTtp://TotalGood.com', startswith='HTTP://', ignorecase=False) 'HTtp://TotalGood.com' "...
[ "def", "startswith_strip", "(", "s", ",", "startswith", "=", "'http://'", ",", "ignorecase", "=", "True", ")", ":", "if", "ignorecase", ":", "if", "s", ".", "lower", "(", ")", ".", "startswith", "(", "startswith", ".", "lower", "(", ")", ")", ":", "r...
Strip a prefix from the beginning of a string >>> startswith_strip('HTtp://TotalGood.com', 'HTTP://') 'TotalGood.com' >>> startswith_strip('HTtp://TotalGood.com', startswith='HTTP://', ignorecase=False) 'HTtp://TotalGood.com'
[ "Strip", "a", "prefix", "from", "the", "beginning", "of", "a", "string" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L587-L601
train
totalgood/nlpia
src/nlpia/loaders.py
get_longest_table
def get_longest_table(url='https://www.openoffice.org/dev_docs/source/file_extensions.html', header=0): """ Retrieve the HTML tables from a URL and return the longest DataFrame found >>> get_longest_table('https://en.wikipedia.org/wiki/List_of_sovereign_states').columns Index(['Common and formal names', 'M...
python
def get_longest_table(url='https://www.openoffice.org/dev_docs/source/file_extensions.html', header=0): """ Retrieve the HTML tables from a URL and return the longest DataFrame found >>> get_longest_table('https://en.wikipedia.org/wiki/List_of_sovereign_states').columns Index(['Common and formal names', 'M...
[ "def", "get_longest_table", "(", "url", "=", "'https://www.openoffice.org/dev_docs/source/file_extensions.html'", ",", "header", "=", "0", ")", ":", "dfs", "=", "pd", ".", "read_html", "(", "url", ",", "header", "=", "header", ")", "return", "longest_table", "(", ...
Retrieve the HTML tables from a URL and return the longest DataFrame found >>> get_longest_table('https://en.wikipedia.org/wiki/List_of_sovereign_states').columns Index(['Common and formal names', 'Membership within the UN System[a]', 'Sovereignty dispute[b]', 'Further information on status and r...
[ "Retrieve", "the", "HTML", "tables", "from", "a", "URL", "and", "return", "the", "longest", "DataFrame", "found" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L609-L619
train
totalgood/nlpia
src/nlpia/loaders.py
get_filename_extensions
def get_filename_extensions(url='https://www.webopedia.com/quick_ref/fileextensionsfull.asp'): """ Load a DataFrame of filename extensions from the indicated url >>> df = get_filename_extensions('https://www.openoffice.org/dev_docs/source/file_extensions.html') >>> df.head(2) ext ...
python
def get_filename_extensions(url='https://www.webopedia.com/quick_ref/fileextensionsfull.asp'): """ Load a DataFrame of filename extensions from the indicated url >>> df = get_filename_extensions('https://www.openoffice.org/dev_docs/source/file_extensions.html') >>> df.head(2) ext ...
[ "def", "get_filename_extensions", "(", "url", "=", "'https://www.webopedia.com/quick_ref/fileextensionsfull.asp'", ")", ":", "df", "=", "get_longest_table", "(", "url", ")", "columns", "=", "list", "(", "df", ".", "columns", ")", "columns", "[", "0", "]", "=", "...
Load a DataFrame of filename extensions from the indicated url >>> df = get_filename_extensions('https://www.openoffice.org/dev_docs/source/file_extensions.html') >>> df.head(2) ext description 0 .a UNIX static library file. 1 .asm Non-UNIX assembler source file...
[ "Load", "a", "DataFrame", "of", "filename", "extensions", "from", "the", "indicated", "url" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L663-L679
train
totalgood/nlpia
src/nlpia/loaders.py
create_big_url
def create_big_url(name): """ If name looks like a url, with an http, add an entry for it in BIG_URLS """ # BIG side effect global BIG_URLS filemeta = get_url_filemeta(name) if not filemeta: return None filename = filemeta['filename'] remote_size = filemeta['remote_size'] url = f...
python
def create_big_url(name): """ If name looks like a url, with an http, add an entry for it in BIG_URLS """ # BIG side effect global BIG_URLS filemeta = get_url_filemeta(name) if not filemeta: return None filename = filemeta['filename'] remote_size = filemeta['remote_size'] url = f...
[ "def", "create_big_url", "(", "name", ")", ":", "global", "BIG_URLS", "filemeta", "=", "get_url_filemeta", "(", "name", ")", "if", "not", "filemeta", ":", "return", "None", "filename", "=", "filemeta", "[", "'filename'", "]", "remote_size", "=", "filemeta", ...
If name looks like a url, with an http, add an entry for it in BIG_URLS
[ "If", "name", "looks", "like", "a", "url", "with", "an", "http", "add", "an", "entry", "for", "it", "in", "BIG_URLS" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L787-L801
train
totalgood/nlpia
src/nlpia/loaders.py
get_data
def get_data(name='sms-spam', nrows=None, limit=None): """ Load data from a json, csv, or txt file if it exists in the data dir. References: [cities_air_pollution_index](https://www.numbeo.com/pollution/rankings.jsp) [cities](http://download.geonames.org/export/dump/cities.zip) [cities_us](ht...
python
def get_data(name='sms-spam', nrows=None, limit=None): """ Load data from a json, csv, or txt file if it exists in the data dir. References: [cities_air_pollution_index](https://www.numbeo.com/pollution/rankings.jsp) [cities](http://download.geonames.org/export/dump/cities.zip) [cities_us](ht...
[ "def", "get_data", "(", "name", "=", "'sms-spam'", ",", "nrows", "=", "None", ",", "limit", "=", "None", ")", ":", "nrows", "=", "nrows", "or", "limit", "if", "name", "in", "BIG_URLS", ":", "logger", ".", "info", "(", "'Downloading {}'", ".", "format",...
Load data from a json, csv, or txt file if it exists in the data dir. References: [cities_air_pollution_index](https://www.numbeo.com/pollution/rankings.jsp) [cities](http://download.geonames.org/export/dump/cities.zip) [cities_us](http://download.geonames.org/export/dump/cities_us.zip) >>> ...
[ "Load", "data", "from", "a", "json", "csv", "or", "txt", "file", "if", "it", "exists", "in", "the", "data", "dir", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1027-L1113
train
totalgood/nlpia
src/nlpia/loaders.py
get_wikidata_qnum
def get_wikidata_qnum(wikiarticle, wikisite): """Retrieve the Query number for a wikidata database of metadata about a particular article >>> print(get_wikidata_qnum(wikiarticle="Andromeda Galaxy", wikisite="enwiki")) Q2469 """ resp = requests.get('https://www.wikidata.org/w/api.php', timeout=5, pa...
python
def get_wikidata_qnum(wikiarticle, wikisite): """Retrieve the Query number for a wikidata database of metadata about a particular article >>> print(get_wikidata_qnum(wikiarticle="Andromeda Galaxy", wikisite="enwiki")) Q2469 """ resp = requests.get('https://www.wikidata.org/w/api.php', timeout=5, pa...
[ "def", "get_wikidata_qnum", "(", "wikiarticle", ",", "wikisite", ")", ":", "resp", "=", "requests", ".", "get", "(", "'https://www.wikidata.org/w/api.php'", ",", "timeout", "=", "5", ",", "params", "=", "{", "'action'", ":", "'wbgetentities'", ",", "'titles'", ...
Retrieve the Query number for a wikidata database of metadata about a particular article >>> print(get_wikidata_qnum(wikiarticle="Andromeda Galaxy", wikisite="enwiki")) Q2469
[ "Retrieve", "the", "Query", "number", "for", "a", "wikidata", "database", "of", "metadata", "about", "a", "particular", "article" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1126-L1139
train