id
int32
0
252k
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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
245,200
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): 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
245,201
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): 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
245,202
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): 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
245,203
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): 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
245,204
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): headers = self.headers or {} header = headers.get('link') li = {} if header: links = parse_header_links(header) for link in links: key = link.get('rel') or link.get('url') li[key] = link return li
[ "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
245,205
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): 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
245,206
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): ct = self.headers.get('content-type') if ct: ct, options = parse_options_header(ct) charset = options.get('charset') if ct in JSON_CONTENT_TYPES: return self.json() elif ct.startswith('text/'): retu...
[ "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
245,207
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): response = self._request(method, url, **params) if not self._loop.is_running(): return self._loop.run_until_complete(response) else: return response
[ "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
245,208
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): assert ssl, 'SSL not supported' cafile = cafile or DEFAULT_CA_BUNDLE_PATH if verify is True: ce...
[ "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
245,209
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): tunnel_address = req.tunnel_address connection = await self.create_connection(tunnel_address) response = connection.current_consumer() for event in response.events().values(): event.clear() response.start(HttpTunnel(self,...
[ "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
245,210
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): if not script: try: import __main__ script = getfile(__main__) except Exception: # pragma nocover return script = os.path.realpath(script) if self.cfg.get('python_path', True): ...
[ "def", "python_path", "(", "self", ",", "script", ")", ":", "if", "not", "script", ":", "try", ":", "import", "__main__", "script", "=", "getfile", "(", "__main__", ")", "except", "Exception", ":", "# pragma nocover", "return", "script", "=", "os", ".",...
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
245,211
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): on_start = self() actor = arbiter() if actor and on_start: actor.start(exit=exit) if actor.exit_code is not None: return actor.exit_code return on_start
[ "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
245,212
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): 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 stop application')
[ "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
245,213
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): 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(-gid).value) if uid: os.setuid(uid)
[ "def", "set_owner_process", "(", "uid", ",", "gid", ")", ":", "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", "....
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
245,214
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
245,215
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): @wraps(callable) async def _(*args, **kwargs): green = greenlet(callable) # switch to the new greenlet result = green.switch(*args, **kwargs) # back to the parent while isawaitable(result): # keep on switching back to the greenle...
[ "def", "run_in_greenlet", "(", "callable", ")", ":", "@", "wraps", "(", "callable", ")", "async", "def", "_", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "green", "=", "greenlet", "(", "callable", ")", "# switch to the new greenlet", "result", "...
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
245,216
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): 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, Authorization' return response
[ "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
245,217
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", ")", ":", "## format sql", "data", "=", "request", ".", "get_json", "(", ")", "options", ",", "sql_raw", "=", "data", ".", "get", "(", "'options'", ")", ",", "data", ".", "get", "(", "'sql_raw'", ")", "if", "options", "=="...
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
245,218
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): dash_list = r_db.zrevrange(config.DASH_ID_KEY, 0, -1, True) id_list = dash_list[page * size : page * size + size] dash_meta = [] data = [] if id_list: dash_meta = r_db.hmget(config.DASH_META_KEY, [i[0] for i in id_list]) dat...
[ "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
245,219
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): 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
245,220
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): 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", ")", "# data = json.dumps(data) if isinstance(data, str) else data", "# data = json.loads(data) if data else {}", "return", "build_response", "(", "dict", "(", "data", "=", ...
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
245,221
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): return make_response(render_template('dashboard.html', dash_id=dash_id, api_root=config.app_host))
[ "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
245,222
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): data = json.loads(r_db.hmget(config.DASH_CONTENT_KEY, dash_id)[0]) return build_response(dict(data=data, code=200))
[ "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
245,223
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): data = request.get_json() updated = self._update_dash(dash_id, data) return build_response(dict(data=updated, code=200))
[ "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
245,224
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): removed_info = dict( time_modified = r_db.zscore(config.DASH_ID_KEY, dash_id), meta = r_db.hget(config.DASH_META_KEY, dash_id), content = r_db.hget(config.DASH_CONTENT_KEY, dash_id)) r_db.zrem(config.DASH_ID_KEY, dash_id) r_db.hdel(c...
[ "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
245,225
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'), ): mkdir_p(checkpoint_dir) encoder_input_path = os.path.jo...
[ "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
245,226
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): h = np.zeros(self.Nh) if h is None else h negE = np.dot(v, self.bv) negE += np.dot(h, self.bh) for j in range(self.Nv): for i in range(j): negE += v[i] * v[j] * self.Wvv[i][j] for i in range(self.Nv): for k in r...
[ "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
245,227
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", ")", ":", "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
245,228
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): return self.replace(text, to_template=to_template, from_template=from_template, name_matcher=name_matcher, url_matcher=url_matcher)
[ "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
245,229
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): if dialogpath is None: args = parse_args() dialogpath = os.path.abspath(os.path.expanduser(args.dialogpath)) else: dialogpath = os.path.abspath(os.path.expanduser(args.dialogpath)) return clean_csvs(dialogpath=dialogpath)
[ "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
245,230
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): 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 in the path if not os.path.exists(os.path.join(directory,...
[ "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
245,231
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): 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
245,232
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): 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))) _logger.info("Script ends here")
[ "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
245,233
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]): output_column_name = list(df.columns)[-1] if output_column_name is None else output_column_name input_column_names = [colname for colname in df.columns if output_column_name != colname] results = np.zeros((len...
[ "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
245,234
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): X = X.values if hasattr(X, 'values') else np.array(X) N, M = X.shape rownums = np.arange(N) np.random.shuffle(rownums) idx = AnnoyIndex(M) for i, row in enumerate(X): idx.add_item(i, row) idx.build(int(np.log2(N)) + 1) if s...
[ "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
245,235
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): 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 = math.sqrt(sum([x**2 for x in vec1])) mag_2 = math.sqrt(sum([x**2 for x in vec2])) retur...
[ "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
245,236
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): # initial sums n = float(len(X)) sum_x = X.sum() sum_y = y.sum() sum_xy = (X * y).sum() sum_xx = (X**2).sum() # formula for w0 self.slope = (sum_xy - (sum_x * sum_y) / n) / (sum_xx - (sum_x * sum_x) / n) # formula for w1 ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "# initial sums", "n", "=", "float", "(", "len", "(", "X", ")", ")", "sum_x", "=", "X", ".", "sum", "(", ")", "sum_y", "=", "y", ".", "sum", "(", ")", "sum_xy", "=", "(", "X", "*", ...
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
245,237
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): if not isinstance(url, basestring): return False if not isinstance(url, basestring) or len(url) >= 1024 or not cre_url.match(url): return False return True
[ "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
245,238
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): 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(url)) return None if parsed_url.scheme: return parsed...
[ "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
245,239
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): parsed_url = try_parse_url(url) if parsed_url is None: return None if parsed_url.scheme.startswith('ftp'): return get_ftp_filemeta(parsed_url) url = parsed_url.geturl() try: r = requests.get(url, stream=True, allow_redirects=True, timeout=5) ...
[ "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
245,240
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): chunksize = chunksize or 32768 if os.path.sep in filename: full_destination_path = filename else: full_destination_path = os.path.join(destination, filename) full_destination_path = exp...
[ "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
245,241
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): if '&id=' in driveid: # https://drive.google.com/uc?export=download&id=0BwmD_VLjROrfM1BxdkxVaTY2bWs # dailymail_stories.tgz driveid = driveid.split('&id=')[-1] if '?id=' in driveid: # 'https://drive...
[ "def", "download_file_from_google_drive", "(", "driveid", ",", "filename", "=", "None", ",", "destination", "=", "os", ".", "path", ".", "curdir", ")", ":", "if", "'&id='", "in", "driveid", ":", "# https://drive.google.com/uc?export=download&id=0BwmD_VLjROrfM1BxdkxVaTY2...
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
245,242
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): if s[0] == 'H': if s[:3] in ['Hi', 'Hi ', 'Hi,', 'Hi!']: return s[:2] elif s[:6] in ['Hello', 'Hello ', 'Hello,', 'Hello!']: return s[:5] elif s[0] == 'Y': if s[1] == 'o' and s[:3] in ['Yo', 'Yo,', 'Yo ', 'Yo!']: return s[:2] ...
[ "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
245,243
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", ":", "# Strip new line", "line", "=", "line", ".", "strip", "(", "'\\n'", ")", "# Ignore empty lines", "if", "line", "!=", "''", ":", "# Ignore comment...
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
245,244
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
245,245
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
245,246
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
245,247
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'))): dfs = {} for subdirs in tqdm(list(product(*subdirectories))): urlspath = os.path.join(dirpath, subdirs[0], 'urls_{}.txt'.format(subdirs[1])) if not os.path.isfile(urlspat...
[ "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
245,248
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", ")", ":", "num_dim", "=", "isglove", "(", "filepath", ")", "tqdm_prog", "=", "tqdm", "if", "verbose", "else", "no_tqdm", "wv", ...
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
245,249
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): pdkwargs = dict(index_col=0, header=None, sep=r'\s', skiprows=[0], verbose=False, engine='python') pdkwargs.update(kwargs) return pd.read_csv(filepath, **pdkwargs)
[ "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
245,250
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_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
245,251
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'): if os.path.isfile(language): filepath = language lang = re.search('[a-z]{3}-eng/', filepath).group()[:3].lower() else: lang = (language or 'deu').lower()[:3] filepath = os.path.join(BIGDATA_PATH, '{}-eng'.format(lang), '{}.txt'.format(lang)) ...
[ "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
245,252
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): bigurls = bigurls or {} for num_dim in (50, 100, 200, 300): # not all of these dimensionality, and training set size combinations were trained by Stanford for suffixes, num_words in zip( ('sm -sm _sm -small _small'...
[ "def", "generate_big_urls_glove", "(", "bigurls", "=", "None", ")", ":", "bigurls", "=", "bigurls", "or", "{", "}", "for", "num_dim", "in", "(", "50", ",", "100", ",", "200", ",", "300", ")", ":", "# not all of these dimensionality, and training set size combina...
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
245,253
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): logger.debug('normalize_ext.filepath=' + str(filepath)) new_file_path = normalize_ext(filepath) logger.debug('download_unzip.new_filepaths=' + str(new_file_path)) # FIXME: fails when name is a url filename filepath = rename_file(filepath, new_file_path) logger...
[ "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
245,254
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): 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.open(fname) as tf: members = tf.getmembers() for member in tqdm(...
[ "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
245,255
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): if ignorecase: if s.lower().endswith(endswith.lower()): return s[:-len(endswith)] else: if s.endswith(endswith): return s[:-len(endswith)] return s
[ "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
245,256
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): if ignorecase: if s.lower().startswith(startswith.lower()): return s[len(startswith):] else: if s.endswith(startswith): return s[len(startswith):] return s
[ "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
245,257
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): dfs = pd.read_html(url, header=header) return longest_table(dfs)
[ "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
245,258
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'): df = get_longest_table(url) columns = list(df.columns) columns[0] = 'ext' columns[1] = 'description' if len(columns) > 2: columns[2] = 'details' df.columns = columns return df
[ "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
245,259
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): # 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 = filemeta['url'] name = filename.split('.') name = (name[0] if name[0] not in ...
[ "def", "create_big_url", "(", "name", ")", ":", "# BIG side effect", "global", "BIG_URLS", "filemeta", "=", "get_url_filemeta", "(", "name", ")", "if", "not", "filemeta", ":", "return", "None", "filename", "=", "filemeta", "[", "'filename'", "]", "remote_size", ...
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
245,260
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): nrows = nrows or limit if name in BIG_URLS: logger.info('Downloading {}'.format(name)) filepaths = download_unzip(name, normalize_filenames=True) logger.debug('nlpia.loaders.get_data.filepaths=' + str(filepaths)) filepath = f...
[ "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
245,261
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): resp = requests.get('https://www.wikidata.org/w/api.php', timeout=5, params={ 'action': 'wbgetentities', 'titles': wikiarticle, 'sites': wikisite, 'props': '', 'format': 'json' }).json() return list(resp['entities'])[0]
[ "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
245,262
totalgood/nlpia
src/nlpia/loaders.py
normalize_column_names
def normalize_column_names(df): r""" Clean up whitespace in column names. See better version at `pugnlp.clean_columns` >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here']) >>> normalize_column_names(df) ['hello_world', 'not_here'] """ columns = df.columns if hasattr(df, ...
python
def normalize_column_names(df): r""" Clean up whitespace in column names. See better version at `pugnlp.clean_columns` >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here']) >>> normalize_column_names(df) ['hello_world', 'not_here'] """ columns = df.columns if hasattr(df, ...
[ "def", "normalize_column_names", "(", "df", ")", ":", "columns", "=", "df", ".", "columns", "if", "hasattr", "(", "df", ",", "'columns'", ")", "else", "df", "columns", "=", "[", "c", ".", "lower", "(", ")", ".", "replace", "(", "' '", ",", "'_'", "...
r""" Clean up whitespace in column names. See better version at `pugnlp.clean_columns` >>> df = pd.DataFrame([[1, 2], [3, 4]], columns=['Hello World', 'not here']) >>> normalize_column_names(df) ['hello_world', 'not_here']
[ "r", "Clean", "up", "whitespace", "in", "column", "names", ".", "See", "better", "version", "at", "pugnlp", ".", "clean_columns" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1167-L1176
245,263
totalgood/nlpia
src/nlpia/loaders.py
clean_column_values
def clean_column_values(df, inplace=True): r""" Convert dollar value strings, numbers with commas, and percents into floating point values >>> df = get_data('us_gov_deficits_raw') >>> df2 = clean_column_values(df, inplace=False) >>> df2.iloc[0] Fiscal year ...
python
def clean_column_values(df, inplace=True): r""" Convert dollar value strings, numbers with commas, and percents into floating point values >>> df = get_data('us_gov_deficits_raw') >>> df2 = clean_column_values(df, inplace=False) >>> df2.iloc[0] Fiscal year ...
[ "def", "clean_column_values", "(", "df", ",", "inplace", "=", "True", ")", ":", "dollars_percents", "=", "re", ".", "compile", "(", "r'[%$,;\\s]+'", ")", "if", "not", "inplace", ":", "df", "=", "df", ".", "copy", "(", ")", "for", "c", "in", "df", "."...
r""" Convert dollar value strings, numbers with commas, and percents into floating point values >>> df = get_data('us_gov_deficits_raw') >>> df2 = clean_column_values(df, inplace=False) >>> df2.iloc[0] Fiscal year 10/2017-3/2018 Presiden...
[ "r", "Convert", "dollar", "value", "strings", "numbers", "with", "commas", "and", "percents", "into", "floating", "point", "values" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1179-L1222
245,264
totalgood/nlpia
src/nlpia/loaders.py
isglove
def isglove(filepath): """ Get the first word vector in a GloVE file and return its dimensionality or False if not a vector >>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt')) False """ with ensure_open(filepath, 'r') as f: header_line = f.readline() vector_line = f.readline(...
python
def isglove(filepath): with ensure_open(filepath, 'r') as f: header_line = f.readline() vector_line = f.readline() try: num_vectors, num_dim = header_line.split() return int(num_dim) except (ValueError, TypeError): pass vector = vector_line.split()[1:] if len(...
[ "def", "isglove", "(", "filepath", ")", ":", "with", "ensure_open", "(", "filepath", ",", "'r'", ")", "as", "f", ":", "header_line", "=", "f", ".", "readline", "(", ")", "vector_line", "=", "f", ".", "readline", "(", ")", "try", ":", "num_vectors", "...
Get the first word vector in a GloVE file and return its dimensionality or False if not a vector >>> isglove(os.path.join(DATA_PATH, 'cats_and_dogs.txt')) False
[ "Get", "the", "first", "word", "vector", "in", "a", "GloVE", "file", "and", "return", "its", "dimensionality", "or", "False", "if", "not", "a", "vector" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1320-L1346
245,265
totalgood/nlpia
src/nlpia/loaders.py
nlp
def nlp(texts, lang='en', linesep=None, verbose=True): r""" Use the SpaCy parser to parse and tag natural language strings. Load the SpaCy parser language model lazily and share it among all nlpia modules. Probably unnecessary, since SpaCy probably takes care of this with `spacy.load()` >>> _parse is ...
python
def nlp(texts, lang='en', linesep=None, verbose=True): r""" Use the SpaCy parser to parse and tag natural language strings. Load the SpaCy parser language model lazily and share it among all nlpia modules. Probably unnecessary, since SpaCy probably takes care of this with `spacy.load()` >>> _parse is ...
[ "def", "nlp", "(", "texts", ",", "lang", "=", "'en'", ",", "linesep", "=", "None", ",", "verbose", "=", "True", ")", ":", "# doesn't let you load a different model anywhere else in the module", "linesep", "=", "os", ".", "linesep", "if", "linesep", "in", "(", ...
r""" Use the SpaCy parser to parse and tag natural language strings. Load the SpaCy parser language model lazily and share it among all nlpia modules. Probably unnecessary, since SpaCy probably takes care of this with `spacy.load()` >>> _parse is None True >>> doc = nlp("Domo arigatto Mr. Roboto."...
[ "r", "Use", "the", "SpaCy", "parser", "to", "parse", "and", "tag", "natural", "language", "strings", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/loaders.py#L1349-L1405
245,266
totalgood/nlpia
src/nlpia/talk.py
get_decoder
def get_decoder(libdir=None, modeldir=None, lang='en-us'): """ Create a decoder with the requested language model """ modeldir = modeldir or (os.path.join(libdir, 'model') if libdir else MODELDIR) libdir = os.path.dirname(modeldir) config = ps.Decoder.default_config() config.set_string('-hmm', os.pa...
python
def get_decoder(libdir=None, modeldir=None, lang='en-us'): modeldir = modeldir or (os.path.join(libdir, 'model') if libdir else MODELDIR) libdir = os.path.dirname(modeldir) config = ps.Decoder.default_config() config.set_string('-hmm', os.path.join(modeldir, lang)) config.set_string('-lm', os.path.j...
[ "def", "get_decoder", "(", "libdir", "=", "None", ",", "modeldir", "=", "None", ",", "lang", "=", "'en-us'", ")", ":", "modeldir", "=", "modeldir", "or", "(", "os", ".", "path", ".", "join", "(", "libdir", ",", "'model'", ")", "if", "libdir", "else",...
Create a decoder with the requested language model
[ "Create", "a", "decoder", "with", "the", "requested", "language", "model" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/talk.py#L43-L52
245,267
totalgood/nlpia
src/nlpia/talk.py
transcribe
def transcribe(decoder, audio_file, libdir=None): """ Decode streaming audio data from raw binary file on disk. """ decoder = get_decoder() decoder.start_utt() stream = open(audio_file, 'rb') while True: buf = stream.read(1024) if buf: decoder.process_raw(buf, False, Fal...
python
def transcribe(decoder, audio_file, libdir=None): decoder = get_decoder() decoder.start_utt() stream = open(audio_file, 'rb') while True: buf = stream.read(1024) if buf: decoder.process_raw(buf, False, False) else: break decoder.end_utt() return e...
[ "def", "transcribe", "(", "decoder", ",", "audio_file", ",", "libdir", "=", "None", ")", ":", "decoder", "=", "get_decoder", "(", ")", "decoder", ".", "start_utt", "(", ")", "stream", "=", "open", "(", "audio_file", ",", "'rb'", ")", "while", "True", "...
Decode streaming audio data from raw binary file on disk.
[ "Decode", "streaming", "audio", "data", "from", "raw", "binary", "file", "on", "disk", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/talk.py#L67-L80
245,268
totalgood/nlpia
src/nlpia/book/examples/ch09.py
pre_process_data
def pre_process_data(filepath): """ This is dependent on your training data source but we will try to generalize it as best as possible. """ positive_path = os.path.join(filepath, 'pos') negative_path = os.path.join(filepath, 'neg') pos_label = 1 neg_label = 0 dataset = [] for fil...
python
def pre_process_data(filepath): positive_path = os.path.join(filepath, 'pos') negative_path = os.path.join(filepath, 'neg') pos_label = 1 neg_label = 0 dataset = [] for filename in glob.glob(os.path.join(positive_path, '*.txt')): with open(filename, 'r') as f: dataset.appe...
[ "def", "pre_process_data", "(", "filepath", ")", ":", "positive_path", "=", "os", ".", "path", ".", "join", "(", "filepath", ",", "'pos'", ")", "negative_path", "=", "os", ".", "path", ".", "join", "(", "filepath", ",", "'neg'", ")", "pos_label", "=", ...
This is dependent on your training data source but we will try to generalize it as best as possible.
[ "This", "is", "dependent", "on", "your", "training", "data", "source", "but", "we", "will", "try", "to", "generalize", "it", "as", "best", "as", "possible", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L141-L163
245,269
totalgood/nlpia
src/nlpia/book/examples/ch09.py
pad_trunc
def pad_trunc(data, maxlen): """ For a given dataset pad with zero vectors or truncate to maxlen """ new_data = [] # Create a vector of 0's the length of our word vectors zero_vector = [] for _ in range(len(data[0][0])): zero_vector.append(0.0) for sample in data: if len(sampl...
python
def pad_trunc(data, maxlen): new_data = [] # Create a vector of 0's the length of our word vectors zero_vector = [] for _ in range(len(data[0][0])): zero_vector.append(0.0) for sample in data: if len(sample) > maxlen: temp = sample[:maxlen] elif len(sample) < m...
[ "def", "pad_trunc", "(", "data", ",", "maxlen", ")", ":", "new_data", "=", "[", "]", "# Create a vector of 0's the length of our word vectors", "zero_vector", "=", "[", "]", "for", "_", "in", "range", "(", "len", "(", "data", "[", "0", "]", "[", "0", "]", ...
For a given dataset pad with zero vectors or truncate to maxlen
[ "For", "a", "given", "dataset", "pad", "with", "zero", "vectors", "or", "truncate", "to", "maxlen" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L207-L228
245,270
totalgood/nlpia
src/nlpia/book/examples/ch09.py
clean_data
def clean_data(data): """ Shift to lower case, replace unknowns with UNK, and listify """ new_data = [] VALID = 'abcdefghijklmnopqrstuvwxyz123456789"\'?!.,:; ' for sample in data: new_sample = [] for char in sample[1].lower(): # Just grab the string, not the label if char in...
python
def clean_data(data): new_data = [] VALID = 'abcdefghijklmnopqrstuvwxyz123456789"\'?!.,:; ' for sample in data: new_sample = [] for char in sample[1].lower(): # Just grab the string, not the label if char in VALID: new_sample.append(char) else: ...
[ "def", "clean_data", "(", "data", ")", ":", "new_data", "=", "[", "]", "VALID", "=", "'abcdefghijklmnopqrstuvwxyz123456789\"\\'?!.,:; '", "for", "sample", "in", "data", ":", "new_sample", "=", "[", "]", "for", "char", "in", "sample", "[", "1", "]", ".", "l...
Shift to lower case, replace unknowns with UNK, and listify
[ "Shift", "to", "lower", "case", "replace", "unknowns", "with", "UNK", "and", "listify" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L436-L449
245,271
totalgood/nlpia
src/nlpia/book/examples/ch09.py
char_pad_trunc
def char_pad_trunc(data, maxlen): """ We truncate to maxlen or add in PAD tokens """ new_dataset = [] for sample in data: if len(sample) > maxlen: new_data = sample[:maxlen] elif len(sample) < maxlen: pads = maxlen - len(sample) new_data = sample + ['PAD']...
python
def char_pad_trunc(data, maxlen): new_dataset = [] for sample in data: if len(sample) > maxlen: new_data = sample[:maxlen] elif len(sample) < maxlen: pads = maxlen - len(sample) new_data = sample + ['PAD'] * pads else: new_data = sample ...
[ "def", "char_pad_trunc", "(", "data", ",", "maxlen", ")", ":", "new_dataset", "=", "[", "]", "for", "sample", "in", "data", ":", "if", "len", "(", "sample", ")", ">", "maxlen", ":", "new_data", "=", "sample", "[", ":", "maxlen", "]", "elif", "len", ...
We truncate to maxlen or add in PAD tokens
[ "We", "truncate", "to", "maxlen", "or", "add", "in", "PAD", "tokens" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L458-L470
245,272
totalgood/nlpia
src/nlpia/book/examples/ch09.py
create_dicts
def create_dicts(data): """ Modified from Keras LSTM example""" chars = set() for sample in data: chars.update(set(sample)) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumerate(chars)) return char_indices, indices_char
python
def create_dicts(data): chars = set() for sample in data: chars.update(set(sample)) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumerate(chars)) return char_indices, indices_char
[ "def", "create_dicts", "(", "data", ")", ":", "chars", "=", "set", "(", ")", "for", "sample", "in", "data", ":", "chars", ".", "update", "(", "set", "(", "sample", ")", ")", "char_indices", "=", "dict", "(", "(", "c", ",", "i", ")", "for", "i", ...
Modified from Keras LSTM example
[ "Modified", "from", "Keras", "LSTM", "example" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L479-L486
245,273
totalgood/nlpia
src/nlpia/book/examples/ch09.py
onehot_encode
def onehot_encode(dataset, char_indices, maxlen): """ One hot encode the tokens Args: dataset list of lists of tokens char_indices dictionary of {key=character, value=index to use encoding vector} maxlen int Length of each sample Return: np array of shape (samples, ...
python
def onehot_encode(dataset, char_indices, maxlen): X = np.zeros((len(dataset), maxlen, len(char_indices.keys()))) for i, sentence in enumerate(dataset): for t, char in enumerate(sentence): X[i, t, char_indices[char]] = 1 return X
[ "def", "onehot_encode", "(", "dataset", ",", "char_indices", ",", "maxlen", ")", ":", "X", "=", "np", ".", "zeros", "(", "(", "len", "(", "dataset", ")", ",", "maxlen", ",", "len", "(", "char_indices", ".", "keys", "(", ")", ")", ")", ")", "for", ...
One hot encode the tokens Args: dataset list of lists of tokens char_indices dictionary of {key=character, value=index to use encoding vector} maxlen int Length of each sample Return: np array of shape (samples, tokens, encoding length)
[ "One", "hot", "encode", "the", "tokens" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch09.py#L495-L510
245,274
totalgood/nlpia
src/nlpia/book/examples/ch04_sklearn_pca_source.py
_fit_full
def _fit_full(self=self, X=X, n_components=6): """Fit the model by computing full SVD on X""" n_samples, n_features = X.shape # Center data self.mean_ = np.mean(X, axis=0) print(self.mean_) X -= self.mean_ print(X.round(2)) U, S, V = linalg.svd(X, full_matrices=False) print(V.round...
python
def _fit_full(self=self, X=X, n_components=6): n_samples, n_features = X.shape # Center data self.mean_ = np.mean(X, axis=0) print(self.mean_) X -= self.mean_ print(X.round(2)) U, S, V = linalg.svd(X, full_matrices=False) print(V.round(2)) # flip eigenvectors' sign to enforce deter...
[ "def", "_fit_full", "(", "self", "=", "self", ",", "X", "=", "X", ",", "n_components", "=", "6", ")", ":", "n_samples", ",", "n_features", "=", "X", ".", "shape", "# Center data", "self", ".", "mean_", "=", "np", ".", "mean", "(", "X", ",", "axis",...
Fit the model by computing full SVD on X
[ "Fit", "the", "model", "by", "computing", "full", "SVD", "on", "X" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch04_sklearn_pca_source.py#L136-L186
245,275
totalgood/nlpia
src/nlpia/clean_alice.py
extract_aiml
def extract_aiml(path='aiml-en-us-foundation-alice.v1-9'): """ Extract an aiml.zip file if it hasn't been already and return a list of aiml file paths """ path = find_data_path(path) or path if os.path.isdir(path): paths = os.listdir(path) paths = [os.path.join(path, p) for p in paths] e...
python
def extract_aiml(path='aiml-en-us-foundation-alice.v1-9'): path = find_data_path(path) or path if os.path.isdir(path): paths = os.listdir(path) paths = [os.path.join(path, p) for p in paths] else: zf = zipfile.ZipFile(path) paths = [] for name in zf.namelist(): ...
[ "def", "extract_aiml", "(", "path", "=", "'aiml-en-us-foundation-alice.v1-9'", ")", ":", "path", "=", "find_data_path", "(", "path", ")", "or", "path", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "paths", "=", "os", ".", "listdir", "(",...
Extract an aiml.zip file if it hasn't been already and return a list of aiml file paths
[ "Extract", "an", "aiml", ".", "zip", "file", "if", "it", "hasn", "t", "been", "already", "and", "return", "a", "list", "of", "aiml", "file", "paths" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/clean_alice.py#L85-L98
245,276
totalgood/nlpia
src/nlpia/clean_alice.py
create_brain
def create_brain(path='aiml-en-us-foundation-alice.v1-9.zip'): """ Create an aiml_bot.Bot brain from an AIML zip file or directory of AIML files """ path = find_data_path(path) or path bot = Bot() num_templates = bot._brain.template_count paths = extract_aiml(path=path) for path in paths: ...
python
def create_brain(path='aiml-en-us-foundation-alice.v1-9.zip'): path = find_data_path(path) or path bot = Bot() num_templates = bot._brain.template_count paths = extract_aiml(path=path) for path in paths: if not path.lower().endswith('.aiml'): continue try: bo...
[ "def", "create_brain", "(", "path", "=", "'aiml-en-us-foundation-alice.v1-9.zip'", ")", ":", "path", "=", "find_data_path", "(", "path", ")", "or", "path", "bot", "=", "Bot", "(", ")", "num_templates", "=", "bot", ".", "_brain", ".", "template_count", "paths",...
Create an aiml_bot.Bot brain from an AIML zip file or directory of AIML files
[ "Create", "an", "aiml_bot", ".", "Bot", "brain", "from", "an", "AIML", "zip", "file", "or", "directory", "of", "AIML", "files" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/clean_alice.py#L101-L119
245,277
totalgood/nlpia
src/nlpia/transcoders.py
minify_urls
def minify_urls(filepath, ext='asc', url_regex=None, output_ext='.urls_minified', access_token=None): """ Use bitly or similar minifier to shrink all URLs in text files within a folder structure. Used for the NLPIA manuscript directory for Manning Publishing bitly API: https://dev.bitly.com/links.html ...
python
def minify_urls(filepath, ext='asc', url_regex=None, output_ext='.urls_minified', access_token=None): access_token = access_token or secrets.bitly.access_token output_ext = output_ext or '' url_regex = regex.compile(url_regex) if isinstance(url_regex, str) else url_regex filemetas = [] for filemeta ...
[ "def", "minify_urls", "(", "filepath", ",", "ext", "=", "'asc'", ",", "url_regex", "=", "None", ",", "output_ext", "=", "'.urls_minified'", ",", "access_token", "=", "None", ")", ":", "access_token", "=", "access_token", "or", "secrets", ".", "bitly", ".", ...
Use bitly or similar minifier to shrink all URLs in text files within a folder structure. Used for the NLPIA manuscript directory for Manning Publishing bitly API: https://dev.bitly.com/links.html Args: path (str): Directory or file path ext (str): File name extension to filter text files by....
[ "Use", "bitly", "or", "similar", "minifier", "to", "shrink", "all", "URLs", "in", "text", "files", "within", "a", "folder", "structure", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L22-L59
245,278
totalgood/nlpia
src/nlpia/transcoders.py
delimit_slug
def delimit_slug(slug, sep=' '): """ Return a str of separated tokens found within a slugLike_This => 'slug Like This' >>> delimit_slug("slugLike_ThisW/aTLA's") 'slug Like This W a TLA s' >>> delimit_slug('slugLike_ThisW/aTLA', '|') 'slug|Like|This|W|a|TLA' """ hyphenated_slug = re.sub(CRE_...
python
def delimit_slug(slug, sep=' '): hyphenated_slug = re.sub(CRE_SLUG_DELIMITTER, sep, slug) return hyphenated_slug
[ "def", "delimit_slug", "(", "slug", ",", "sep", "=", "' '", ")", ":", "hyphenated_slug", "=", "re", ".", "sub", "(", "CRE_SLUG_DELIMITTER", ",", "sep", ",", "slug", ")", "return", "hyphenated_slug" ]
Return a str of separated tokens found within a slugLike_This => 'slug Like This' >>> delimit_slug("slugLike_ThisW/aTLA's") 'slug Like This W a TLA s' >>> delimit_slug('slugLike_ThisW/aTLA', '|') 'slug|Like|This|W|a|TLA'
[ "Return", "a", "str", "of", "separated", "tokens", "found", "within", "a", "slugLike_This", "=", ">", "slug", "Like", "This" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L62-L71
245,279
totalgood/nlpia
src/nlpia/transcoders.py
clean_asciidoc
def clean_asciidoc(text): r""" Transform asciidoc text into ASCII text that NL parsers can handle TODO: Tag lines and words with meta data like italics, underlined, bold, title, heading 1, etc >>> clean_asciidoc('**Hello** _world_!') '"Hello" "world"!' """ text = re.sub(r'(\b|^)[\[_*]{1,...
python
def clean_asciidoc(text): r""" Transform asciidoc text into ASCII text that NL parsers can handle TODO: Tag lines and words with meta data like italics, underlined, bold, title, heading 1, etc >>> clean_asciidoc('**Hello** _world_!') '"Hello" "world"!' """ text = re.sub(r'(\b|^)[\[_*]{1,...
[ "def", "clean_asciidoc", "(", "text", ")", ":", "text", "=", "re", ".", "sub", "(", "r'(\\b|^)[\\[_*]{1,2}([a-zA-Z0-9])'", ",", "r'\"\\2'", ",", "text", ")", "text", "=", "re", ".", "sub", "(", "r'([a-zA-Z0-9])[\\]_*]{1,2}'", ",", "r'\\1\"'", ",", "text", ")...
r""" Transform asciidoc text into ASCII text that NL parsers can handle TODO: Tag lines and words with meta data like italics, underlined, bold, title, heading 1, etc >>> clean_asciidoc('**Hello** _world_!') '"Hello" "world"!'
[ "r", "Transform", "asciidoc", "text", "into", "ASCII", "text", "that", "NL", "parsers", "can", "handle" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L121-L132
245,280
totalgood/nlpia
src/nlpia/transcoders.py
split_sentences_regex
def split_sentences_regex(text): """ Use dead-simple regex to split text into sentences. Very poor accuracy. >>> split_sentences_regex("Hello World. I'm I.B.M.'s Watson. --Watson") ['Hello World.', "I'm I.B.M.'s Watson.", '--Watson'] """ parts = regex.split(r'([a-zA-Z0-9][.?!])[\s$]', text) sen...
python
def split_sentences_regex(text): parts = regex.split(r'([a-zA-Z0-9][.?!])[\s$]', text) sentences = [''.join(s) for s in zip(parts[0::2], parts[1::2])] return sentences + [parts[-1]] if len(parts) % 2 else sentences
[ "def", "split_sentences_regex", "(", "text", ")", ":", "parts", "=", "regex", ".", "split", "(", "r'([a-zA-Z0-9][.?!])[\\s$]'", ",", "text", ")", "sentences", "=", "[", "''", ".", "join", "(", "s", ")", "for", "s", "in", "zip", "(", "parts", "[", "0", ...
Use dead-simple regex to split text into sentences. Very poor accuracy. >>> split_sentences_regex("Hello World. I'm I.B.M.'s Watson. --Watson") ['Hello World.', "I'm I.B.M.'s Watson.", '--Watson']
[ "Use", "dead", "-", "simple", "regex", "to", "split", "text", "into", "sentences", ".", "Very", "poor", "accuracy", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L157-L165
245,281
totalgood/nlpia
src/nlpia/transcoders.py
split_sentences_spacy
def split_sentences_spacy(text, language_model='en'): r""" You must download a spacy language model with python -m download 'en' The default English language model for spacy tends to be a lot more agressive than NLTK's punkt: >>> split_sentences_nltk("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) -...
python
def split_sentences_spacy(text, language_model='en'): r""" You must download a spacy language model with python -m download 'en' The default English language model for spacy tends to be a lot more agressive than NLTK's punkt: >>> split_sentences_nltk("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) -...
[ "def", "split_sentences_spacy", "(", "text", ",", "language_model", "=", "'en'", ")", ":", "doc", "=", "nlp", "(", "text", ")", "sentences", "=", "[", "]", "if", "not", "hasattr", "(", "doc", ",", "'sents'", ")", ":", "logger", ".", "warning", "(", "...
r""" You must download a spacy language model with python -m download 'en' The default English language model for spacy tends to be a lot more agressive than NLTK's punkt: >>> split_sentences_nltk("Hi Ms. Lovelace.\nI'm a wanna-\nbe human @ I.B.M. ;) --Watson 2.0") ['Hi Ms. Lovelace.', "I'm a wanna-\nbe h...
[ "r", "You", "must", "download", "a", "spacy", "language", "model", "with", "python", "-", "m", "download", "en" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L168-L192
245,282
totalgood/nlpia
src/nlpia/transcoders.py
segment_sentences
def segment_sentences(path=os.path.join(DATA_PATH, 'book'), splitter=split_sentences_nltk, **find_files_kwargs): """ Return a list of all sentences and empty lines. TODO: 1. process each line with an aggressive sentence segmenter, like DetectorMorse 2. process our manuscript to create a complet...
python
def segment_sentences(path=os.path.join(DATA_PATH, 'book'), splitter=split_sentences_nltk, **find_files_kwargs): sentences = [] if os.path.isdir(path): for filemeta in find_files(path, **find_files_kwargs): with open(filemeta['path']) as fin: i, batch = 0, [] ...
[ "def", "segment_sentences", "(", "path", "=", "os", ".", "path", ".", "join", "(", "DATA_PATH", ",", "'book'", ")", ",", "splitter", "=", "split_sentences_nltk", ",", "*", "*", "find_files_kwargs", ")", ":", "sentences", "=", "[", "]", "if", "os", ".", ...
Return a list of all sentences and empty lines. TODO: 1. process each line with an aggressive sentence segmenter, like DetectorMorse 2. process our manuscript to create a complete-sentence and heading training set normalized/simplified syntax net tree is the input feature set common word...
[ "Return", "a", "list", "of", "all", "sentences", "and", "empty", "lines", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L216-L267
245,283
totalgood/nlpia
src/nlpia/transcoders.py
fix_hunspell_json
def fix_hunspell_json(badjson_path='en_us.json', goodjson_path='en_us_fixed.json'): """Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings Args: badjson_path (str): path to input json file that doesn't properly quote goodjson_path (str): path to output ...
python
def fix_hunspell_json(badjson_path='en_us.json', goodjson_path='en_us_fixed.json'): with open(badjson_path, 'r') as fin: with open(goodjson_path, 'w') as fout: for i, line in enumerate(fin): line2 = regex.sub(r'\[(\w)', r'["\1', line) line2 = regex.sub(r'(\w)\]', ...
[ "def", "fix_hunspell_json", "(", "badjson_path", "=", "'en_us.json'", ",", "goodjson_path", "=", "'en_us_fixed.json'", ")", ":", "with", "open", "(", "badjson_path", ",", "'r'", ")", "as", "fin", ":", "with", "open", "(", "goodjson_path", ",", "'w'", ")", "a...
Fix the invalid hunspellToJSON.py json format by inserting double-quotes in list of affix strings Args: badjson_path (str): path to input json file that doesn't properly quote goodjson_path (str): path to output json file with properly quoted strings in list of affixes Returns: list of all w...
[ "Fix", "the", "invalid", "hunspellToJSON", ".", "py", "json", "format", "by", "inserting", "double", "-", "quotes", "in", "list", "of", "affix", "strings" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/transcoders.py#L295-L327
245,284
totalgood/nlpia
src/nlpia/book/examples/ch12_retrieval.py
format_ubuntu_dialog
def format_ubuntu_dialog(df): """ Print statements paired with replies, formatted for easy review """ s = '' for i, record in df.iterrows(): statement = list(split_turns(record.Context))[-1] # <1> reply = list(split_turns(record.Utterance))[-1] # <2> s += 'Statement: {}\n'.format(s...
python
def format_ubuntu_dialog(df): s = '' for i, record in df.iterrows(): statement = list(split_turns(record.Context))[-1] # <1> reply = list(split_turns(record.Utterance))[-1] # <2> s += 'Statement: {}\n'.format(statement) s += 'Reply: {}\n\n'.format(reply) return s
[ "def", "format_ubuntu_dialog", "(", "df", ")", ":", "s", "=", "''", "for", "i", ",", "record", "in", "df", ".", "iterrows", "(", ")", ":", "statement", "=", "list", "(", "split_turns", "(", "record", ".", "Context", ")", ")", "[", "-", "1", "]", ...
Print statements paired with replies, formatted for easy review
[ "Print", "statements", "paired", "with", "replies", "formatted", "for", "easy", "review" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book/examples/ch12_retrieval.py#L40-L48
245,285
totalgood/nlpia
src/nlpia/regexes.py
splitext
def splitext(filepath): """ Like os.path.splitext except splits compound extensions as one long one >>> splitext('~/.bashrc.asciidoc.ext.ps4.42') ('~/.bashrc', '.asciidoc.ext.ps4.42') >>> splitext('~/.bash_profile') ('~/.bash_profile', '') """ exts = getattr(CRE_FILENAME_EXT.search(filepath...
python
def splitext(filepath): exts = getattr(CRE_FILENAME_EXT.search(filepath), 'group', str)() return (filepath[:(-len(exts) or None)], exts)
[ "def", "splitext", "(", "filepath", ")", ":", "exts", "=", "getattr", "(", "CRE_FILENAME_EXT", ".", "search", "(", "filepath", ")", ",", "'group'", ",", "str", ")", "(", ")", "return", "(", "filepath", "[", ":", "(", "-", "len", "(", "exts", ")", "...
Like os.path.splitext except splits compound extensions as one long one >>> splitext('~/.bashrc.asciidoc.ext.ps4.42') ('~/.bashrc', '.asciidoc.ext.ps4.42') >>> splitext('~/.bash_profile') ('~/.bash_profile', '')
[ "Like", "os", ".", "path", ".", "splitext", "except", "splits", "compound", "extensions", "as", "one", "long", "one" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/regexes.py#L109-L118
245,286
totalgood/nlpia
src/nlpia/plots.py
offline_plotly_scatter3d
def offline_plotly_scatter3d(df, x=0, y=1, z=-1): """ Plot an offline scatter plot colored according to the categories in the 'name' column. >> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/iris.csv') >> offline_plotly(df) """ data = [] # clusters = [] colors = ...
python
def offline_plotly_scatter3d(df, x=0, y=1, z=-1): data = [] # clusters = [] colors = ['rgb(228,26,28)', 'rgb(55,126,184)', 'rgb(77,175,74)'] # df.columns = clean_columns(df.columns) x = get_array(df, x, default=0) y = get_array(df, y, default=1) z = get_array(df, z, default=-1) for i i...
[ "def", "offline_plotly_scatter3d", "(", "df", ",", "x", "=", "0", ",", "y", "=", "1", ",", "z", "=", "-", "1", ")", ":", "data", "=", "[", "]", "# clusters = []", "colors", "=", "[", "'rgb(228,26,28)'", ",", "'rgb(55,126,184)'", ",", "'rgb(77,175,74)'", ...
Plot an offline scatter plot colored according to the categories in the 'name' column. >> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/iris.csv') >> offline_plotly(df)
[ "Plot", "an", "offline", "scatter", "plot", "colored", "according", "to", "the", "categories", "in", "the", "name", "column", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/plots.py#L107-L172
245,287
totalgood/nlpia
src/nlpia/plots.py
offline_plotly_data
def offline_plotly_data(data, filename=None, config=None, validate=True, default_width='100%', default_height=525, global_requirejs=False): r""" Write a plotly scatter plot to HTML file that doesn't require server >>> from nlpia.loaders import get_data >>> df = get_data('etpinard') ...
python
def offline_plotly_data(data, filename=None, config=None, validate=True, default_width='100%', default_height=525, global_requirejs=False): r""" Write a plotly scatter plot to HTML file that doesn't require server >>> from nlpia.loaders import get_data >>> df = get_data('etpinard') ...
[ "def", "offline_plotly_data", "(", "data", ",", "filename", "=", "None", ",", "config", "=", "None", ",", "validate", "=", "True", ",", "default_width", "=", "'100%'", ",", "default_height", "=", "525", ",", "global_requirejs", "=", "False", ")", ":", "con...
r""" Write a plotly scatter plot to HTML file that doesn't require server >>> from nlpia.loaders import get_data >>> df = get_data('etpinard') # pd.read_csv('https://plot.ly/~etpinard/191.csv') >>> df.columns = [eval(c) if c[0] in '"\'' else str(c) for c in df.columns] >>> data = {'data': [ ... ...
[ "r", "Write", "a", "plotly", "scatter", "plot", "to", "HTML", "file", "that", "doesn", "t", "require", "server" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/plots.py#L189-L223
245,288
totalgood/nlpia
src/nlpia/plots.py
normalize_etpinard_df
def normalize_etpinard_df(df='https://plot.ly/~etpinard/191.csv', columns='x y size text'.split(), category_col='category', possible_categories=['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']): """Reformat a dataframe in etpinard's format for use in plot functions and sklearn models"""...
python
def normalize_etpinard_df(df='https://plot.ly/~etpinard/191.csv', columns='x y size text'.split(), category_col='category', possible_categories=['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']): possible_categories = ['Africa', 'Americas', 'Asia', 'Europe', 'O...
[ "def", "normalize_etpinard_df", "(", "df", "=", "'https://plot.ly/~etpinard/191.csv'", ",", "columns", "=", "'x y size text'", ".", "split", "(", ")", ",", "category_col", "=", "'category'", ",", "possible_categories", "=", "[", "'Africa'", ",", "'Americas'", ",", ...
Reformat a dataframe in etpinard's format for use in plot functions and sklearn models
[ "Reformat", "a", "dataframe", "in", "etpinard", "s", "format", "for", "use", "in", "plot", "functions", "and", "sklearn", "models" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/plots.py#L226-L239
245,289
totalgood/nlpia
src/nlpia/plots.py
offline_plotly_scatter_bubble
def offline_plotly_scatter_bubble(df, x='x', y='y', size_col='size', text_col='text', category_col='category', possible_categories=None, filename=None, config={'displaylogo': False}, x...
python
def offline_plotly_scatter_bubble(df, x='x', y='y', size_col='size', text_col='text', category_col='category', possible_categories=None, filename=None, config={'displaylogo': False}, x...
[ "def", "offline_plotly_scatter_bubble", "(", "df", ",", "x", "=", "'x'", ",", "y", "=", "'y'", ",", "size_col", "=", "'size'", ",", "text_col", "=", "'text'", ",", "category_col", "=", "'category'", ",", "possible_categories", "=", "None", ",", "filename", ...
r"""Interactive scatterplot of a DataFrame with the size and color of circles linke to two columns config keys: fillFrame setBackground displaylogo sendData showLink linkText staticPlot scrollZoom plot3dPixelRatio displayModeBar showTips workspace doubleClick autosizable editable layout keys: ...
[ "r", "Interactive", "scatterplot", "of", "a", "DataFrame", "with", "the", "size", "and", "color", "of", "circles", "linke", "to", "two", "columns" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/plots.py#L242-L316
245,290
totalgood/nlpia
src/nlpia/data_utils.py
format_hex
def format_hex(i, num_bytes=4, prefix='0x'): """ Format hexidecimal string from decimal integer value >>> format_hex(42, num_bytes=8, prefix=None) '0000002a' >>> format_hex(23) '0x0017' """ prefix = str(prefix or '') i = int(i or 0) return prefix + '{0:0{1}x}'.format(i, num_bytes)
python
def format_hex(i, num_bytes=4, prefix='0x'): prefix = str(prefix or '') i = int(i or 0) return prefix + '{0:0{1}x}'.format(i, num_bytes)
[ "def", "format_hex", "(", "i", ",", "num_bytes", "=", "4", ",", "prefix", "=", "'0x'", ")", ":", "prefix", "=", "str", "(", "prefix", "or", "''", ")", "i", "=", "int", "(", "i", "or", "0", ")", "return", "prefix", "+", "'{0:0{1}x}'", ".", "format...
Format hexidecimal string from decimal integer value >>> format_hex(42, num_bytes=8, prefix=None) '0000002a' >>> format_hex(23) '0x0017'
[ "Format", "hexidecimal", "string", "from", "decimal", "integer", "value" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L38-L48
245,291
totalgood/nlpia
src/nlpia/data_utils.py
is_up_url
def is_up_url(url, allow_redirects=False, timeout=5): r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP error code) cleaned up URL (following redirects and possibly adding HTTP schema "ht...
python
def is_up_url(url, allow_redirects=False, timeout=5): r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP error code) cleaned up URL (following redirects and possibly adding HTTP schema "ht...
[ "def", "is_up_url", "(", "url", ",", "allow_redirects", "=", "False", ",", "timeout", "=", "5", ")", ":", "if", "not", "isinstance", "(", "url", ",", "basestring", ")", "or", "'.'", "not", "in", "url", ":", "return", "False", "normalized_url", "=", "pr...
r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP error code) cleaned up URL (following redirects and possibly adding HTTP schema "http://") >>> is_up_url("duckduckgo.com") # a more pri...
[ "r", "Check", "URL", "to", "see", "if", "it", "is", "a", "valid", "web", "page", "return", "the", "redirected", "location", "if", "it", "is" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L83-L122
245,292
totalgood/nlpia
src/nlpia/data_utils.py
get_markdown_levels
def get_markdown_levels(lines, levels=set((0, 1, 2, 3, 4, 5, 6))): r""" Return a list of 2-tuples with a level integer for the heading levels >>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n') [(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')] >>> get_markdown_levels('- bul...
python
def get_markdown_levels(lines, levels=set((0, 1, 2, 3, 4, 5, 6))): r""" Return a list of 2-tuples with a level integer for the heading levels >>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n') [(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')] >>> get_markdown_levels('- bul...
[ "def", "get_markdown_levels", "(", "lines", ",", "levels", "=", "set", "(", "(", "0", ",", "1", ",", "2", ",", "3", ",", "4", ",", "5", ",", "6", ")", ")", ")", ":", "if", "isinstance", "(", "levels", ",", "(", "int", ",", "float", ",", "base...
r""" Return a list of 2-tuples with a level integer for the heading levels >>> get_markdown_levels('paragraph \n##bad\n# hello\n ### world\n') [(0, 'paragraph '), (2, 'bad'), (0, '# hello'), (3, 'world')] >>> get_markdown_levels('- bullet \n##bad\n# hello\n ### world\n') [(0, '- bullet '), (2, 'bad')...
[ "r", "Return", "a", "list", "of", "2", "-", "tuples", "with", "a", "level", "integer", "for", "the", "heading", "levels" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L125-L155
245,293
totalgood/nlpia
src/nlpia/data_utils.py
iter_lines
def iter_lines(url_or_text, ext=None, mode='rt'): r""" Return an iterator over the lines of a file or URI response. >>> len(list(iter_lines('cats_and_dogs.txt'))) 263 >>> len(list(iter_lines(list('abcdefgh')))) 8 >>> len(list(iter_lines('abc\n def\n gh\n'))) 3 >>> len(list(iter_lines('a...
python
def iter_lines(url_or_text, ext=None, mode='rt'): r""" Return an iterator over the lines of a file or URI response. >>> len(list(iter_lines('cats_and_dogs.txt'))) 263 >>> len(list(iter_lines(list('abcdefgh')))) 8 >>> len(list(iter_lines('abc\n def\n gh\n'))) 3 >>> len(list(iter_lines('a...
[ "def", "iter_lines", "(", "url_or_text", ",", "ext", "=", "None", ",", "mode", "=", "'rt'", ")", ":", "if", "url_or_text", "is", "None", "or", "not", "url_or_text", ":", "return", "[", "]", "# url_or_text = 'https://www.fileformat.info/info/charset/UTF-8/list.htm'",...
r""" Return an iterator over the lines of a file or URI response. >>> len(list(iter_lines('cats_and_dogs.txt'))) 263 >>> len(list(iter_lines(list('abcdefgh')))) 8 >>> len(list(iter_lines('abc\n def\n gh\n'))) 3 >>> len(list(iter_lines('abc\n def\n gh'))) 3 >>> 20000 > len(list(iter_...
[ "r", "Return", "an", "iterator", "over", "the", "lines", "of", "a", "file", "or", "URI", "response", "." ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L186-L224
245,294
totalgood/nlpia
src/nlpia/data_utils.py
parse_utf_html
def parse_utf_html(url=os.path.join(DATA_PATH, 'utf8_table.html')): """ Parse HTML table UTF8 char descriptions returning DataFrame with `ascii` and `mutliascii` """ utf = pd.read_html(url) utf = [df for df in utf if len(df) > 1023 and len(df.columns) > 2][0] utf = utf.iloc[:1024] if len(utf) == 1025 el...
python
def parse_utf_html(url=os.path.join(DATA_PATH, 'utf8_table.html')): utf = pd.read_html(url) utf = [df for df in utf if len(df) > 1023 and len(df.columns) > 2][0] utf = utf.iloc[:1024] if len(utf) == 1025 else utf utf.columns = 'char name hex'.split() utf.name = utf.name.str.replace('<control>', 'CON...
[ "def", "parse_utf_html", "(", "url", "=", "os", ".", "path", ".", "join", "(", "DATA_PATH", ",", "'utf8_table.html'", ")", ")", ":", "utf", "=", "pd", ".", "read_html", "(", "url", ")", "utf", "=", "[", "df", "for", "df", "in", "utf", "if", "len", ...
Parse HTML table UTF8 char descriptions returning DataFrame with `ascii` and `mutliascii`
[ "Parse", "HTML", "table", "UTF8", "char", "descriptions", "returning", "DataFrame", "with", "ascii", "and", "mutliascii" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L227-L291
245,295
totalgood/nlpia
src/nlpia/data_utils.py
clean_csvs
def clean_csvs(dialogpath=None): """ Translate non-ASCII characters to spaces or equivalent ASCII characters """ dialogdir = os.dirname(dialogpath) if os.path.isfile(dialogpath) else dialogpath filenames = [dialogpath.split(os.path.sep)[-1]] if os.path.isfile(dialogpath) else os.listdir(dialogpath) for ...
python
def clean_csvs(dialogpath=None): dialogdir = os.dirname(dialogpath) if os.path.isfile(dialogpath) else dialogpath filenames = [dialogpath.split(os.path.sep)[-1]] if os.path.isfile(dialogpath) else os.listdir(dialogpath) for filename in filenames: filepath = os.path.join(dialogdir, filename) ...
[ "def", "clean_csvs", "(", "dialogpath", "=", "None", ")", ":", "dialogdir", "=", "os", ".", "dirname", "(", "dialogpath", ")", "if", "os", ".", "path", ".", "isfile", "(", "dialogpath", ")", "else", "dialogpath", "filenames", "=", "[", "dialogpath", ".",...
Translate non-ASCII characters to spaces or equivalent ASCII characters
[ "Translate", "non", "-", "ASCII", "characters", "to", "spaces", "or", "equivalent", "ASCII", "characters" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L294-L302
245,296
totalgood/nlpia
src/nlpia/data_utils.py
unicode2ascii
def unicode2ascii(text, expand=True): r""" Translate UTF8 characters to ASCII >> unicode2ascii("żółw") zozw utf8_letters = 'ą ę ć ź ż ó ł ń ś “ ” ’'.split() ascii_letters = 'a e c z z o l n s " " \'' """ translate = UTF8_TO_ASCII if not expand else UTF8_TO_MULTIASCII output = '' f...
python
def unicode2ascii(text, expand=True): r""" Translate UTF8 characters to ASCII >> unicode2ascii("żółw") zozw utf8_letters = 'ą ę ć ź ż ó ł ń ś “ ” ’'.split() ascii_letters = 'a e c z z o l n s " " \'' """ translate = UTF8_TO_ASCII if not expand else UTF8_TO_MULTIASCII output = '' f...
[ "def", "unicode2ascii", "(", "text", ",", "expand", "=", "True", ")", ":", "translate", "=", "UTF8_TO_ASCII", "if", "not", "expand", "else", "UTF8_TO_MULTIASCII", "output", "=", "''", "for", "c", "in", "text", ":", "if", "not", "c", "or", "ord", "(", "...
r""" Translate UTF8 characters to ASCII >> unicode2ascii("żółw") zozw utf8_letters = 'ą ę ć ź ż ó ł ń ś “ ” ’'.split() ascii_letters = 'a e c z z o l n s " " \''
[ "r", "Translate", "UTF8", "characters", "to", "ASCII" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L305-L321
245,297
totalgood/nlpia
src/nlpia/data_utils.py
clean_df
def clean_df(df, header=None, **read_csv_kwargs): """ Convert UTF8 characters in a CSV file or dataframe into ASCII Args: df (DataFrame or str): DataFrame or path or url to CSV """ df = read_csv(df, header=header, **read_csv_kwargs) df = df.fillna(' ') for col in df.columns: df[co...
python
def clean_df(df, header=None, **read_csv_kwargs): df = read_csv(df, header=header, **read_csv_kwargs) df = df.fillna(' ') for col in df.columns: df[col] = df[col].apply(unicode2ascii) return df
[ "def", "clean_df", "(", "df", ",", "header", "=", "None", ",", "*", "*", "read_csv_kwargs", ")", ":", "df", "=", "read_csv", "(", "df", ",", "header", "=", "header", ",", "*", "*", "read_csv_kwargs", ")", "df", "=", "df", ".", "fillna", "(", "' '",...
Convert UTF8 characters in a CSV file or dataframe into ASCII Args: df (DataFrame or str): DataFrame or path or url to CSV
[ "Convert", "UTF8", "characters", "in", "a", "CSV", "file", "or", "dataframe", "into", "ASCII" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/data_utils.py#L324-L334
245,298
totalgood/nlpia
src/nlpia/book_parser.py
get_acronyms
def get_acronyms(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript')): """ Find all the 2 and 3-letter acronyms in the manuscript and return as a sorted list of tuples """ acronyms = [] for f, lines in get_lines(manuscript): for line in lines: matches = CRE_ACRONYM.finditer(lin...
python
def get_acronyms(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript')): acronyms = [] for f, lines in get_lines(manuscript): for line in lines: matches = CRE_ACRONYM.finditer(line) if matches: for m in matches: if m.group('a2'): ...
[ "def", "get_acronyms", "(", "manuscript", "=", "os", ".", "path", ".", "expanduser", "(", "'~/code/nlpia/lane/manuscript'", ")", ")", ":", "acronyms", "=", "[", "]", "for", "f", ",", "lines", "in", "get_lines", "(", "manuscript", ")", ":", "for", "line", ...
Find all the 2 and 3-letter acronyms in the manuscript and return as a sorted list of tuples
[ "Find", "all", "the", "2", "and", "3", "-", "letter", "acronyms", "in", "the", "manuscript", "and", "return", "as", "a", "sorted", "list", "of", "tuples" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book_parser.py#L90-L107
245,299
totalgood/nlpia
src/nlpia/book_parser.py
write_glossary
def write_glossary(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript'), linesep=None): """ Compose an asciidoc string with acronyms culled from the manuscript """ linesep = linesep or os.linesep lines = ['[acronyms]', '== Acronyms', '', '[acronyms,template="glossary",id="terms"]'] acronyms = g...
python
def write_glossary(manuscript=os.path.expanduser('~/code/nlpia/lane/manuscript'), linesep=None): linesep = linesep or os.linesep lines = ['[acronyms]', '== Acronyms', '', '[acronyms,template="glossary",id="terms"]'] acronyms = get_acronyms(manuscript) for a in acronyms: lines.append('*{}*:: {} -...
[ "def", "write_glossary", "(", "manuscript", "=", "os", ".", "path", ".", "expanduser", "(", "'~/code/nlpia/lane/manuscript'", ")", ",", "linesep", "=", "None", ")", ":", "linesep", "=", "linesep", "or", "os", ".", "linesep", "lines", "=", "[", "'[acronyms]'"...
Compose an asciidoc string with acronyms culled from the manuscript
[ "Compose", "an", "asciidoc", "string", "with", "acronyms", "culled", "from", "the", "manuscript" ]
efa01126275e9cd3c3a5151a644f1c798a9ec53f
https://github.com/totalgood/nlpia/blob/efa01126275e9cd3c3a5151a644f1c798a9ec53f/src/nlpia/book_parser.py#L110-L117