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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
220,000
lorien/grab
grab/script/crawl.py
save_list
def save_list(lst, path): """ Save items from list to the file. """ with open(path, 'wb') as out: lines = [] for item in lst: if isinstance(item, (six.text_type, six.binary_type)): lines.append(make_str(item)) else: lines.append(ma...
python
def save_list(lst, path): """ Save items from list to the file. """ with open(path, 'wb') as out: lines = [] for item in lst: if isinstance(item, (six.text_type, six.binary_type)): lines.append(make_str(item)) else: lines.append(ma...
[ "def", "save_list", "(", "lst", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'wb'", ")", "as", "out", ":", "lines", "=", "[", "]", "for", "item", "in", "lst", ":", "if", "isinstance", "(", "item", ",", "(", "six", ".", "text_type", ...
Save items from list to the file.
[ "Save", "items", "from", "list", "to", "the", "file", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/script/crawl.py#L57-L69
220,001
lorien/grab
grab/proxylist.py
parse_proxy_line
def parse_proxy_line(line): """ Parse proxy details from the raw text line. The text line could be in one of the following formats: * host:port * host:port:username:password """ line = line.strip() match = RE_SIMPLE_PROXY.search(line) if match: return match.group(1), match....
python
def parse_proxy_line(line): """ Parse proxy details from the raw text line. The text line could be in one of the following formats: * host:port * host:port:username:password """ line = line.strip() match = RE_SIMPLE_PROXY.search(line) if match: return match.group(1), match....
[ "def", "parse_proxy_line", "(", "line", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "match", "=", "RE_SIMPLE_PROXY", ".", "search", "(", "line", ")", "if", "match", ":", "return", "match", ".", "group", "(", "1", ")", ",", "match", ".", ...
Parse proxy details from the raw text line. The text line could be in one of the following formats: * host:port * host:port:username:password
[ "Parse", "proxy", "details", "from", "the", "raw", "text", "line", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/proxylist.py#L32-L51
220,002
lorien/grab
grab/proxylist.py
parse_raw_list_data
def parse_raw_list_data(data, proxy_type='http', proxy_userpwd=None): """Iterate over proxy servers found in the raw data""" if not isinstance(data, six.text_type): data = data.decode('utf-8') for orig_line in data.splitlines(): line = orig_line.strip().replace(' ', '') if line and n...
python
def parse_raw_list_data(data, proxy_type='http', proxy_userpwd=None): """Iterate over proxy servers found in the raw data""" if not isinstance(data, six.text_type): data = data.decode('utf-8') for orig_line in data.splitlines(): line = orig_line.strip().replace(' ', '') if line and n...
[ "def", "parse_raw_list_data", "(", "data", ",", "proxy_type", "=", "'http'", ",", "proxy_userpwd", "=", "None", ")", ":", "if", "not", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", ":", "data", "=", "data", ".", "decode", "(", "'utf-8'", ...
Iterate over proxy servers found in the raw data
[ "Iterate", "over", "proxy", "servers", "found", "in", "the", "raw", "data" ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/proxylist.py#L54-L68
220,003
lorien/grab
grab/proxylist.py
ProxyList.load
def load(self): """Load proxy list from configured proxy source""" self._list = self._source.load() self._list_iter = itertools.cycle(self._list)
python
def load(self): """Load proxy list from configured proxy source""" self._list = self._source.load() self._list_iter = itertools.cycle(self._list)
[ "def", "load", "(", "self", ")", ":", "self", ".", "_list", "=", "self", ".", "_source", ".", "load", "(", ")", "self", ".", "_list_iter", "=", "itertools", ".", "cycle", "(", "self", ".", "_list", ")" ]
Load proxy list from configured proxy source
[ "Load", "proxy", "list", "from", "configured", "proxy", "source" ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/proxylist.py#L156-L159
220,004
lorien/grab
grab/proxylist.py
ProxyList.get_random_proxy
def get_random_proxy(self): """Return random proxy""" idx = randint(0, len(self._list) - 1) return self._list[idx]
python
def get_random_proxy(self): """Return random proxy""" idx = randint(0, len(self._list) - 1) return self._list[idx]
[ "def", "get_random_proxy", "(", "self", ")", ":", "idx", "=", "randint", "(", "0", ",", "len", "(", "self", ".", "_list", ")", "-", "1", ")", "return", "self", ".", "_list", "[", "idx", "]" ]
Return random proxy
[ "Return", "random", "proxy" ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/proxylist.py#L161-L164
220,005
lorien/grab
grab/spider/task.py
Task.clone
def clone(self, **kwargs): """ Clone Task instance. Reset network_try_count, increase task_try_count. Reset priority attribute if it was not set explicitly. """ # First, create exact copy of the current Task object attr_copy = self.__dict__.copy() if att...
python
def clone(self, **kwargs): """ Clone Task instance. Reset network_try_count, increase task_try_count. Reset priority attribute if it was not set explicitly. """ # First, create exact copy of the current Task object attr_copy = self.__dict__.copy() if att...
[ "def", "clone", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# First, create exact copy of the current Task object", "attr_copy", "=", "self", ".", "__dict__", ".", "copy", "(", ")", "if", "attr_copy", ".", "get", "(", "'grab_config'", ")", "is", "not", ...
Clone Task instance. Reset network_try_count, increase task_try_count. Reset priority attribute if it was not set explicitly.
[ "Clone", "Task", "instance", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/spider/task.py#L170-L228
220,006
lorien/grab
grab/base.py
copy_config
def copy_config(config, mutable_config_keys=MUTABLE_CONFIG_KEYS): """ Copy grab config with correct handling of mutable config values. """ cloned_config = copy(config) # Apply ``copy`` function to mutable config values for key in mutable_config_keys: cloned_config[key] = copy(config[key...
python
def copy_config(config, mutable_config_keys=MUTABLE_CONFIG_KEYS): """ Copy grab config with correct handling of mutable config values. """ cloned_config = copy(config) # Apply ``copy`` function to mutable config values for key in mutable_config_keys: cloned_config[key] = copy(config[key...
[ "def", "copy_config", "(", "config", ",", "mutable_config_keys", "=", "MUTABLE_CONFIG_KEYS", ")", ":", "cloned_config", "=", "copy", "(", "config", ")", "# Apply ``copy`` function to mutable config values", "for", "key", "in", "mutable_config_keys", ":", "cloned_config", ...
Copy grab config with correct handling of mutable config values.
[ "Copy", "grab", "config", "with", "correct", "handling", "of", "mutable", "config", "values", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L60-L69
220,007
lorien/grab
grab/base.py
Grab.reset
def reset(self): """ Reset all attributes which could be modified during previous request or which is not initialized yet if this is the new Grab instance. This methods is automatically called before each network request. """ self.request_head = None #self.reque...
python
def reset(self): """ Reset all attributes which could be modified during previous request or which is not initialized yet if this is the new Grab instance. This methods is automatically called before each network request. """ self.request_head = None #self.reque...
[ "def", "reset", "(", "self", ")", ":", "self", ".", "request_head", "=", "None", "#self.request_log = None", "self", ".", "request_body", "=", "None", "self", ".", "request_method", "=", "None", "self", ".", "request_counter", "=", "None", "self", ".", "exce...
Reset all attributes which could be modified during previous request or which is not initialized yet if this is the new Grab instance. This methods is automatically called before each network request.
[ "Reset", "all", "attributes", "which", "could", "be", "modified", "during", "previous", "request", "or", "which", "is", "not", "initialized", "yet", "if", "this", "is", "the", "new", "Grab", "instance", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L280-L295
220,008
lorien/grab
grab/base.py
Grab.clone
def clone(self, **kwargs): """ Create clone of Grab instance. Cloned instance will have the same state: cookies, referrer, response document data :param **kwargs: overrides settings of cloned grab instance """ grab = Grab(transport=self.transport_param) ...
python
def clone(self, **kwargs): """ Create clone of Grab instance. Cloned instance will have the same state: cookies, referrer, response document data :param **kwargs: overrides settings of cloned grab instance """ grab = Grab(transport=self.transport_param) ...
[ "def", "clone", "(", "self", ",", "*", "*", "kwargs", ")", ":", "grab", "=", "Grab", "(", "transport", "=", "self", ".", "transport_param", ")", "grab", ".", "config", "=", "self", ".", "dump_config", "(", ")", "grab", ".", "doc", "=", "self", ".",...
Create clone of Grab instance. Cloned instance will have the same state: cookies, referrer, response document data :param **kwargs: overrides settings of cloned grab instance
[ "Create", "clone", "of", "Grab", "instance", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L297-L320
220,009
lorien/grab
grab/base.py
Grab.adopt
def adopt(self, grab): """ Copy the state of another `Grab` instance. Use case: create backup of current state to the cloned instance and then restore the state from it. """ self.load_config(grab.config) self.doc = grab.doc.copy(new_grab=self) for key ...
python
def adopt(self, grab): """ Copy the state of another `Grab` instance. Use case: create backup of current state to the cloned instance and then restore the state from it. """ self.load_config(grab.config) self.doc = grab.doc.copy(new_grab=self) for key ...
[ "def", "adopt", "(", "self", ",", "grab", ")", ":", "self", ".", "load_config", "(", "grab", ".", "config", ")", "self", ".", "doc", "=", "grab", ".", "doc", ".", "copy", "(", "new_grab", "=", "self", ")", "for", "key", "in", "self", ".", "clonab...
Copy the state of another `Grab` instance. Use case: create backup of current state to the cloned instance and then restore the state from it.
[ "Copy", "the", "state", "of", "another", "Grab", "instance", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L322-L336
220,010
lorien/grab
grab/base.py
Grab.dump_config
def dump_config(self): """ Make clone of current config. """ conf = copy_config(self.config, self.mutable_config_keys) conf['state'] = { 'cookiejar_cookies': list(self.cookies.cookiejar), } return conf
python
def dump_config(self): """ Make clone of current config. """ conf = copy_config(self.config, self.mutable_config_keys) conf['state'] = { 'cookiejar_cookies': list(self.cookies.cookiejar), } return conf
[ "def", "dump_config", "(", "self", ")", ":", "conf", "=", "copy_config", "(", "self", ".", "config", ",", "self", ".", "mutable_config_keys", ")", "conf", "[", "'state'", "]", "=", "{", "'cookiejar_cookies'", ":", "list", "(", "self", ".", "cookies", "."...
Make clone of current config.
[ "Make", "clone", "of", "current", "config", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L338-L347
220,011
lorien/grab
grab/base.py
Grab.load_config
def load_config(self, config): """ Configure grab instance with external config object. """ self.config = copy_config(config, self.mutable_config_keys) if 'cookiejar_cookies' in config['state']: self.cookies = CookieManager.from_cookie_list( config['s...
python
def load_config(self, config): """ Configure grab instance with external config object. """ self.config = copy_config(config, self.mutable_config_keys) if 'cookiejar_cookies' in config['state']: self.cookies = CookieManager.from_cookie_list( config['s...
[ "def", "load_config", "(", "self", ",", "config", ")", ":", "self", ".", "config", "=", "copy_config", "(", "config", ",", "self", ".", "mutable_config_keys", ")", "if", "'cookiejar_cookies'", "in", "config", "[", "'state'", "]", ":", "self", ".", "cookies...
Configure grab instance with external config object.
[ "Configure", "grab", "instance", "with", "external", "config", "object", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L349-L357
220,012
lorien/grab
grab/base.py
Grab.setup
def setup(self, **kwargs): """ Setting up Grab instance configuration. """ for key in kwargs: if key not in self.config.keys(): raise error.GrabMisuseError('Unknown option: %s' % key) if 'url' in kwargs: if self.config.get('url'): ...
python
def setup(self, **kwargs): """ Setting up Grab instance configuration. """ for key in kwargs: if key not in self.config.keys(): raise error.GrabMisuseError('Unknown option: %s' % key) if 'url' in kwargs: if self.config.get('url'): ...
[ "def", "setup", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", "in", "kwargs", ":", "if", "key", "not", "in", "self", ".", "config", ".", "keys", "(", ")", ":", "raise", "error", ".", "GrabMisuseError", "(", "'Unknown option: %s'", "%"...
Setting up Grab instance configuration.
[ "Setting", "up", "Grab", "instance", "configuration", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L359-L371
220,013
lorien/grab
grab/base.py
Grab.download
def download(self, url, location, **kwargs): """ Fetch document located at ``url`` and save to to ``location``. """ doc = self.go(url, **kwargs) with open(location, 'wb') as out: out.write(doc.body) return len(doc.body)
python
def download(self, url, location, **kwargs): """ Fetch document located at ``url`` and save to to ``location``. """ doc = self.go(url, **kwargs) with open(location, 'wb') as out: out.write(doc.body) return len(doc.body)
[ "def", "download", "(", "self", ",", "url", ",", "location", ",", "*", "*", "kwargs", ")", ":", "doc", "=", "self", ".", "go", "(", "url", ",", "*", "*", "kwargs", ")", "with", "open", "(", "location", ",", "'wb'", ")", "as", "out", ":", "out",...
Fetch document located at ``url`` and save to to ``location``.
[ "Fetch", "document", "located", "at", "url", "and", "save", "to", "to", "location", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L384-L392
220,014
lorien/grab
grab/base.py
Grab.prepare_request
def prepare_request(self, **kwargs): """ Configure all things to make real network request. This method is called before doing real request via transport extension. """ if self.transport is None: self.setup_transport(self.transport_param) self.reset()...
python
def prepare_request(self, **kwargs): """ Configure all things to make real network request. This method is called before doing real request via transport extension. """ if self.transport is None: self.setup_transport(self.transport_param) self.reset()...
[ "def", "prepare_request", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "transport", "is", "None", ":", "self", ".", "setup_transport", "(", "self", ".", "transport_param", ")", "self", ".", "reset", "(", ")", "self", ".", "request...
Configure all things to make real network request. This method is called before doing real request via transport extension.
[ "Configure", "all", "things", "to", "make", "real", "network", "request", ".", "This", "method", "is", "called", "before", "doing", "real", "request", "via", "transport", "extension", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L394-L410
220,015
lorien/grab
grab/base.py
Grab.log_request
def log_request(self, extra=''): """ Send request details to logging system. """ # pylint: disable=no-member thread_name = threading.currentThread().getName().lower() # pylint: enable=no-member if thread_name == 'mainthread': thread_name = '' ...
python
def log_request(self, extra=''): """ Send request details to logging system. """ # pylint: disable=no-member thread_name = threading.currentThread().getName().lower() # pylint: enable=no-member if thread_name == 'mainthread': thread_name = '' ...
[ "def", "log_request", "(", "self", ",", "extra", "=", "''", ")", ":", "# pylint: disable=no-member", "thread_name", "=", "threading", ".", "currentThread", "(", ")", ".", "getName", "(", ")", ".", "lower", "(", ")", "# pylint: enable=no-member", "if", "thread_...
Send request details to logging system.
[ "Send", "request", "details", "to", "logging", "system", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L412-L442
220,016
lorien/grab
grab/base.py
Grab.request
def request(self, **kwargs): """ Perform network request. You can specify grab settings in ``**kwargs``. Any keyword argument will be passed to ``self.config``. Returns: ``Document`` objects. """ self.prepare_request(**kwargs) refresh_count = 0 ...
python
def request(self, **kwargs): """ Perform network request. You can specify grab settings in ``**kwargs``. Any keyword argument will be passed to ``self.config``. Returns: ``Document`` objects. """ self.prepare_request(**kwargs) refresh_count = 0 ...
[ "def", "request", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "prepare_request", "(", "*", "*", "kwargs", ")", "refresh_count", "=", "0", "while", "True", ":", "self", ".", "log_request", "(", ")", "try", ":", "self", ".", "transport...
Perform network request. You can specify grab settings in ``**kwargs``. Any keyword argument will be passed to ``self.config``. Returns: ``Document`` objects.
[ "Perform", "network", "request", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L444-L495
220,017
lorien/grab
grab/base.py
Grab.submit
def submit(self, make_request=True, **kwargs): """ Submit current form. :param make_request: if `False` then grab instance will be configured with form post data but request will not be performed For details see `Document.submit()` method Example:: ...
python
def submit(self, make_request=True, **kwargs): """ Submit current form. :param make_request: if `False` then grab instance will be configured with form post data but request will not be performed For details see `Document.submit()` method Example:: ...
[ "def", "submit", "(", "self", ",", "make_request", "=", "True", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "doc", ".", "get_form_request", "(", "*", "*", "kwargs", ")", "if", "result", "[", "'multipart_post'", "]", ":", "self", "....
Submit current form. :param make_request: if `False` then grab instance will be configured with form post data but request will not be performed For details see `Document.submit()` method Example:: # Assume that we going to some page with some form ...
[ "Submit", "current", "form", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L497-L538
220,018
lorien/grab
grab/base.py
Grab.process_request_result
def process_request_result(self, prepare_response_func=None): """ Process result of real request performed via transport extension. """ now = datetime.utcnow() # TODO: move into separate method if self.config['debug_post']: post = self.config['post'] or self....
python
def process_request_result(self, prepare_response_func=None): """ Process result of real request performed via transport extension. """ now = datetime.utcnow() # TODO: move into separate method if self.config['debug_post']: post = self.config['post'] or self....
[ "def", "process_request_result", "(", "self", ",", "prepare_response_func", "=", "None", ")", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "# TODO: move into separate method", "if", "self", ".", "config", "[", "'debug_post'", "]", ":", "post", "=", "s...
Process result of real request performed via transport extension.
[ "Process", "result", "of", "real", "request", "performed", "via", "transport", "extension", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L540-L606
220,019
lorien/grab
grab/base.py
Grab.save_failed_dump
def save_failed_dump(self): """ Save dump of failed request for debugging. This method is called then fatal network exception is raised. The saved dump could be used for debugging the reason of the failure. """ # try/except for safety, to not break live spiders ...
python
def save_failed_dump(self): """ Save dump of failed request for debugging. This method is called then fatal network exception is raised. The saved dump could be used for debugging the reason of the failure. """ # try/except for safety, to not break live spiders ...
[ "def", "save_failed_dump", "(", "self", ")", ":", "# try/except for safety, to not break live spiders", "try", ":", "# FIXME", "if", "(", "self", ".", "transport", ".", "__class__", ".", "__name__", "==", "'Urllib3Transport'", "and", "not", "getattr", "(", "self", ...
Save dump of failed request for debugging. This method is called then fatal network exception is raised. The saved dump could be used for debugging the reason of the failure.
[ "Save", "dump", "of", "failed", "request", "for", "debugging", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L614-L633
220,020
lorien/grab
grab/base.py
Grab.setup_document
def setup_document(self, content, **kwargs): """ Setup `response` object without real network requests. Useful for testing and debuging. All ``**kwargs`` will be passed to `Document` constructor. """ self.reset() if isinstance(content, six.text_type): ...
python
def setup_document(self, content, **kwargs): """ Setup `response` object without real network requests. Useful for testing and debuging. All ``**kwargs`` will be passed to `Document` constructor. """ self.reset() if isinstance(content, six.text_type): ...
[ "def", "setup_document", "(", "self", ",", "content", ",", "*", "*", "kwargs", ")", ":", "self", ".", "reset", "(", ")", "if", "isinstance", "(", "content", ",", "six", ".", "text_type", ")", ":", "raise", "error", ".", "GrabMisuseError", "(", "'Method...
Setup `response` object without real network requests. Useful for testing and debuging. All ``**kwargs`` will be passed to `Document` constructor.
[ "Setup", "response", "object", "without", "real", "network", "requests", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L641-L670
220,021
lorien/grab
grab/base.py
Grab.change_proxy
def change_proxy(self, random=True): """ Set random proxy from proxylist. """ if self.proxylist.size(): if random: proxy = self.proxylist.get_random_proxy() else: proxy = self.proxylist.get_next_proxy() self.setup(proxy...
python
def change_proxy(self, random=True): """ Set random proxy from proxylist. """ if self.proxylist.size(): if random: proxy = self.proxylist.get_random_proxy() else: proxy = self.proxylist.get_next_proxy() self.setup(proxy...
[ "def", "change_proxy", "(", "self", ",", "random", "=", "True", ")", ":", "if", "self", ".", "proxylist", ".", "size", "(", ")", ":", "if", "random", ":", "proxy", "=", "self", ".", "proxylist", ".", "get_random_proxy", "(", ")", "else", ":", "proxy"...
Set random proxy from proxylist.
[ "Set", "random", "proxy", "from", "proxylist", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L672-L686
220,022
lorien/grab
grab/base.py
Grab.make_url_absolute
def make_url_absolute(self, url, resolve_base=False): """ Make url absolute using previous request url as base url. """ if self.config['url']: if resolve_base: ubody = self.doc.unicode_body() base_url = find_base_url(ubody) if ...
python
def make_url_absolute(self, url, resolve_base=False): """ Make url absolute using previous request url as base url. """ if self.config['url']: if resolve_base: ubody = self.doc.unicode_body() base_url = find_base_url(ubody) if ...
[ "def", "make_url_absolute", "(", "self", ",", "url", ",", "resolve_base", "=", "False", ")", ":", "if", "self", ".", "config", "[", "'url'", "]", ":", "if", "resolve_base", ":", "ubody", "=", "self", ".", "doc", ".", "unicode_body", "(", ")", "base_url...
Make url absolute using previous request url as base url.
[ "Make", "url", "absolute", "using", "previous", "request", "url", "as", "base", "url", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L734-L747
220,023
lorien/grab
grab/base.py
Grab.detect_request_method
def detect_request_method(self): """ Analyze request config and find which request method will be used. Returns request method in upper case This method needs simetime when `process_config` method was not called yet. """ method = self.config['method'] ...
python
def detect_request_method(self): """ Analyze request config and find which request method will be used. Returns request method in upper case This method needs simetime when `process_config` method was not called yet. """ method = self.config['method'] ...
[ "def", "detect_request_method", "(", "self", ")", ":", "method", "=", "self", ".", "config", "[", "'method'", "]", "if", "method", ":", "method", "=", "method", ".", "upper", "(", ")", "else", ":", "if", "self", ".", "config", "[", "'post'", "]", "or...
Analyze request config and find which request method will be used. Returns request method in upper case This method needs simetime when `process_config` method was not called yet.
[ "Analyze", "request", "config", "and", "find", "which", "request", "method", "will", "be", "used", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/base.py#L749-L768
220,024
lorien/grab
grab/cookie.py
create_cookie
def create_cookie(name, value, domain, httponly=None, **kwargs): """Creates `cookielib.Cookie` instance""" if domain == 'localhost': domain = '' config = dict( name=name, value=value, version=0, port=None, domain=domain, path='/', secure=False...
python
def create_cookie(name, value, domain, httponly=None, **kwargs): """Creates `cookielib.Cookie` instance""" if domain == 'localhost': domain = '' config = dict( name=name, value=value, version=0, port=None, domain=domain, path='/', secure=False...
[ "def", "create_cookie", "(", "name", ",", "value", ",", "domain", ",", "httponly", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "domain", "==", "'localhost'", ":", "domain", "=", "''", "config", "=", "dict", "(", "name", "=", "name", ",", ...
Creates `cookielib.Cookie` instance
[ "Creates", "cookielib", ".", "Cookie", "instance" ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/cookie.py#L118-L152
220,025
lorien/grab
grab/cookie.py
CookieManager.set
def set(self, name, value, domain, **kwargs): """Add new cookie or replace existing cookie with same parameters. :param name: name of cookie :param value: value of cookie :param kwargs: extra attributes of cookie """ if domain == 'localhost': domain = '' ...
python
def set(self, name, value, domain, **kwargs): """Add new cookie or replace existing cookie with same parameters. :param name: name of cookie :param value: value of cookie :param kwargs: extra attributes of cookie """ if domain == 'localhost': domain = '' ...
[ "def", "set", "(", "self", ",", "name", ",", "value", ",", "domain", ",", "*", "*", "kwargs", ")", ":", "if", "domain", "==", "'localhost'", ":", "domain", "=", "''", "self", ".", "cookiejar", ".", "set_cookie", "(", "create_cookie", "(", "name", ","...
Add new cookie or replace existing cookie with same parameters. :param name: name of cookie :param value: value of cookie :param kwargs: extra attributes of cookie
[ "Add", "new", "cookie", "or", "replace", "existing", "cookie", "with", "same", "parameters", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/cookie.py#L176-L187
220,026
lorien/grab
grab/cookie.py
CookieManager.load_from_file
def load_from_file(self, path): """ Load cookies from the file. Content of file should be a JSON-serialized list of dicts. """ with open(path) as inf: data = inf.read() if data: items = json.loads(data) else: i...
python
def load_from_file(self, path): """ Load cookies from the file. Content of file should be a JSON-serialized list of dicts. """ with open(path) as inf: data = inf.read() if data: items = json.loads(data) else: i...
[ "def", "load_from_file", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ")", "as", "inf", ":", "data", "=", "inf", ".", "read", "(", ")", "if", "data", ":", "items", "=", "json", ".", "loads", "(", "data", ")", "else", ":", "i...
Load cookies from the file. Content of file should be a JSON-serialized list of dicts.
[ "Load", "cookies", "from", "the", "file", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/cookie.py#L245-L261
220,027
lorien/grab
grab/cookie.py
CookieManager.save_to_file
def save_to_file(self, path): """ Dump all cookies to file. Cookies are dumped as JSON-serialized dict of keys and values. """ with open(path, 'w') as out: out.write(json.dumps(self.get_dict()))
python
def save_to_file(self, path): """ Dump all cookies to file. Cookies are dumped as JSON-serialized dict of keys and values. """ with open(path, 'w') as out: out.write(json.dumps(self.get_dict()))
[ "def", "save_to_file", "(", "self", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'w'", ")", "as", "out", ":", "out", ".", "write", "(", "json", ".", "dumps", "(", "self", ".", "get_dict", "(", ")", ")", ")" ]
Dump all cookies to file. Cookies are dumped as JSON-serialized dict of keys and values.
[ "Dump", "all", "cookies", "to", "file", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/cookie.py#L269-L277
220,028
lorien/grab
grab/spider/task_dispatcher_service.py
TaskDispatcherService.process_service_result
def process_service_result(self, result, task, meta=None): """ Process result submitted from any service to task dispatcher service. Result could be: * Task * None * Task instance * ResponseNotValid-based exception * Arbitrary exception * Network ...
python
def process_service_result(self, result, task, meta=None): """ Process result submitted from any service to task dispatcher service. Result could be: * Task * None * Task instance * ResponseNotValid-based exception * Arbitrary exception * Network ...
[ "def", "process_service_result", "(", "self", ",", "result", ",", "task", ",", "meta", "=", "None", ")", ":", "if", "meta", "is", "None", ":", "meta", "=", "{", "}", "if", "isinstance", "(", "result", ",", "Task", ")", ":", "if", "meta", ".", "get"...
Process result submitted from any service to task dispatcher service. Result could be: * Task * None * Task instance * ResponseNotValid-based exception * Arbitrary exception * Network response: {ok, ecode, emsg, error_abbr, exc, grab, grab_config_back...
[ "Process", "result", "submitted", "from", "any", "service", "to", "task", "dispatcher", "service", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/spider/task_dispatcher_service.py#L29-L109
220,029
lorien/grab
grab/deprecated.py
DeprecatedThings.find_link
def find_link(self, href_pattern, make_absolute=True): """ Find link in response body which href value matches ``href_pattern``. Returns found url or None. """ if make_absolute: self.tree.make_links_absolute(self.doc.url) if isinstance(href_pattern, six.tex...
python
def find_link(self, href_pattern, make_absolute=True): """ Find link in response body which href value matches ``href_pattern``. Returns found url or None. """ if make_absolute: self.tree.make_links_absolute(self.doc.url) if isinstance(href_pattern, six.tex...
[ "def", "find_link", "(", "self", ",", "href_pattern", ",", "make_absolute", "=", "True", ")", ":", "if", "make_absolute", ":", "self", ".", "tree", ".", "make_links_absolute", "(", "self", ".", "doc", ".", "url", ")", "if", "isinstance", "(", "href_pattern...
Find link in response body which href value matches ``href_pattern``. Returns found url or None.
[ "Find", "link", "in", "response", "body", "which", "href", "value", "matches", "href_pattern", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L76-L93
220,030
lorien/grab
grab/deprecated.py
DeprecatedThings.find_link_rex
def find_link_rex(self, rex, make_absolute=True): """ Find link matched the given regular expression in response body. Returns found url or None. """ if make_absolute: self.tree.make_links_absolute(self.doc.url) for elem, _, link, _ in self.tree.iterlinks()...
python
def find_link_rex(self, rex, make_absolute=True): """ Find link matched the given regular expression in response body. Returns found url or None. """ if make_absolute: self.tree.make_links_absolute(self.doc.url) for elem, _, link, _ in self.tree.iterlinks()...
[ "def", "find_link_rex", "(", "self", ",", "rex", ",", "make_absolute", "=", "True", ")", ":", "if", "make_absolute", ":", "self", ".", "tree", ".", "make_links_absolute", "(", "self", ".", "doc", ".", "url", ")", "for", "elem", ",", "_", ",", "link", ...
Find link matched the given regular expression in response body. Returns found url or None.
[ "Find", "link", "matched", "the", "given", "regular", "expression", "in", "response", "body", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L96-L113
220,031
lorien/grab
grab/deprecated.py
DeprecatedThings.css_one
def css_one(self, path, default=NULL): """ Get first element which matches the given css path or raise DataNotFound. """ try: return self.css_list(path)[0] except IndexError: if default is NULL: raise DataNotFound('CSS path not...
python
def css_one(self, path, default=NULL): """ Get first element which matches the given css path or raise DataNotFound. """ try: return self.css_list(path)[0] except IndexError: if default is NULL: raise DataNotFound('CSS path not...
[ "def", "css_one", "(", "self", ",", "path", ",", "default", "=", "NULL", ")", ":", "try", ":", "return", "self", ".", "css_list", "(", "path", ")", "[", "0", "]", "except", "IndexError", ":", "if", "default", "is", "NULL", ":", "raise", "DataNotFound...
Get first element which matches the given css path or raise DataNotFound.
[ "Get", "first", "element", "which", "matches", "the", "given", "css", "path", "or", "raise", "DataNotFound", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L150-L162
220,032
lorien/grab
grab/deprecated.py
DeprecatedThings.css_text
def css_text(self, path, default=NULL, smart=False, normalize_space=True): """ Get normalized text of node which matches the css path. """ try: return get_node_text(self.css_one(path), smart=smart, normalize_space=normalize_space) exc...
python
def css_text(self, path, default=NULL, smart=False, normalize_space=True): """ Get normalized text of node which matches the css path. """ try: return get_node_text(self.css_one(path), smart=smart, normalize_space=normalize_space) exc...
[ "def", "css_text", "(", "self", ",", "path", ",", "default", "=", "NULL", ",", "smart", "=", "False", ",", "normalize_space", "=", "True", ")", ":", "try", ":", "return", "get_node_text", "(", "self", ".", "css_one", "(", "path", ")", ",", "smart", "...
Get normalized text of node which matches the css path.
[ "Get", "normalized", "text", "of", "node", "which", "matches", "the", "css", "path", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L173-L185
220,033
lorien/grab
grab/deprecated.py
DeprecatedThings.css_number
def css_number(self, path, default=NULL, ignore_spaces=False, smart=False, make_int=True): """ Find number in normalized text of node which matches the given css path. """ try: text = self.css_text(path, smart=smart) return find_num...
python
def css_number(self, path, default=NULL, ignore_spaces=False, smart=False, make_int=True): """ Find number in normalized text of node which matches the given css path. """ try: text = self.css_text(path, smart=smart) return find_num...
[ "def", "css_number", "(", "self", ",", "path", ",", "default", "=", "NULL", ",", "ignore_spaces", "=", "False", ",", "smart", "=", "False", ",", "make_int", "=", "True", ")", ":", "try", ":", "text", "=", "self", ".", "css_text", "(", "path", ",", ...
Find number in normalized text of node which matches the given css path.
[ "Find", "number", "in", "normalized", "text", "of", "node", "which", "matches", "the", "given", "css", "path", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L188-L203
220,034
lorien/grab
grab/deprecated.py
DeprecatedThings.strip_tags
def strip_tags(self, content, smart=False): """ Strip tags from the HTML content. """ from lxml.html import fromstring return get_node_text(fromstring(content), smart=smart)
python
def strip_tags(self, content, smart=False): """ Strip tags from the HTML content. """ from lxml.html import fromstring return get_node_text(fromstring(content), smart=smart)
[ "def", "strip_tags", "(", "self", ",", "content", ",", "smart", "=", "False", ")", ":", "from", "lxml", ".", "html", "import", "fromstring", "return", "get_node_text", "(", "fromstring", "(", "content", ")", ",", "smart", "=", "smart", ")" ]
Strip tags from the HTML content.
[ "Strip", "tags", "from", "the", "HTML", "content", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/deprecated.py#L230-L236
220,035
lorien/grab
grab/util/misc.py
camel_case_to_underscore
def camel_case_to_underscore(name): """Converts camel_case into CamelCase""" res = RE_TOKEN1.sub(r'\1_\2', name) res = RE_TOKEN2.sub(r'\1_\2', res) return res.lower()
python
def camel_case_to_underscore(name): """Converts camel_case into CamelCase""" res = RE_TOKEN1.sub(r'\1_\2', name) res = RE_TOKEN2.sub(r'\1_\2', res) return res.lower()
[ "def", "camel_case_to_underscore", "(", "name", ")", ":", "res", "=", "RE_TOKEN1", ".", "sub", "(", "r'\\1_\\2'", ",", "name", ")", "res", "=", "RE_TOKEN2", ".", "sub", "(", "r'\\1_\\2'", ",", "res", ")", "return", "res", ".", "lower", "(", ")" ]
Converts camel_case into CamelCase
[ "Converts", "camel_case", "into", "CamelCase" ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/util/misc.py#L8-L12
220,036
lorien/grab
grab/document.py
read_bom
def read_bom(data): """Read the byte order mark in the text, if present, and return the encoding represented by the BOM and the BOM. If no BOM can be detected, (None, None) is returned. """ # common case is no BOM, so this is fast if data and data[0] in _FIRST_CHARS: for bom, encoding i...
python
def read_bom(data): """Read the byte order mark in the text, if present, and return the encoding represented by the BOM and the BOM. If no BOM can be detected, (None, None) is returned. """ # common case is no BOM, so this is fast if data and data[0] in _FIRST_CHARS: for bom, encoding i...
[ "def", "read_bom", "(", "data", ")", ":", "# common case is no BOM, so this is fast", "if", "data", "and", "data", "[", "0", "]", "in", "_FIRST_CHARS", ":", "for", "bom", ",", "encoding", "in", "_BOM_TABLE", ":", "if", "data", ".", "startswith", "(", "bom", ...
Read the byte order mark in the text, if present, and return the encoding represented by the BOM and the BOM. If no BOM can be detected, (None, None) is returned.
[ "Read", "the", "byte", "order", "mark", "in", "the", "text", "if", "present", "and", "return", "the", "encoding", "represented", "by", "the", "BOM", "and", "the", "BOM", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L67-L78
220,037
lorien/grab
grab/document.py
Document.parse
def parse(self, charset=None, headers=None): """ Parse headers. This method is called after Grab instance performs network request. """ if headers: self.headers = headers else: # Parse headers only from last response # There could be ...
python
def parse(self, charset=None, headers=None): """ Parse headers. This method is called after Grab instance performs network request. """ if headers: self.headers = headers else: # Parse headers only from last response # There could be ...
[ "def", "parse", "(", "self", ",", "charset", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "headers", ":", "self", ".", "headers", "=", "headers", "else", ":", "# Parse headers only from last response", "# There could be multiple responses in `self.head`...
Parse headers. This method is called after Grab instance performs network request.
[ "Parse", "headers", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L159-L193
220,038
lorien/grab
grab/document.py
Document.detect_charset
def detect_charset(self): """ Detect charset of the response. Try following methods: * meta[name="Http-Equiv"] * XML declaration * HTTP Content-Type header Ignore unknown charsets. Use utf-8 as fallback charset. """ charset = None ...
python
def detect_charset(self): """ Detect charset of the response. Try following methods: * meta[name="Http-Equiv"] * XML declaration * HTTP Content-Type header Ignore unknown charsets. Use utf-8 as fallback charset. """ charset = None ...
[ "def", "detect_charset", "(", "self", ")", ":", "charset", "=", "None", "body_chunk", "=", "self", ".", "get_body_chunk", "(", ")", "if", "body_chunk", ":", "# Try to extract charset from http-equiv meta tag", "match_charset", "=", "RE_META_CHARSET", ".", "search", ...
Detect charset of the response. Try following methods: * meta[name="Http-Equiv"] * XML declaration * HTTP Content-Type header Ignore unknown charsets. Use utf-8 as fallback charset.
[ "Detect", "charset", "of", "the", "response", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L195-L258
220,039
lorien/grab
grab/document.py
Document.copy
def copy(self, new_grab=None): """ Clone the Response object. """ obj = self.__class__() obj.process_grab(new_grab if new_grab else self.grab) copy_keys = ('status', 'code', 'head', 'body', 'total_time', 'connect_time', 'name_lookup_time', ...
python
def copy(self, new_grab=None): """ Clone the Response object. """ obj = self.__class__() obj.process_grab(new_grab if new_grab else self.grab) copy_keys = ('status', 'code', 'head', 'body', 'total_time', 'connect_time', 'name_lookup_time', ...
[ "def", "copy", "(", "self", ",", "new_grab", "=", "None", ")", ":", "obj", "=", "self", ".", "__class__", "(", ")", "obj", ".", "process_grab", "(", "new_grab", "if", "new_grab", "else", "self", ".", "grab", ")", "copy_keys", "=", "(", "'status'", ",...
Clone the Response object.
[ "Clone", "the", "Response", "object", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L260-L279
220,040
lorien/grab
grab/document.py
Document.save
def save(self, path): """ Save response body to file. """ path_dir = os.path.split(path)[0] if not os.path.exists(path_dir): try: os.makedirs(path_dir) except OSError: pass with open(path, 'wb') as out: ...
python
def save(self, path): """ Save response body to file. """ path_dir = os.path.split(path)[0] if not os.path.exists(path_dir): try: os.makedirs(path_dir) except OSError: pass with open(path, 'wb') as out: ...
[ "def", "save", "(", "self", ",", "path", ")", ":", "path_dir", "=", "os", ".", "path", ".", "split", "(", "path", ")", "[", "0", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "path_dir", ")", ":", "try", ":", "os", ".", "makedirs", ...
Save response body to file.
[ "Save", "response", "body", "to", "file", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L281-L295
220,041
lorien/grab
grab/document.py
Document.save_hash
def save_hash(self, location, basedir, ext=None): """ Save response body into file with special path builded from hash. That allows to lower number of files per directory. :param location: URL of file or something else. It is used to build the SHA1 hash. :par...
python
def save_hash(self, location, basedir, ext=None): """ Save response body into file with special path builded from hash. That allows to lower number of files per directory. :param location: URL of file or something else. It is used to build the SHA1 hash. :par...
[ "def", "save_hash", "(", "self", ",", "location", ",", "basedir", ",", "ext", "=", "None", ")", ":", "if", "isinstance", "(", "location", ",", "six", ".", "text_type", ")", ":", "location", "=", "location", ".", "encode", "(", "'utf-8'", ")", "rel_path...
Save response body into file with special path builded from hash. That allows to lower number of files per directory. :param location: URL of file or something else. It is used to build the SHA1 hash. :param basedir: base directory to save the file. Note that fil...
[ "Save", "response", "body", "into", "file", "with", "special", "path", "builded", "from", "hash", ".", "That", "allows", "to", "lower", "number", "of", "files", "per", "directory", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L297-L336
220,042
lorien/grab
grab/document.py
Document.json
def json(self): """ Return response body deserialized into JSON object. """ if six.PY3: return json.loads(self.body.decode(self.charset)) else: return json.loads(self.body)
python
def json(self): """ Return response body deserialized into JSON object. """ if six.PY3: return json.loads(self.body.decode(self.charset)) else: return json.loads(self.body)
[ "def", "json", "(", "self", ")", ":", "if", "six", ".", "PY3", ":", "return", "json", ".", "loads", "(", "self", ".", "body", ".", "decode", "(", "self", ".", "charset", ")", ")", "else", ":", "return", "json", ".", "loads", "(", "self", ".", "...
Return response body deserialized into JSON object.
[ "Return", "response", "body", "deserialized", "into", "JSON", "object", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L339-L347
220,043
lorien/grab
grab/document.py
Document.browse
def browse(self): """ Save response in temporary file and open it in GUI browser. """ _, path = tempfile.mkstemp() self.save(path) webbrowser.open('file://' + path)
python
def browse(self): """ Save response in temporary file and open it in GUI browser. """ _, path = tempfile.mkstemp() self.save(path) webbrowser.open('file://' + path)
[ "def", "browse", "(", "self", ")", ":", "_", ",", "path", "=", "tempfile", ".", "mkstemp", "(", ")", "self", ".", "save", "(", "path", ")", "webbrowser", ".", "open", "(", "'file://'", "+", "path", ")" ]
Save response in temporary file and open it in GUI browser.
[ "Save", "response", "in", "temporary", "file", "and", "open", "it", "in", "GUI", "browser", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L363-L370
220,044
lorien/grab
grab/document.py
Document.text_search
def text_search(self, anchor, byte=False): """ Search the substring in response body. :param anchor: string to search :param byte: if False then `anchor` should be the unicode string, and search will be performed in `response.unicode_body()` else `anchor` should ...
python
def text_search(self, anchor, byte=False): """ Search the substring in response body. :param anchor: string to search :param byte: if False then `anchor` should be the unicode string, and search will be performed in `response.unicode_body()` else `anchor` should ...
[ "def", "text_search", "(", "self", ",", "anchor", ",", "byte", "=", "False", ")", ":", "if", "isinstance", "(", "anchor", ",", "six", ".", "text_type", ")", ":", "if", "byte", ":", "raise", "GrabMisuseError", "(", "'The anchor should be bytes string in '", "...
Search the substring in response body. :param anchor: string to search :param byte: if False then `anchor` should be the unicode string, and search will be performed in `response.unicode_body()` else `anchor` should be the byte-string and search will be performed in ...
[ "Search", "the", "substring", "in", "response", "body", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L403-L430
220,045
lorien/grab
grab/document.py
Document.text_assert
def text_assert(self, anchor, byte=False): """ If `anchor` is not found then raise `DataNotFound` exception. """ if not self.text_search(anchor, byte=byte): raise DataNotFound(u'Substring not found: %s' % anchor)
python
def text_assert(self, anchor, byte=False): """ If `anchor` is not found then raise `DataNotFound` exception. """ if not self.text_search(anchor, byte=byte): raise DataNotFound(u'Substring not found: %s' % anchor)
[ "def", "text_assert", "(", "self", ",", "anchor", ",", "byte", "=", "False", ")", ":", "if", "not", "self", ".", "text_search", "(", "anchor", ",", "byte", "=", "byte", ")", ":", "raise", "DataNotFound", "(", "u'Substring not found: %s'", "%", "anchor", ...
If `anchor` is not found then raise `DataNotFound` exception.
[ "If", "anchor", "is", "not", "found", "then", "raise", "DataNotFound", "exception", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L432-L438
220,046
lorien/grab
grab/document.py
Document.text_assert_any
def text_assert_any(self, anchors, byte=False): """ If no `anchors` were found then raise `DataNotFound` exception. """ found = False for anchor in anchors: if self.text_search(anchor, byte=byte): found = True break if not foun...
python
def text_assert_any(self, anchors, byte=False): """ If no `anchors` were found then raise `DataNotFound` exception. """ found = False for anchor in anchors: if self.text_search(anchor, byte=byte): found = True break if not foun...
[ "def", "text_assert_any", "(", "self", ",", "anchors", ",", "byte", "=", "False", ")", ":", "found", "=", "False", "for", "anchor", "in", "anchors", ":", "if", "self", ".", "text_search", "(", "anchor", ",", "byte", "=", "byte", ")", ":", "found", "=...
If no `anchors` were found then raise `DataNotFound` exception.
[ "If", "no", "anchors", "were", "found", "then", "raise", "DataNotFound", "exception", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L440-L452
220,047
lorien/grab
grab/document.py
Document.rex_text
def rex_text(self, regexp, flags=0, byte=False, default=NULL): """ Search regular expression in response body and return content of first matching group. :param byte: if False then search is performed in `response.unicode_body()` else the rex is searched in `response.body`. ...
python
def rex_text(self, regexp, flags=0, byte=False, default=NULL): """ Search regular expression in response body and return content of first matching group. :param byte: if False then search is performed in `response.unicode_body()` else the rex is searched in `response.body`. ...
[ "def", "rex_text", "(", "self", ",", "regexp", ",", "flags", "=", "0", ",", "byte", "=", "False", ",", "default", "=", "NULL", ")", ":", "# pylint: disable=no-member", "try", ":", "match", "=", "self", ".", "rex_search", "(", "regexp", ",", "flags", "=...
Search regular expression in response body and return content of first matching group. :param byte: if False then search is performed in `response.unicode_body()` else the rex is searched in `response.body`.
[ "Search", "regular", "expression", "in", "response", "body", "and", "return", "content", "of", "first", "matching", "group", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L456-L474
220,048
lorien/grab
grab/document.py
Document.rex_search
def rex_search(self, regexp, flags=0, byte=False, default=NULL): """ Search the regular expression in response body. :param byte: if False then search is performed in `response.unicode_body()` else the rex is searched in `response.body`. Note: if you use default non-byte mode t...
python
def rex_search(self, regexp, flags=0, byte=False, default=NULL): """ Search the regular expression in response body. :param byte: if False then search is performed in `response.unicode_body()` else the rex is searched in `response.body`. Note: if you use default non-byte mode t...
[ "def", "rex_search", "(", "self", ",", "regexp", ",", "flags", "=", "0", ",", "byte", "=", "False", ",", "default", "=", "NULL", ")", ":", "regexp", "=", "normalize_regexp", "(", "regexp", ",", "flags", ")", "match", "=", "None", "if", "byte", ":", ...
Search the regular expression in response body. :param byte: if False then search is performed in `response.unicode_body()` else the rex is searched in `response.body`. Note: if you use default non-byte mode than do not forget to build your regular expression with re.U flag. R...
[ "Search", "the", "regular", "expression", "in", "response", "body", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L476-L509
220,049
lorien/grab
grab/document.py
Document.rex_assert
def rex_assert(self, rex, byte=False): """ If `rex` expression is not found then raise `DataNotFound` exception. """ self.rex_search(rex, byte=byte)
python
def rex_assert(self, rex, byte=False): """ If `rex` expression is not found then raise `DataNotFound` exception. """ self.rex_search(rex, byte=byte)
[ "def", "rex_assert", "(", "self", ",", "rex", ",", "byte", "=", "False", ")", ":", "self", ".", "rex_search", "(", "rex", ",", "byte", "=", "byte", ")" ]
If `rex` expression is not found then raise `DataNotFound` exception.
[ "If", "rex", "expression", "is", "not", "found", "then", "raise", "DataNotFound", "exception", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L511-L516
220,050
lorien/grab
grab/document.py
Document.pyquery
def pyquery(self): """ Returns pyquery handler. """ if not self._pyquery: from pyquery import PyQuery self._pyquery = PyQuery(self.tree) return self._pyquery
python
def pyquery(self): """ Returns pyquery handler. """ if not self._pyquery: from pyquery import PyQuery self._pyquery = PyQuery(self.tree) return self._pyquery
[ "def", "pyquery", "(", "self", ")", ":", "if", "not", "self", ".", "_pyquery", ":", "from", "pyquery", "import", "PyQuery", "self", ".", "_pyquery", "=", "PyQuery", "(", "self", ".", "tree", ")", "return", "self", ".", "_pyquery" ]
Returns pyquery handler.
[ "Returns", "pyquery", "handler", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L521-L530
220,051
lorien/grab
grab/document.py
Document.unicode_body
def unicode_body(self, ignore_errors=True, fix_special_entities=True): """ Return response body as unicode string. """ if not self._unicode_body: self._unicode_body = self.convert_body_to_unicode( body=self.body, bom=self.bom, ...
python
def unicode_body(self, ignore_errors=True, fix_special_entities=True): """ Return response body as unicode string. """ if not self._unicode_body: self._unicode_body = self.convert_body_to_unicode( body=self.body, bom=self.bom, ...
[ "def", "unicode_body", "(", "self", ",", "ignore_errors", "=", "True", ",", "fix_special_entities", "=", "True", ")", ":", "if", "not", "self", ".", "_unicode_body", ":", "self", ".", "_unicode_body", "=", "self", ".", "convert_body_to_unicode", "(", "body", ...
Return response body as unicode string.
[ "Return", "response", "body", "as", "unicode", "string", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L562-L575
220,052
lorien/grab
grab/document.py
Document.choose_form
def choose_form(self, number=None, xpath=None, name=None, **kwargs): """ Set the default form. :param number: number of form (starting from zero) :param id: value of "id" attribute :param name: value of "name" attribute :param xpath: XPath query :raises: :class:`...
python
def choose_form(self, number=None, xpath=None, name=None, **kwargs): """ Set the default form. :param number: number of form (starting from zero) :param id: value of "id" attribute :param name: value of "name" attribute :param xpath: XPath query :raises: :class:`...
[ "def", "choose_form", "(", "self", ",", "number", "=", "None", ",", "xpath", "=", "None", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "id_", "=", "kwargs", ".", "pop", "(", "'id'", ",", "None", ")", "if", "id_", "is", "not", "N...
Set the default form. :param number: number of form (starting from zero) :param id: value of "id" attribute :param name: value of "name" attribute :param xpath: XPath query :raises: :class:`DataNotFound` if form not found :raises: :class:`GrabMisuseError` if ...
[ "Set", "the", "default", "form", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L688-L743
220,053
lorien/grab
grab/document.py
Document.form
def form(self): """ This attribute points to default form. If form was not selected manually then select the form which has the biggest number of input elements. The form value is just an `lxml.html` form element. Example:: g.go('some URL') # C...
python
def form(self): """ This attribute points to default form. If form was not selected manually then select the form which has the biggest number of input elements. The form value is just an `lxml.html` form element. Example:: g.go('some URL') # C...
[ "def", "form", "(", "self", ")", ":", "if", "self", ".", "_lxml_form", "is", "None", ":", "forms", "=", "[", "(", "idx", ",", "len", "(", "list", "(", "x", ".", "fields", ")", ")", ")", "for", "idx", ",", "x", "in", "enumerate", "(", "self", ...
This attribute points to default form. If form was not selected manually then select the form which has the biggest number of input elements. The form value is just an `lxml.html` form element. Example:: g.go('some URL') # Choose form automatically ...
[ "This", "attribute", "points", "to", "default", "form", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L746-L774
220,054
lorien/grab
grab/document.py
Document.set_input
def set_input(self, name, value): """ Set the value of form element by its `name` attribute. :param name: name of element :param value: value which should be set to element To check/uncheck the checkbox pass boolean value. Example:: g.set_input('sex', 'mal...
python
def set_input(self, name, value): """ Set the value of form element by its `name` attribute. :param name: name of element :param value: value which should be set to element To check/uncheck the checkbox pass boolean value. Example:: g.set_input('sex', 'mal...
[ "def", "set_input", "(", "self", ",", "name", ",", "value", ")", ":", "if", "self", ".", "_lxml_form", "is", "None", ":", "self", ".", "choose_form_by_element", "(", "'.//*[@name=\"%s\"]'", "%", "name", ")", "elem", "=", "self", ".", "form", ".", "inputs...
Set the value of form element by its `name` attribute. :param name: name of element :param value: value which should be set to element To check/uncheck the checkbox pass boolean value. Example:: g.set_input('sex', 'male') # Check the checkbox g.se...
[ "Set", "the", "value", "of", "form", "element", "by", "its", "name", "attribute", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L776-L811
220,055
lorien/grab
grab/document.py
Document.set_input_by_id
def set_input_by_id(self, _id, value): """ Set the value of form element by its `id` attribute. :param _id: id of element :param value: value which should be set to element """ xpath = './/*[@id="%s"]' % _id if self._lxml_form is None: self.choose_fo...
python
def set_input_by_id(self, _id, value): """ Set the value of form element by its `id` attribute. :param _id: id of element :param value: value which should be set to element """ xpath = './/*[@id="%s"]' % _id if self._lxml_form is None: self.choose_fo...
[ "def", "set_input_by_id", "(", "self", ",", "_id", ",", "value", ")", ":", "xpath", "=", "'.//*[@id=\"%s\"]'", "%", "_id", "if", "self", ".", "_lxml_form", "is", "None", ":", "self", ".", "choose_form_by_element", "(", "xpath", ")", "sel", "=", "XpathSelec...
Set the value of form element by its `id` attribute. :param _id: id of element :param value: value which should be set to element
[ "Set", "the", "value", "of", "form", "element", "by", "its", "id", "attribute", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L813-L827
220,056
lorien/grab
grab/document.py
Document.set_input_by_number
def set_input_by_number(self, number, value): """ Set the value of form element by its number in the form :param number: number of element :param value: value which should be set to element """ sel = XpathSelector(self.form) elem = sel.select('.//input[@type="te...
python
def set_input_by_number(self, number, value): """ Set the value of form element by its number in the form :param number: number of element :param value: value which should be set to element """ sel = XpathSelector(self.form) elem = sel.select('.//input[@type="te...
[ "def", "set_input_by_number", "(", "self", ",", "number", ",", "value", ")", ":", "sel", "=", "XpathSelector", "(", "self", ".", "form", ")", "elem", "=", "sel", ".", "select", "(", "'.//input[@type=\"text\"]'", ")", "[", "number", "]", ".", "node", "(",...
Set the value of form element by its number in the form :param number: number of element :param value: value which should be set to element
[ "Set", "the", "value", "of", "form", "element", "by", "its", "number", "in", "the", "form" ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L829-L839
220,057
lorien/grab
grab/document.py
Document.set_input_by_xpath
def set_input_by_xpath(self, xpath, value): """ Set the value of form element by xpath :param xpath: xpath path :param value: value which should be set to element """ elem = self.select(xpath).node() if self._lxml_form is None: # Explicitly set the ...
python
def set_input_by_xpath(self, xpath, value): """ Set the value of form element by xpath :param xpath: xpath path :param value: value which should be set to element """ elem = self.select(xpath).node() if self._lxml_form is None: # Explicitly set the ...
[ "def", "set_input_by_xpath", "(", "self", ",", "xpath", ",", "value", ")", ":", "elem", "=", "self", ".", "select", "(", "xpath", ")", ".", "node", "(", ")", "if", "self", ".", "_lxml_form", "is", "None", ":", "# Explicitly set the default form", "# which ...
Set the value of form element by xpath :param xpath: xpath path :param value: value which should be set to element
[ "Set", "the", "value", "of", "form", "element", "by", "xpath" ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L841-L862
220,058
lorien/grab
grab/document.py
Document.get_form_request
def get_form_request( self, submit_name=None, url=None, extra_post=None, remove_from_post=None): """ Submit default form. :param submit_name: name of button which should be "clicked" to submit form :param url: explicitly specify form action url ...
python
def get_form_request( self, submit_name=None, url=None, extra_post=None, remove_from_post=None): """ Submit default form. :param submit_name: name of button which should be "clicked" to submit form :param url: explicitly specify form action url ...
[ "def", "get_form_request", "(", "self", ",", "submit_name", "=", "None", ",", "url", "=", "None", ",", "extra_post", "=", "None", ",", "remove_from_post", "=", "None", ")", ":", "# pylint: disable=no-member", "post", "=", "self", ".", "form_fields", "(", ")"...
Submit default form. :param submit_name: name of button which should be "clicked" to submit form :param url: explicitly specify form action url :param extra_post: (dict or list of pairs) additional form data which will override data automatically extracted from the form....
[ "Submit", "default", "form", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L869-L978
220,059
lorien/grab
grab/document.py
Document.form_fields
def form_fields(self): """ Return fields of default form. Fill some fields with reasonable values. """ fields = dict(self.form.fields) # pylint: disable=no-member fields_to_remove = set() for key, val in list(fields.items()): if isinstance(val, Che...
python
def form_fields(self): """ Return fields of default form. Fill some fields with reasonable values. """ fields = dict(self.form.fields) # pylint: disable=no-member fields_to_remove = set() for key, val in list(fields.items()): if isinstance(val, Che...
[ "def", "form_fields", "(", "self", ")", ":", "fields", "=", "dict", "(", "self", ".", "form", ".", "fields", ")", "# pylint: disable=no-member", "fields_to_remove", "=", "set", "(", ")", "for", "key", ",", "val", "in", "list", "(", "fields", ".", "items"...
Return fields of default form. Fill some fields with reasonable values.
[ "Return", "fields", "of", "default", "form", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L993-L1048
220,060
maxpumperla/elephas
elephas/utils/functional_utils.py
add_params
def add_params(param_list_left, param_list_right): """Add two lists of parameters one by one :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ res = [] for x, y in zip(param_list_left, param_list_right): res....
python
def add_params(param_list_left, param_list_right): """Add two lists of parameters one by one :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ res = [] for x, y in zip(param_list_left, param_list_right): res....
[ "def", "add_params", "(", "param_list_left", ",", "param_list_right", ")", ":", "res", "=", "[", "]", "for", "x", ",", "y", "in", "zip", "(", "param_list_left", ",", "param_list_right", ")", ":", "res", ".", "append", "(", "x", "+", "y", ")", "return",...
Add two lists of parameters one by one :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays
[ "Add", "two", "lists", "of", "parameters", "one", "by", "one" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L7-L17
220,061
maxpumperla/elephas
elephas/utils/functional_utils.py
subtract_params
def subtract_params(param_list_left, param_list_right): """Subtract two lists of parameters :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ res = [] for x, y in zip(param_list_left, param_list_right): res.a...
python
def subtract_params(param_list_left, param_list_right): """Subtract two lists of parameters :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ res = [] for x, y in zip(param_list_left, param_list_right): res.a...
[ "def", "subtract_params", "(", "param_list_left", ",", "param_list_right", ")", ":", "res", "=", "[", "]", "for", "x", ",", "y", "in", "zip", "(", "param_list_left", ",", "param_list_right", ")", ":", "res", ".", "append", "(", "x", "-", "y", ")", "ret...
Subtract two lists of parameters :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays
[ "Subtract", "two", "lists", "of", "parameters" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L20-L30
220,062
maxpumperla/elephas
elephas/utils/functional_utils.py
get_neutral
def get_neutral(array_list): """Get list of zero-valued numpy arrays for specified list of numpy arrays :param array_list: list of numpy arrays :return: list of zeros of same shape as input """ res = [] for x in array_list: res.append(np.zeros_like(x)) return res
python
def get_neutral(array_list): """Get list of zero-valued numpy arrays for specified list of numpy arrays :param array_list: list of numpy arrays :return: list of zeros of same shape as input """ res = [] for x in array_list: res.append(np.zeros_like(x)) return res
[ "def", "get_neutral", "(", "array_list", ")", ":", "res", "=", "[", "]", "for", "x", "in", "array_list", ":", "res", ".", "append", "(", "np", ".", "zeros_like", "(", "x", ")", ")", "return", "res" ]
Get list of zero-valued numpy arrays for specified list of numpy arrays :param array_list: list of numpy arrays :return: list of zeros of same shape as input
[ "Get", "list", "of", "zero", "-", "valued", "numpy", "arrays", "for", "specified", "list", "of", "numpy", "arrays" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L33-L43
220,063
maxpumperla/elephas
elephas/utils/functional_utils.py
divide_by
def divide_by(array_list, num_workers): """Divide a list of parameters by an integer num_workers. :param array_list: :param num_workers: :return: """ for i, x in enumerate(array_list): array_list[i] /= num_workers return array_list
python
def divide_by(array_list, num_workers): """Divide a list of parameters by an integer num_workers. :param array_list: :param num_workers: :return: """ for i, x in enumerate(array_list): array_list[i] /= num_workers return array_list
[ "def", "divide_by", "(", "array_list", ",", "num_workers", ")", ":", "for", "i", ",", "x", "in", "enumerate", "(", "array_list", ")", ":", "array_list", "[", "i", "]", "/=", "num_workers", "return", "array_list" ]
Divide a list of parameters by an integer num_workers. :param array_list: :param num_workers: :return:
[ "Divide", "a", "list", "of", "parameters", "by", "an", "integer", "num_workers", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L46-L55
220,064
maxpumperla/elephas
elephas/parameter/server.py
HttpServer.start_flask_service
def start_flask_service(self): """Define Flask parameter server service. This HTTP server can do two things: get the current model parameters and update model parameters. After registering the `parameters` and `update` routes, the service will get started. """ a...
python
def start_flask_service(self): """Define Flask parameter server service. This HTTP server can do two things: get the current model parameters and update model parameters. After registering the `parameters` and `update` routes, the service will get started. """ a...
[ "def", "start_flask_service", "(", "self", ")", ":", "app", "=", "Flask", "(", "__name__", ")", "self", ".", "app", "=", "app", "@", "app", ".", "route", "(", "'/'", ")", "def", "home", "(", ")", ":", "return", "'Elephas'", "@", "app", ".", "route"...
Define Flask parameter server service. This HTTP server can do two things: get the current model parameters and update model parameters. After registering the `parameters` and `update` routes, the service will get started.
[ "Define", "Flask", "parameter", "server", "service", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/parameter/server.py#L92-L138
220,065
maxpumperla/elephas
elephas/mllib/adapter.py
to_matrix
def to_matrix(np_array): """Convert numpy array to MLlib Matrix """ if len(np_array.shape) == 2: return Matrices.dense(np_array.shape[0], np_array.shape[1], np_array.ravel()) else: raise Exception("An MLLib Matrix can only be cr...
python
def to_matrix(np_array): """Convert numpy array to MLlib Matrix """ if len(np_array.shape) == 2: return Matrices.dense(np_array.shape[0], np_array.shape[1], np_array.ravel()) else: raise Exception("An MLLib Matrix can only be cr...
[ "def", "to_matrix", "(", "np_array", ")", ":", "if", "len", "(", "np_array", ".", "shape", ")", "==", "2", ":", "return", "Matrices", ".", "dense", "(", "np_array", ".", "shape", "[", "0", "]", ",", "np_array", ".", "shape", "[", "1", "]", ",", "...
Convert numpy array to MLlib Matrix
[ "Convert", "numpy", "array", "to", "MLlib", "Matrix" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/mllib/adapter.py#L11-L20
220,066
maxpumperla/elephas
elephas/mllib/adapter.py
to_vector
def to_vector(np_array): """Convert numpy array to MLlib Vector """ if len(np_array.shape) == 1: return Vectors.dense(np_array) else: raise Exception("An MLLib Vector can only be created from a one-dimensional " + "numpy array, got {}".format(len(np_array.shape)))
python
def to_vector(np_array): """Convert numpy array to MLlib Vector """ if len(np_array.shape) == 1: return Vectors.dense(np_array) else: raise Exception("An MLLib Vector can only be created from a one-dimensional " + "numpy array, got {}".format(len(np_array.shape)))
[ "def", "to_vector", "(", "np_array", ")", ":", "if", "len", "(", "np_array", ".", "shape", ")", "==", "1", ":", "return", "Vectors", ".", "dense", "(", "np_array", ")", "else", ":", "raise", "Exception", "(", "\"An MLLib Vector can only be created from a one-d...
Convert numpy array to MLlib Vector
[ "Convert", "numpy", "array", "to", "MLlib", "Vector" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/mllib/adapter.py#L29-L36
220,067
maxpumperla/elephas
elephas/java/adapter.py
retrieve_keras_weights
def retrieve_keras_weights(java_model): """For a previously imported Keras model, after training it with DL4J Spark, we want to set the resulting weights back to the original Keras model. :param java_model: DL4J model (MultiLayerNetwork or ComputationGraph :return: list of numpy arrays in correct order...
python
def retrieve_keras_weights(java_model): """For a previously imported Keras model, after training it with DL4J Spark, we want to set the resulting weights back to the original Keras model. :param java_model: DL4J model (MultiLayerNetwork or ComputationGraph :return: list of numpy arrays in correct order...
[ "def", "retrieve_keras_weights", "(", "java_model", ")", ":", "weights", "=", "[", "]", "layers", "=", "java_model", ".", "getLayers", "(", ")", "for", "layer", "in", "layers", ":", "params", "=", "layer", ".", "paramTable", "(", ")", "keys", "=", "param...
For a previously imported Keras model, after training it with DL4J Spark, we want to set the resulting weights back to the original Keras model. :param java_model: DL4J model (MultiLayerNetwork or ComputationGraph :return: list of numpy arrays in correct order for model.set_weights(...) of a corresponding ...
[ "For", "a", "previously", "imported", "Keras", "model", "after", "training", "it", "with", "DL4J", "Spark", "we", "want", "to", "set", "the", "resulting", "weights", "back", "to", "the", "original", "Keras", "model", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/java/adapter.py#L35-L52
220,068
maxpumperla/elephas
elephas/ml_model.py
ElephasEstimator._fit
def _fit(self, df): """Private fit method of the Estimator, which trains the model. """ simple_rdd = df_to_simple_rdd(df, categorical=self.get_categorical_labels(), nb_classes=self.get_nb_classes(), features_col=self.getFeaturesCol(), label_col=self.getLabel...
python
def _fit(self, df): """Private fit method of the Estimator, which trains the model. """ simple_rdd = df_to_simple_rdd(df, categorical=self.get_categorical_labels(), nb_classes=self.get_nb_classes(), features_col=self.getFeaturesCol(), label_col=self.getLabel...
[ "def", "_fit", "(", "self", ",", "df", ")", ":", "simple_rdd", "=", "df_to_simple_rdd", "(", "df", ",", "categorical", "=", "self", ".", "get_categorical_labels", "(", ")", ",", "nb_classes", "=", "self", ".", "get_nb_classes", "(", ")", ",", "features_col...
Private fit method of the Estimator, which trains the model.
[ "Private", "fit", "method", "of", "the", "Estimator", "which", "trains", "the", "model", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml_model.py#L72-L99
220,069
maxpumperla/elephas
elephas/ml_model.py
ElephasTransformer._transform
def _transform(self, df): """Private transform method of a Transformer. This serves as batch-prediction method for our purposes. """ output_col = self.getOutputCol() label_col = self.getLabelCol() new_schema = copy.deepcopy(df.schema) new_schema.add(StructField(output_col...
python
def _transform(self, df): """Private transform method of a Transformer. This serves as batch-prediction method for our purposes. """ output_col = self.getOutputCol() label_col = self.getLabelCol() new_schema = copy.deepcopy(df.schema) new_schema.add(StructField(output_col...
[ "def", "_transform", "(", "self", ",", "df", ")", ":", "output_col", "=", "self", ".", "getOutputCol", "(", ")", "label_col", "=", "self", ".", "getLabelCol", "(", ")", "new_schema", "=", "copy", ".", "deepcopy", "(", "df", ".", "schema", ")", "new_sch...
Private transform method of a Transformer. This serves as batch-prediction method for our purposes.
[ "Private", "transform", "method", "of", "a", "Transformer", ".", "This", "serves", "as", "batch", "-", "prediction", "method", "for", "our", "purposes", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml_model.py#L146-L171
220,070
maxpumperla/elephas
elephas/java/ndarray.py
_from_numpy
def _from_numpy(np_array): """ Convert numpy array to nd4j array """ # Convert the numpy array to nd4j context dtype required_dtype = get_np_dtype(get_context_dtype()) if np_array.dtype != required_dtype: raise Exception("{} is required, got {}".format( repr(required_dtype),...
python
def _from_numpy(np_array): """ Convert numpy array to nd4j array """ # Convert the numpy array to nd4j context dtype required_dtype = get_np_dtype(get_context_dtype()) if np_array.dtype != required_dtype: raise Exception("{} is required, got {}".format( repr(required_dtype),...
[ "def", "_from_numpy", "(", "np_array", ")", ":", "# Convert the numpy array to nd4j context dtype", "required_dtype", "=", "get_np_dtype", "(", "get_context_dtype", "(", ")", ")", "if", "np_array", ".", "dtype", "!=", "required_dtype", ":", "raise", "Exception", "(", ...
Convert numpy array to nd4j array
[ "Convert", "numpy", "array", "to", "nd4j", "array" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/java/ndarray.py#L78-L133
220,071
maxpumperla/elephas
elephas/java/ndarray.py
_to_numpy
def _to_numpy(nd4j_array): """ Convert nd4j array to numpy array """ buff = nd4j_array.data() address = buff.pointer().address() dtype = get_context_dtype() mapping = { 'double': ctypes.c_double, 'float': ctypes.c_float } Pointer = ctypes.POINTER(mapping[dtype]) p...
python
def _to_numpy(nd4j_array): """ Convert nd4j array to numpy array """ buff = nd4j_array.data() address = buff.pointer().address() dtype = get_context_dtype() mapping = { 'double': ctypes.c_double, 'float': ctypes.c_float } Pointer = ctypes.POINTER(mapping[dtype]) p...
[ "def", "_to_numpy", "(", "nd4j_array", ")", ":", "buff", "=", "nd4j_array", ".", "data", "(", ")", "address", "=", "buff", ".", "pointer", "(", ")", ".", "address", "(", ")", "dtype", "=", "get_context_dtype", "(", ")", "mapping", "=", "{", "'double'",...
Convert nd4j array to numpy array
[ "Convert", "nd4j", "array", "to", "numpy", "array" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/java/ndarray.py#L136-L150
220,072
maxpumperla/elephas
elephas/utils/rwlock.py
RWLock.acquire_read
def acquire_read(self): """ Acquire a read lock. Several threads can hold this typeof lock. It is exclusive with write locks. """ self.monitor.acquire() while self.rwlock < 0 or self.writers_waiting: self.readers_ok.wait() self.rwlock += 1 self...
python
def acquire_read(self): """ Acquire a read lock. Several threads can hold this typeof lock. It is exclusive with write locks. """ self.monitor.acquire() while self.rwlock < 0 or self.writers_waiting: self.readers_ok.wait() self.rwlock += 1 self...
[ "def", "acquire_read", "(", "self", ")", ":", "self", ".", "monitor", ".", "acquire", "(", ")", "while", "self", ".", "rwlock", "<", "0", "or", "self", ".", "writers_waiting", ":", "self", ".", "readers_ok", ".", "wait", "(", ")", "self", ".", "rwloc...
Acquire a read lock. Several threads can hold this typeof lock. It is exclusive with write locks.
[ "Acquire", "a", "read", "lock", ".", "Several", "threads", "can", "hold", "this", "typeof", "lock", ".", "It", "is", "exclusive", "with", "write", "locks", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rwlock.py#L25-L34
220,073
maxpumperla/elephas
elephas/utils/rwlock.py
RWLock.acquire_write
def acquire_write(self): """ Acquire a write lock. Only one thread can hold this lock, and only when no read locks are also held. """ self.monitor.acquire() while self.rwlock != 0: self.writers_waiting += 1 self.writers_ok.wait() self.w...
python
def acquire_write(self): """ Acquire a write lock. Only one thread can hold this lock, and only when no read locks are also held. """ self.monitor.acquire() while self.rwlock != 0: self.writers_waiting += 1 self.writers_ok.wait() self.w...
[ "def", "acquire_write", "(", "self", ")", ":", "self", ".", "monitor", ".", "acquire", "(", ")", "while", "self", ".", "rwlock", "!=", "0", ":", "self", ".", "writers_waiting", "+=", "1", "self", ".", "writers_ok", ".", "wait", "(", ")", "self", ".",...
Acquire a write lock. Only one thread can hold this lock, and only when no read locks are also held.
[ "Acquire", "a", "write", "lock", ".", "Only", "one", "thread", "can", "hold", "this", "lock", "and", "only", "when", "no", "read", "locks", "are", "also", "held", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rwlock.py#L36-L47
220,074
maxpumperla/elephas
elephas/utils/rwlock.py
RWLock.release
def release(self): """ Release a lock, whether read or write. """ self.monitor.acquire() if self.rwlock < 0: self.rwlock = 0 else: self.rwlock -= 1 wake_writers = self.writers_waiting and self.rwlock == 0 wake_readers = self.writers...
python
def release(self): """ Release a lock, whether read or write. """ self.monitor.acquire() if self.rwlock < 0: self.rwlock = 0 else: self.rwlock -= 1 wake_writers = self.writers_waiting and self.rwlock == 0 wake_readers = self.writers...
[ "def", "release", "(", "self", ")", ":", "self", ".", "monitor", ".", "acquire", "(", ")", "if", "self", ".", "rwlock", "<", "0", ":", "self", ".", "rwlock", "=", "0", "else", ":", "self", ".", "rwlock", "-=", "1", "wake_writers", "=", "self", "....
Release a lock, whether read or write.
[ "Release", "a", "lock", "whether", "read", "or", "write", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rwlock.py#L49-L68
220,075
maxpumperla/elephas
elephas/ml/adapter.py
to_data_frame
def to_data_frame(sc, features, labels, categorical=False): """Convert numpy arrays of features and labels into Spark DataFrame """ lp_rdd = to_labeled_point(sc, features, labels, categorical) sql_context = SQLContext(sc) df = sql_context.createDataFrame(lp_rdd) return df
python
def to_data_frame(sc, features, labels, categorical=False): """Convert numpy arrays of features and labels into Spark DataFrame """ lp_rdd = to_labeled_point(sc, features, labels, categorical) sql_context = SQLContext(sc) df = sql_context.createDataFrame(lp_rdd) return df
[ "def", "to_data_frame", "(", "sc", ",", "features", ",", "labels", ",", "categorical", "=", "False", ")", ":", "lp_rdd", "=", "to_labeled_point", "(", "sc", ",", "features", ",", "labels", ",", "categorical", ")", "sql_context", "=", "SQLContext", "(", "sc...
Convert numpy arrays of features and labels into Spark DataFrame
[ "Convert", "numpy", "arrays", "of", "features", "and", "labels", "into", "Spark", "DataFrame" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml/adapter.py#L9-L15
220,076
maxpumperla/elephas
elephas/ml/adapter.py
from_data_frame
def from_data_frame(df, categorical=False, nb_classes=None): """Convert DataFrame back to pair of numpy arrays """ lp_rdd = df.rdd.map(lambda row: LabeledPoint(row.label, row.features)) features, labels = from_labeled_point(lp_rdd, categorical, nb_classes) return features, labels
python
def from_data_frame(df, categorical=False, nb_classes=None): """Convert DataFrame back to pair of numpy arrays """ lp_rdd = df.rdd.map(lambda row: LabeledPoint(row.label, row.features)) features, labels = from_labeled_point(lp_rdd, categorical, nb_classes) return features, labels
[ "def", "from_data_frame", "(", "df", ",", "categorical", "=", "False", ",", "nb_classes", "=", "None", ")", ":", "lp_rdd", "=", "df", ".", "rdd", ".", "map", "(", "lambda", "row", ":", "LabeledPoint", "(", "row", ".", "label", ",", "row", ".", "featu...
Convert DataFrame back to pair of numpy arrays
[ "Convert", "DataFrame", "back", "to", "pair", "of", "numpy", "arrays" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml/adapter.py#L18-L23
220,077
maxpumperla/elephas
elephas/ml/adapter.py
df_to_simple_rdd
def df_to_simple_rdd(df, categorical=False, nb_classes=None, features_col='features', label_col='label'): """Convert DataFrame into RDD of pairs """ sql_context = df.sql_ctx sql_context.registerDataFrameAsTable(df, "temp_table") selected_df = sql_context.sql( "SELECT {0} AS features, {1} as ...
python
def df_to_simple_rdd(df, categorical=False, nb_classes=None, features_col='features', label_col='label'): """Convert DataFrame into RDD of pairs """ sql_context = df.sql_ctx sql_context.registerDataFrameAsTable(df, "temp_table") selected_df = sql_context.sql( "SELECT {0} AS features, {1} as ...
[ "def", "df_to_simple_rdd", "(", "df", ",", "categorical", "=", "False", ",", "nb_classes", "=", "None", ",", "features_col", "=", "'features'", ",", "label_col", "=", "'label'", ")", ":", "sql_context", "=", "df", ".", "sql_ctx", "sql_context", ".", "registe...
Convert DataFrame into RDD of pairs
[ "Convert", "DataFrame", "into", "RDD", "of", "pairs" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml/adapter.py#L26-L40
220,078
maxpumperla/elephas
elephas/spark_model.py
SparkModel.fit
def fit(self, rdd, epochs=10, batch_size=32, verbose=0, validation_split=0.1): """ Train an elephas model on an RDD. The Keras model configuration as specified in the elephas model is sent to Spark workers, abd each worker will be trained on their data partition. :pa...
python
def fit(self, rdd, epochs=10, batch_size=32, verbose=0, validation_split=0.1): """ Train an elephas model on an RDD. The Keras model configuration as specified in the elephas model is sent to Spark workers, abd each worker will be trained on their data partition. :pa...
[ "def", "fit", "(", "self", ",", "rdd", ",", "epochs", "=", "10", ",", "batch_size", "=", "32", ",", "verbose", "=", "0", ",", "validation_split", "=", "0.1", ")", ":", "print", "(", "'>>> Fit model'", ")", "if", "self", ".", "num_workers", ":", "rdd"...
Train an elephas model on an RDD. The Keras model configuration as specified in the elephas model is sent to Spark workers, abd each worker will be trained on their data partition. :param rdd: RDD with features and labels :param epochs: number of epochs used for training :param ...
[ "Train", "an", "elephas", "model", "on", "an", "RDD", ".", "The", "Keras", "model", "configuration", "as", "specified", "in", "the", "elephas", "model", "is", "sent", "to", "Spark", "workers", "abd", "each", "worker", "will", "be", "trained", "on", "their"...
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L133-L154
220,079
maxpumperla/elephas
elephas/spark_model.py
SparkModel._fit
def _fit(self, rdd, epochs, batch_size, verbose, validation_split): """Protected train method to make wrapping of modes easier """ self._master_network.compile(optimizer=self.master_optimizer, loss=self.master_loss, metric...
python
def _fit(self, rdd, epochs, batch_size, verbose, validation_split): """Protected train method to make wrapping of modes easier """ self._master_network.compile(optimizer=self.master_optimizer, loss=self.master_loss, metric...
[ "def", "_fit", "(", "self", ",", "rdd", ",", "epochs", ",", "batch_size", ",", "verbose", ",", "validation_split", ")", ":", "self", ".", "_master_network", ".", "compile", "(", "optimizer", "=", "self", ".", "master_optimizer", ",", "loss", "=", "self", ...
Protected train method to make wrapping of modes easier
[ "Protected", "train", "method", "to", "make", "wrapping", "of", "modes", "easier" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L156-L197
220,080
maxpumperla/elephas
elephas/spark_model.py
SparkMLlibModel.fit
def fit(self, labeled_points, epochs=10, batch_size=32, verbose=0, validation_split=0.1, categorical=False, nb_classes=None): """Train an elephas model on an RDD of LabeledPoints """ rdd = lp_to_simple_rdd(labeled_points, categorical, nb_classes) rdd = rdd.repartition(self.nu...
python
def fit(self, labeled_points, epochs=10, batch_size=32, verbose=0, validation_split=0.1, categorical=False, nb_classes=None): """Train an elephas model on an RDD of LabeledPoints """ rdd = lp_to_simple_rdd(labeled_points, categorical, nb_classes) rdd = rdd.repartition(self.nu...
[ "def", "fit", "(", "self", ",", "labeled_points", ",", "epochs", "=", "10", ",", "batch_size", "=", "32", ",", "verbose", "=", "0", ",", "validation_split", "=", "0.1", ",", "categorical", "=", "False", ",", "nb_classes", "=", "None", ")", ":", "rdd", ...
Train an elephas model on an RDD of LabeledPoints
[ "Train", "an", "elephas", "model", "on", "an", "RDD", "of", "LabeledPoints" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L235-L242
220,081
maxpumperla/elephas
elephas/spark_model.py
SparkMLlibModel.predict
def predict(self, mllib_data): """Predict probabilities for an RDD of features """ if isinstance(mllib_data, pyspark.mllib.linalg.Matrix): return to_matrix(self._master_network.predict(from_matrix(mllib_data))) elif isinstance(mllib_data, pyspark.mllib.linalg.Vector): ...
python
def predict(self, mllib_data): """Predict probabilities for an RDD of features """ if isinstance(mllib_data, pyspark.mllib.linalg.Matrix): return to_matrix(self._master_network.predict(from_matrix(mllib_data))) elif isinstance(mllib_data, pyspark.mllib.linalg.Vector): ...
[ "def", "predict", "(", "self", ",", "mllib_data", ")", ":", "if", "isinstance", "(", "mllib_data", ",", "pyspark", ".", "mllib", ".", "linalg", ".", "Matrix", ")", ":", "return", "to_matrix", "(", "self", ".", "_master_network", ".", "predict", "(", "fro...
Predict probabilities for an RDD of features
[ "Predict", "probabilities", "for", "an", "RDD", "of", "features" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L244-L253
220,082
maxpumperla/elephas
elephas/worker.py
SparkWorker.train
def train(self, data_iterator): """Train a keras model on a worker """ optimizer = get_optimizer(self.master_optimizer) self.model = model_from_yaml(self.yaml, self.custom_objects) self.model.compile(optimizer=optimizer, loss=self.master_loss, metrics=s...
python
def train(self, data_iterator): """Train a keras model on a worker """ optimizer = get_optimizer(self.master_optimizer) self.model = model_from_yaml(self.yaml, self.custom_objects) self.model.compile(optimizer=optimizer, loss=self.master_loss, metrics=s...
[ "def", "train", "(", "self", ",", "data_iterator", ")", ":", "optimizer", "=", "get_optimizer", "(", "self", ".", "master_optimizer", ")", "self", ".", "model", "=", "model_from_yaml", "(", "self", ".", "yaml", ",", "self", ".", "custom_objects", ")", "sel...
Train a keras model on a worker
[ "Train", "a", "keras", "model", "on", "a", "worker" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/worker.py#L26-L49
220,083
maxpumperla/elephas
elephas/worker.py
AsynchronousSparkWorker.train
def train(self, data_iterator): """Train a keras model on a worker and send asynchronous updates to parameter server """ feature_iterator, label_iterator = tee(data_iterator, 2) x_train = np.asarray([x for x, y in feature_iterator]) y_train = np.asarray([y for x, y in lab...
python
def train(self, data_iterator): """Train a keras model on a worker and send asynchronous updates to parameter server """ feature_iterator, label_iterator = tee(data_iterator, 2) x_train = np.asarray([x for x, y in feature_iterator]) y_train = np.asarray([y for x, y in lab...
[ "def", "train", "(", "self", ",", "data_iterator", ")", ":", "feature_iterator", ",", "label_iterator", "=", "tee", "(", "data_iterator", ",", "2", ")", "x_train", "=", "np", ".", "asarray", "(", "[", "x", "for", "x", ",", "y", "in", "feature_iterator", ...
Train a keras model on a worker and send asynchronous updates to parameter server
[ "Train", "a", "keras", "model", "on", "a", "worker", "and", "send", "asynchronous", "updates", "to", "parameter", "server" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/worker.py#L77-L133
220,084
maxpumperla/elephas
elephas/utils/sockets.py
determine_master
def determine_master(port=4000): """Determine address of master so that workers can connect to it. If the environment variable SPARK_LOCAL_IP is set, that address will be used. :param port: port on which the application runs :return: Master address Example usage: SPARK_LOCAL_IP=127.0.0...
python
def determine_master(port=4000): """Determine address of master so that workers can connect to it. If the environment variable SPARK_LOCAL_IP is set, that address will be used. :param port: port on which the application runs :return: Master address Example usage: SPARK_LOCAL_IP=127.0.0...
[ "def", "determine_master", "(", "port", "=", "4000", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'SPARK_LOCAL_IP'", ")", ":", "return", "os", ".", "environ", "[", "'SPARK_LOCAL_IP'", "]", "+", "\":\"", "+", "str", "(", "port", ")", "else", ...
Determine address of master so that workers can connect to it. If the environment variable SPARK_LOCAL_IP is set, that address will be used. :param port: port on which the application runs :return: Master address Example usage: SPARK_LOCAL_IP=127.0.0.1 spark-submit --master \ l...
[ "Determine", "address", "of", "master", "so", "that", "workers", "can", "connect", "to", "it", ".", "If", "the", "environment", "variable", "SPARK_LOCAL_IP", "is", "set", "that", "address", "will", "be", "used", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/sockets.py#L6-L21
220,085
maxpumperla/elephas
elephas/utils/sockets.py
_receive_all
def _receive_all(socket, num_bytes): """Reads `num_bytes` bytes from the specified socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data """ buffer = '' buffer_size = 0 bytes_left = num_bytes while buffer_size < num_bytes: ...
python
def _receive_all(socket, num_bytes): """Reads `num_bytes` bytes from the specified socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data """ buffer = '' buffer_size = 0 bytes_left = num_bytes while buffer_size < num_bytes: ...
[ "def", "_receive_all", "(", "socket", ",", "num_bytes", ")", ":", "buffer", "=", "''", "buffer_size", "=", "0", "bytes_left", "=", "num_bytes", "while", "buffer_size", "<", "num_bytes", ":", "data", "=", "socket", ".", "recv", "(", "bytes_left", ")", "delt...
Reads `num_bytes` bytes from the specified socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data
[ "Reads", "num_bytes", "bytes", "from", "the", "specified", "socket", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/sockets.py#L24-L42
220,086
maxpumperla/elephas
elephas/utils/sockets.py
receive
def receive(socket, num_bytes=20): """Receive data frame from open socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data """ length = int(_receive_all(socket, num_bytes).decode()) serialized_data = _receive_all(socket, length) retu...
python
def receive(socket, num_bytes=20): """Receive data frame from open socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data """ length = int(_receive_all(socket, num_bytes).decode()) serialized_data = _receive_all(socket, length) retu...
[ "def", "receive", "(", "socket", ",", "num_bytes", "=", "20", ")", ":", "length", "=", "int", "(", "_receive_all", "(", "socket", ",", "num_bytes", ")", ".", "decode", "(", ")", ")", "serialized_data", "=", "_receive_all", "(", "socket", ",", "length", ...
Receive data frame from open socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data
[ "Receive", "data", "frame", "from", "open", "socket", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/sockets.py#L45-L55
220,087
maxpumperla/elephas
elephas/utils/sockets.py
send
def send(socket, data, num_bytes=20): """Send data to specified socket. :param socket: open socket instance :param data: data to send :param num_bytes: number of bytes to read :return: received data """ pickled_data = pickle.dumps(data, -1) length = str(len(pickled_data)).zfill(num_by...
python
def send(socket, data, num_bytes=20): """Send data to specified socket. :param socket: open socket instance :param data: data to send :param num_bytes: number of bytes to read :return: received data """ pickled_data = pickle.dumps(data, -1) length = str(len(pickled_data)).zfill(num_by...
[ "def", "send", "(", "socket", ",", "data", ",", "num_bytes", "=", "20", ")", ":", "pickled_data", "=", "pickle", ".", "dumps", "(", "data", ",", "-", "1", ")", "length", "=", "str", "(", "len", "(", "pickled_data", ")", ")", ".", "zfill", "(", "n...
Send data to specified socket. :param socket: open socket instance :param data: data to send :param num_bytes: number of bytes to read :return: received data
[ "Send", "data", "to", "specified", "socket", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/sockets.py#L58-L71
220,088
maxpumperla/elephas
elephas/utils/rdd_utils.py
to_java_rdd
def to_java_rdd(jsc, features, labels, batch_size): """Convert numpy features and labels into a JavaRDD of DL4J DataSet type. :param jsc: JavaSparkContext from pyjnius :param features: numpy array with features :param labels: numpy array with labels: :return: JavaRDD<DataSet> """ data_s...
python
def to_java_rdd(jsc, features, labels, batch_size): """Convert numpy features and labels into a JavaRDD of DL4J DataSet type. :param jsc: JavaSparkContext from pyjnius :param features: numpy array with features :param labels: numpy array with labels: :return: JavaRDD<DataSet> """ data_s...
[ "def", "to_java_rdd", "(", "jsc", ",", "features", ",", "labels", ",", "batch_size", ")", ":", "data_sets", "=", "java_classes", ".", "ArrayList", "(", ")", "num_batches", "=", "int", "(", "len", "(", "features", ")", "/", "batch_size", ")", "for", "i", ...
Convert numpy features and labels into a JavaRDD of DL4J DataSet type. :param jsc: JavaSparkContext from pyjnius :param features: numpy array with features :param labels: numpy array with labels: :return: JavaRDD<DataSet>
[ "Convert", "numpy", "features", "and", "labels", "into", "a", "JavaRDD", "of", "DL4J", "DataSet", "type", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L16-L35
220,089
maxpumperla/elephas
elephas/utils/rdd_utils.py
to_simple_rdd
def to_simple_rdd(sc, features, labels): """Convert numpy arrays of features and labels into an RDD of pairs. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :return: Spark RDD with feature-label pairs """ pairs = [(x, y) for x,...
python
def to_simple_rdd(sc, features, labels): """Convert numpy arrays of features and labels into an RDD of pairs. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :return: Spark RDD with feature-label pairs """ pairs = [(x, y) for x,...
[ "def", "to_simple_rdd", "(", "sc", ",", "features", ",", "labels", ")", ":", "pairs", "=", "[", "(", "x", ",", "y", ")", "for", "x", ",", "y", "in", "zip", "(", "features", ",", "labels", ")", "]", "return", "sc", ".", "parallelize", "(", "pairs"...
Convert numpy arrays of features and labels into an RDD of pairs. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :return: Spark RDD with feature-label pairs
[ "Convert", "numpy", "arrays", "of", "features", "and", "labels", "into", "an", "RDD", "of", "pairs", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L38-L48
220,090
maxpumperla/elephas
elephas/utils/rdd_utils.py
to_labeled_point
def to_labeled_point(sc, features, labels, categorical=False): """Convert numpy arrays of features and labels into a LabeledPoint RDD for MLlib and ML integration. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :param categorical: bool...
python
def to_labeled_point(sc, features, labels, categorical=False): """Convert numpy arrays of features and labels into a LabeledPoint RDD for MLlib and ML integration. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :param categorical: bool...
[ "def", "to_labeled_point", "(", "sc", ",", "features", ",", "labels", ",", "categorical", "=", "False", ")", ":", "labeled_points", "=", "[", "]", "for", "x", ",", "y", "in", "zip", "(", "features", ",", "labels", ")", ":", "if", "categorical", ":", ...
Convert numpy arrays of features and labels into a LabeledPoint RDD for MLlib and ML integration. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :param categorical: boolean, whether labels are already one-hot encoded or not :return: La...
[ "Convert", "numpy", "arrays", "of", "features", "and", "labels", "into", "a", "LabeledPoint", "RDD", "for", "MLlib", "and", "ML", "integration", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L51-L68
220,091
maxpumperla/elephas
elephas/utils/rdd_utils.py
from_labeled_point
def from_labeled_point(rdd, categorical=False, nb_classes=None): """Convert a LabeledPoint RDD back to a pair of numpy arrays :param rdd: LabeledPoint RDD :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: optional int, indicating the number of class labels...
python
def from_labeled_point(rdd, categorical=False, nb_classes=None): """Convert a LabeledPoint RDD back to a pair of numpy arrays :param rdd: LabeledPoint RDD :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: optional int, indicating the number of class labels...
[ "def", "from_labeled_point", "(", "rdd", ",", "categorical", "=", "False", ",", "nb_classes", "=", "None", ")", ":", "features", "=", "np", ".", "asarray", "(", "rdd", ".", "map", "(", "lambda", "lp", ":", "from_vector", "(", "lp", ".", "features", ")"...
Convert a LabeledPoint RDD back to a pair of numpy arrays :param rdd: LabeledPoint RDD :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: optional int, indicating the number of class labels :return: pair of numpy arrays, features and labels
[ "Convert", "a", "LabeledPoint", "RDD", "back", "to", "a", "pair", "of", "numpy", "arrays" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L71-L89
220,092
maxpumperla/elephas
elephas/utils/rdd_utils.py
encode_label
def encode_label(label, nb_classes): """One-hot encoding of a single label :param label: class label (int or double without floating point digits) :param nb_classes: int, number of total classes :return: one-hot encoded vector """ encoded = np.zeros(nb_classes) encoded[int(label)] = 1. ...
python
def encode_label(label, nb_classes): """One-hot encoding of a single label :param label: class label (int or double without floating point digits) :param nb_classes: int, number of total classes :return: one-hot encoded vector """ encoded = np.zeros(nb_classes) encoded[int(label)] = 1. ...
[ "def", "encode_label", "(", "label", ",", "nb_classes", ")", ":", "encoded", "=", "np", ".", "zeros", "(", "nb_classes", ")", "encoded", "[", "int", "(", "label", ")", "]", "=", "1.", "return", "encoded" ]
One-hot encoding of a single label :param label: class label (int or double without floating point digits) :param nb_classes: int, number of total classes :return: one-hot encoded vector
[ "One", "-", "hot", "encoding", "of", "a", "single", "label" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L92-L101
220,093
maxpumperla/elephas
elephas/utils/rdd_utils.py
lp_to_simple_rdd
def lp_to_simple_rdd(lp_rdd, categorical=False, nb_classes=None): """Convert a LabeledPoint RDD into an RDD of feature-label pairs :param lp_rdd: LabeledPoint RDD of features and labels :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: int, number of total...
python
def lp_to_simple_rdd(lp_rdd, categorical=False, nb_classes=None): """Convert a LabeledPoint RDD into an RDD of feature-label pairs :param lp_rdd: LabeledPoint RDD of features and labels :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: int, number of total...
[ "def", "lp_to_simple_rdd", "(", "lp_rdd", ",", "categorical", "=", "False", ",", "nb_classes", "=", "None", ")", ":", "if", "categorical", ":", "if", "not", "nb_classes", ":", "labels", "=", "np", ".", "asarray", "(", "lp_rdd", ".", "map", "(", "lambda",...
Convert a LabeledPoint RDD into an RDD of feature-label pairs :param lp_rdd: LabeledPoint RDD of features and labels :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: int, number of total classes :return: Spark RDD with feature-label pairs
[ "Convert", "a", "LabeledPoint", "RDD", "into", "an", "RDD", "of", "feature", "-", "label", "pairs" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L104-L121
220,094
lebinh/ngxtop
ngxtop/ngxtop.py
follow
def follow(the_file): """ Follow a given file and yield new lines when they are available, like `tail -f`. """ with open(the_file) as f: f.seek(0, 2) # seek to eof while True: line = f.readline() if not line: time.sleep(0.1) # sleep briefly befor...
python
def follow(the_file): """ Follow a given file and yield new lines when they are available, like `tail -f`. """ with open(the_file) as f: f.seek(0, 2) # seek to eof while True: line = f.readline() if not line: time.sleep(0.1) # sleep briefly befor...
[ "def", "follow", "(", "the_file", ")", ":", "with", "open", "(", "the_file", ")", "as", "f", ":", "f", ".", "seek", "(", "0", ",", "2", ")", "# seek to eof", "while", "True", ":", "line", "=", "f", ".", "readline", "(", ")", "if", "not", "line", ...
Follow a given file and yield new lines when they are available, like `tail -f`.
[ "Follow", "a", "given", "file", "and", "yield", "new", "lines", "when", "they", "are", "available", "like", "tail", "-", "f", "." ]
170caa1cd899de051ab961a3e46f7ecfbfed7764
https://github.com/lebinh/ngxtop/blob/170caa1cd899de051ab961a3e46f7ecfbfed7764/ngxtop/ngxtop.py#L116-L127
220,095
lebinh/ngxtop
ngxtop/ngxtop.py
map_field
def map_field(field, func, dict_sequence): """ Apply given function to value of given key in every dictionary in sequence and set the result as new value for that key. """ for item in dict_sequence: try: item[field] = func(item.get(field, None)) yield item exc...
python
def map_field(field, func, dict_sequence): """ Apply given function to value of given key in every dictionary in sequence and set the result as new value for that key. """ for item in dict_sequence: try: item[field] = func(item.get(field, None)) yield item exc...
[ "def", "map_field", "(", "field", ",", "func", ",", "dict_sequence", ")", ":", "for", "item", "in", "dict_sequence", ":", "try", ":", "item", "[", "field", "]", "=", "func", "(", "item", ".", "get", "(", "field", ",", "None", ")", ")", "yield", "it...
Apply given function to value of given key in every dictionary in sequence and set the result as new value for that key.
[ "Apply", "given", "function", "to", "value", "of", "given", "key", "in", "every", "dictionary", "in", "sequence", "and", "set", "the", "result", "as", "new", "value", "for", "that", "key", "." ]
170caa1cd899de051ab961a3e46f7ecfbfed7764
https://github.com/lebinh/ngxtop/blob/170caa1cd899de051ab961a3e46f7ecfbfed7764/ngxtop/ngxtop.py#L130-L140
220,096
lebinh/ngxtop
ngxtop/ngxtop.py
add_field
def add_field(field, func, dict_sequence): """ Apply given function to the record and store result in given field of current record. Do nothing if record already contains given field. """ for item in dict_sequence: if field not in item: item[field] = func(item) yield item
python
def add_field(field, func, dict_sequence): """ Apply given function to the record and store result in given field of current record. Do nothing if record already contains given field. """ for item in dict_sequence: if field not in item: item[field] = func(item) yield item
[ "def", "add_field", "(", "field", ",", "func", ",", "dict_sequence", ")", ":", "for", "item", "in", "dict_sequence", ":", "if", "field", "not", "in", "item", ":", "item", "[", "field", "]", "=", "func", "(", "item", ")", "yield", "item" ]
Apply given function to the record and store result in given field of current record. Do nothing if record already contains given field.
[ "Apply", "given", "function", "to", "the", "record", "and", "store", "result", "in", "given", "field", "of", "current", "record", ".", "Do", "nothing", "if", "record", "already", "contains", "given", "field", "." ]
170caa1cd899de051ab961a3e46f7ecfbfed7764
https://github.com/lebinh/ngxtop/blob/170caa1cd899de051ab961a3e46f7ecfbfed7764/ngxtop/ngxtop.py#L143-L151
220,097
dedupeio/dedupe
dedupe/canonical.py
getCanonicalRep
def getCanonicalRep(record_cluster): """ Given a list of records within a duplicate cluster, constructs a canonical representation of the cluster by finding canonical values for each field """ canonical_rep = {} keys = record_cluster[0].keys() for key in keys: key_values = [] ...
python
def getCanonicalRep(record_cluster): """ Given a list of records within a duplicate cluster, constructs a canonical representation of the cluster by finding canonical values for each field """ canonical_rep = {} keys = record_cluster[0].keys() for key in keys: key_values = [] ...
[ "def", "getCanonicalRep", "(", "record_cluster", ")", ":", "canonical_rep", "=", "{", "}", "keys", "=", "record_cluster", "[", "0", "]", ".", "keys", "(", ")", "for", "key", "in", "keys", ":", "key_values", "=", "[", "]", "for", "record", "in", "record...
Given a list of records within a duplicate cluster, constructs a canonical representation of the cluster by finding canonical values for each field
[ "Given", "a", "list", "of", "records", "within", "a", "duplicate", "cluster", "constructs", "a", "canonical", "representation", "of", "the", "cluster", "by", "finding", "canonical", "values", "for", "each", "field" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/canonical.py#L48-L71
220,098
dedupeio/dedupe
dedupe/predicates.py
nearIntegersPredicate
def nearIntegersPredicate(field): """return any integers N, N+1, and N-1""" ints = integers(field) near_ints = set() for char in ints: num = int(char) near_ints.add(str(num - 1)) near_ints.add(str(num)) near_ints.add(str(num + 1)) return near_ints
python
def nearIntegersPredicate(field): """return any integers N, N+1, and N-1""" ints = integers(field) near_ints = set() for char in ints: num = int(char) near_ints.add(str(num - 1)) near_ints.add(str(num)) near_ints.add(str(num + 1)) return near_ints
[ "def", "nearIntegersPredicate", "(", "field", ")", ":", "ints", "=", "integers", "(", "field", ")", "near_ints", "=", "set", "(", ")", "for", "char", "in", "ints", ":", "num", "=", "int", "(", "char", ")", "near_ints", ".", "add", "(", "str", "(", ...
return any integers N, N+1, and N-1
[ "return", "any", "integers", "N", "N", "+", "1", "and", "N", "-", "1" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/predicates.py#L320-L330
220,099
dedupeio/dedupe
dedupe/core.py
randomPairsMatch
def randomPairsMatch(n_records_A, n_records_B, sample_size): """ Return random combinations of indices for record list A and B """ n = int(n_records_A * n_records_B) if sample_size >= n: random_pairs = numpy.arange(n) else: random_pairs = numpy.array(random.sample(range(n), samp...
python
def randomPairsMatch(n_records_A, n_records_B, sample_size): """ Return random combinations of indices for record list A and B """ n = int(n_records_A * n_records_B) if sample_size >= n: random_pairs = numpy.arange(n) else: random_pairs = numpy.array(random.sample(range(n), samp...
[ "def", "randomPairsMatch", "(", "n_records_A", ",", "n_records_B", ",", "sample_size", ")", ":", "n", "=", "int", "(", "n_records_A", "*", "n_records_B", ")", "if", "sample_size", ">=", "n", ":", "random_pairs", "=", "numpy", ".", "arange", "(", "n", ")", ...
Return random combinations of indices for record list A and B
[ "Return", "random", "combinations", "of", "indices", "for", "record", "list", "A", "and", "B" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/core.py#L65-L79