repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.set_file
def set_file(self, filename): """ Analyse the file with the captured content """ # Use the file name as prefix if none is given if self.output_prefix is None: _, self.output_prefix = os.path.split(filename) # Check if the file is present, since rdpcap will not do that ...
python
def set_file(self, filename): """ Analyse the file with the captured content """ # Use the file name as prefix if none is given if self.output_prefix is None: _, self.output_prefix = os.path.split(filename) # Check if the file is present, since rdpcap will not do that ...
[ "def", "set_file", "(", "self", ",", "filename", ")", ":", "# Use the file name as prefix if none is given", "if", "self", ".", "output_prefix", "is", "None", ":", "_", ",", "self", ".", "output_prefix", "=", "os", ".", "path", ".", "split", "(", "filename", ...
Analyse the file with the captured content
[ "Analyse", "the", "file", "with", "the", "captured", "content" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L86-L125
train
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS._parse_load
def _parse_load(self, load): """ Parse the load from a single packet """ # If the load is ?? if load in ['??']: self._debug('IGNORING') # If there is a start in load elif any([start in load for start in STARTS]): self._debug('START') self.messa...
python
def _parse_load(self, load): """ Parse the load from a single packet """ # If the load is ?? if load in ['??']: self._debug('IGNORING') # If there is a start in load elif any([start in load for start in STARTS]): self._debug('START') self.messa...
[ "def", "_parse_load", "(", "self", ",", "load", ")", ":", "# If the load is ??", "if", "load", "in", "[", "'??'", "]", ":", "self", ".", "_debug", "(", "'IGNORING'", ")", "# If there is a start in load", "elif", "any", "(", "[", "start", "in", "load", "for...
Parse the load from a single packet
[ "Parse", "the", "load", "from", "a", "single", "packet" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L127-L159
train
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS._debug
def _debug(self, message, load=False, no_prefix=False): """ Output debug information """ if self.args.debug_analysis: if load: message = '\r\n'.join( ['# ' + line for line in message.strip().split('\r\n')] ) print '{0}\n{1}\...
python
def _debug(self, message, load=False, no_prefix=False): """ Output debug information """ if self.args.debug_analysis: if load: message = '\r\n'.join( ['# ' + line for line in message.strip().split('\r\n')] ) print '{0}\n{1}\...
[ "def", "_debug", "(", "self", ",", "message", ",", "load", "=", "False", ",", "no_prefix", "=", "False", ")", ":", "if", "self", ".", "args", ".", "debug_analysis", ":", "if", "load", ":", "message", "=", "'\\r\\n'", ".", "join", "(", "[", "'# '", ...
Output debug information
[ "Output", "debug", "information" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L161-L175
train
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.to_file_mode
def to_file_mode(self): """ Write all the messages to files """ for message_no in range(len(self.messages)): self.__to_file(message_no)
python
def to_file_mode(self): """ Write all the messages to files """ for message_no in range(len(self.messages)): self.__to_file(message_no)
[ "def", "to_file_mode", "(", "self", ")", ":", "for", "message_no", "in", "range", "(", "len", "(", "self", ".", "messages", ")", ")", ":", "self", ".", "__to_file", "(", "message_no", ")" ]
Write all the messages to files
[ "Write", "all", "the", "messages", "to", "files" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L177-L180
train
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.__to_file
def __to_file(self, message_no): """ Write a single message to file """ filename = self.__create_file_name(message_no) try: with codecs.open(filename, mode='w', encoding=self.messages[message_no].encoding)\ as file__: f...
python
def __to_file(self, message_no): """ Write a single message to file """ filename = self.__create_file_name(message_no) try: with codecs.open(filename, mode='w', encoding=self.messages[message_no].encoding)\ as file__: f...
[ "def", "__to_file", "(", "self", ",", "message_no", ")", ":", "filename", "=", "self", ".", "__create_file_name", "(", "message_no", ")", "try", ":", "with", "codecs", ".", "open", "(", "filename", ",", "mode", "=", "'w'", ",", "encoding", "=", "self", ...
Write a single message to file
[ "Write", "a", "single", "message", "to", "file" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L182-L196
train
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.__create_file_name
def __create_file_name(self, message_no): """ Create the filename to save to """ cwd = os.getcwd() filename = '{0}_{1}.xml'.format(self.output_prefix, message_no) return os.path.join(cwd, filename)
python
def __create_file_name(self, message_no): """ Create the filename to save to """ cwd = os.getcwd() filename = '{0}_{1}.xml'.format(self.output_prefix, message_no) return os.path.join(cwd, filename)
[ "def", "__create_file_name", "(", "self", ",", "message_no", ")", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "filename", "=", "'{0}_{1}.xml'", ".", "format", "(", "self", ".", "output_prefix", ",", "message_no", ")", "return", "os", ".", "path", "."...
Create the filename to save to
[ "Create", "the", "filename", "to", "save", "to" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L198-L202
train
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.to_browser_mode
def to_browser_mode(self): """ Write all the messages to files and open them in the browser """ for message_no in range(len(self.messages)): self.__to_browser(message_no)
python
def to_browser_mode(self): """ Write all the messages to files and open them in the browser """ for message_no in range(len(self.messages)): self.__to_browser(message_no)
[ "def", "to_browser_mode", "(", "self", ")", ":", "for", "message_no", "in", "range", "(", "len", "(", "self", ".", "messages", ")", ")", ":", "self", ".", "__to_browser", "(", "message_no", ")" ]
Write all the messages to files and open them in the browser
[ "Write", "all", "the", "messages", "to", "files", "and", "open", "them", "in", "the", "browser" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L204-L207
train
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.__to_browser
def __to_browser(self, message_no): """ Write a single message to file and open the file in a browser """ filename = self.__to_file(message_no) try: command = self.config.get('General', 'browser_command') except (ConfigParser.NoOptionError, AttributeError): ...
python
def __to_browser(self, message_no): """ Write a single message to file and open the file in a browser """ filename = self.__to_file(message_no) try: command = self.config.get('General', 'browser_command') except (ConfigParser.NoOptionError, AttributeError): ...
[ "def", "__to_browser", "(", "self", ",", "message_no", ")", ":", "filename", "=", "self", ".", "__to_file", "(", "message_no", ")", "try", ":", "command", "=", "self", ".", "config", ".", "get", "(", "'General'", ",", "'browser_command'", ")", "except", ...
Write a single message to file and open the file in a browser
[ "Write", "a", "single", "message", "to", "file", "and", "open", "the", "file", "in", "a", "browser" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L209-L229
train
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS.__update_window
def __update_window(self, width, height, message_no, page_no): """ Update the window with the menu and the new text """ file_exists_label = '-F-ILE' if not os.path.exists(self.__create_file_name(message_no)): file_exists_label = '(f)ile' # Clear the screen if PLATFOR...
python
def __update_window(self, width, height, message_no, page_no): """ Update the window with the menu and the new text """ file_exists_label = '-F-ILE' if not os.path.exists(self.__create_file_name(message_no)): file_exists_label = '(f)ile' # Clear the screen if PLATFOR...
[ "def", "__update_window", "(", "self", ",", "width", ",", "height", ",", "message_no", ",", "page_no", ")", ":", "file_exists_label", "=", "'-F-ILE'", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "__create_file_name", "(", "message_no", ...
Update the window with the menu and the new text
[ "Update", "the", "window", "with", "the", "menu", "and", "the", "new", "text" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L268-L310
train
SoCo/SoCo
dev_tools/analyse_ws.py
AnalyzeWS._form_pages
def _form_pages(self, message_no, content, out, height, width): """ Form the pages """ self.pages[message_no] = [] page_height = height - 4 # 2-3 for menu, 1 for cursor outline = u'' no_lines_page = 0 for original, formatted in zip(content.split('\n'), out.split('\n')): ...
python
def _form_pages(self, message_no, content, out, height, width): """ Form the pages """ self.pages[message_no] = [] page_height = height - 4 # 2-3 for menu, 1 for cursor outline = u'' no_lines_page = 0 for original, formatted in zip(content.split('\n'), out.split('\n')): ...
[ "def", "_form_pages", "(", "self", ",", "message_no", ",", "content", ",", "out", ",", "height", ",", "width", ")", ":", "self", ".", "pages", "[", "message_no", "]", "=", "[", "]", "page_height", "=", "height", "-", "4", "# 2-3 for menu, 1 for cursor", ...
Form the pages
[ "Form", "the", "pages" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L312-L353
train
SoCo/SoCo
dev_tools/analyse_ws.py
WSPart.finalize_content
def finalize_content(self): """ Finalize the additons """ self.write_closed = True body = self.raw_body.decode(self.encoding) self._init_xml(body) self._form_output()
python
def finalize_content(self): """ Finalize the additons """ self.write_closed = True body = self.raw_body.decode(self.encoding) self._init_xml(body) self._form_output()
[ "def", "finalize_content", "(", "self", ")", ":", "self", ".", "write_closed", "=", "True", "body", "=", "self", ".", "raw_body", ".", "decode", "(", "self", ".", "encoding", ")", "self", ".", "_init_xml", "(", "body", ")", "self", ".", "_form_output", ...
Finalize the additons
[ "Finalize", "the", "additons" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L382-L387
train
SoCo/SoCo
dev_tools/analyse_ws.py
WSPart._init_xml
def _init_xml(self, body): """ Parse the present body as xml """ tree = etree.fromstring(body.encode(self.encoding), PARSER) # Extract and replace inner DIDL xml in tags for text in tree.xpath('.//text()[contains(., "DIDL")]'): item = text.getparent() didl_tree = ...
python
def _init_xml(self, body): """ Parse the present body as xml """ tree = etree.fromstring(body.encode(self.encoding), PARSER) # Extract and replace inner DIDL xml in tags for text in tree.xpath('.//text()[contains(., "DIDL")]'): item = text.getparent() didl_tree = ...
[ "def", "_init_xml", "(", "self", ",", "body", ")", ":", "tree", "=", "etree", ".", "fromstring", "(", "body", ".", "encode", "(", "self", ".", "encoding", ")", ",", "PARSER", ")", "# Extract and replace inner DIDL xml in tags", "for", "text", "in", "tree", ...
Parse the present body as xml
[ "Parse", "the", "present", "body", "as", "xml" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L389-L413
train
SoCo/SoCo
dev_tools/analyse_ws.py
WSPart._form_output
def _form_output(self): """ Form the output """ self.output = u'' if self.external_inner_xml: self.output += u'<Dummy_tag_to_create_valid_xml_on_external_inner'\ '_xml>\n' self.output += u'<!-- BODY -->\n{0}'.format(self.body_formatted) if ...
python
def _form_output(self): """ Form the output """ self.output = u'' if self.external_inner_xml: self.output += u'<Dummy_tag_to_create_valid_xml_on_external_inner'\ '_xml>\n' self.output += u'<!-- BODY -->\n{0}'.format(self.body_formatted) if ...
[ "def", "_form_output", "(", "self", ")", ":", "self", ".", "output", "=", "u''", "if", "self", ".", "external_inner_xml", ":", "self", ".", "output", "+=", "u'<Dummy_tag_to_create_valid_xml_on_external_inner'", "'_xml>\\n'", "self", ".", "output", "+=", "u'<!-- BO...
Form the output
[ "Form", "the", "output" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/analyse_ws.py#L418-L431
train
SoCo/SoCo
soco/data_structures_entry.py
attempt_datastructure_upgrade
def attempt_datastructure_upgrade(didl_item): """Attempt to upgrade a didl_item to a music services data structure if it originates from a music services """ try: resource = didl_item.resources[0] except IndexError: _LOG.debug('Upgrade not possible, no resources') return did...
python
def attempt_datastructure_upgrade(didl_item): """Attempt to upgrade a didl_item to a music services data structure if it originates from a music services """ try: resource = didl_item.resources[0] except IndexError: _LOG.debug('Upgrade not possible, no resources') return did...
[ "def", "attempt_datastructure_upgrade", "(", "didl_item", ")", ":", "try", ":", "resource", "=", "didl_item", ".", "resources", "[", "0", "]", "except", "IndexError", ":", "_LOG", ".", "debug", "(", "'Upgrade not possible, no resources'", ")", "return", "didl_item...
Attempt to upgrade a didl_item to a music services data structure if it originates from a music services
[ "Attempt", "to", "upgrade", "a", "didl_item", "to", "a", "music", "services", "data", "structure", "if", "it", "originates", "from", "a", "music", "services" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/data_structures_entry.py#L76-L135
train
SoCo/SoCo
soco/plugins/__init__.py
SoCoPlugin.from_name
def from_name(cls, fullname, soco, *args, **kwargs): """Instantiate a plugin by its full name.""" _LOG.info('Loading plugin %s', fullname) parts = fullname.split('.') modname = '.'.join(parts[:-1]) clsname = parts[-1] mod = importlib.import_module(modname) clas...
python
def from_name(cls, fullname, soco, *args, **kwargs): """Instantiate a plugin by its full name.""" _LOG.info('Loading plugin %s', fullname) parts = fullname.split('.') modname = '.'.join(parts[:-1]) clsname = parts[-1] mod = importlib.import_module(modname) clas...
[ "def", "from_name", "(", "cls", ",", "fullname", ",", "soco", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_LOG", ".", "info", "(", "'Loading plugin %s'", ",", "fullname", ")", "parts", "=", "fullname", ".", "split", "(", "'.'", ")", "modnam...
Instantiate a plugin by its full name.
[ "Instantiate", "a", "plugin", "by", "its", "full", "name", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/plugins/__init__.py#L34-L48
train
SoCo/SoCo
soco/ms_data_structures.py
get_ms_item
def get_ms_item(xml, service, parent_id): """Return the music service item that corresponds to xml. The class is identified by getting the type from the 'itemType' tag """ cls = MS_TYPE_TO_CLASS.get(xml.findtext(ns_tag('ms', 'itemType'))) out = cls.from_xml(xml, service, parent_id) return out
python
def get_ms_item(xml, service, parent_id): """Return the music service item that corresponds to xml. The class is identified by getting the type from the 'itemType' tag """ cls = MS_TYPE_TO_CLASS.get(xml.findtext(ns_tag('ms', 'itemType'))) out = cls.from_xml(xml, service, parent_id) return out
[ "def", "get_ms_item", "(", "xml", ",", "service", ",", "parent_id", ")", ":", "cls", "=", "MS_TYPE_TO_CLASS", ".", "get", "(", "xml", ".", "findtext", "(", "ns_tag", "(", "'ms'", ",", "'itemType'", ")", ")", ")", "out", "=", "cls", ".", "from_xml", "...
Return the music service item that corresponds to xml. The class is identified by getting the type from the 'itemType' tag
[ "Return", "the", "music", "service", "item", "that", "corresponds", "to", "xml", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/ms_data_structures.py#L21-L28
train
SoCo/SoCo
soco/ms_data_structures.py
tags_with_text
def tags_with_text(xml, tags=None): """Return a list of tags that contain text retrieved recursively from an XML tree.""" if tags is None: tags = [] for element in xml: if element.text is not None: tags.append(element) elif len(element) > 0: # pylint: disable=len-as-...
python
def tags_with_text(xml, tags=None): """Return a list of tags that contain text retrieved recursively from an XML tree.""" if tags is None: tags = [] for element in xml: if element.text is not None: tags.append(element) elif len(element) > 0: # pylint: disable=len-as-...
[ "def", "tags_with_text", "(", "xml", ",", "tags", "=", "None", ")", ":", "if", "tags", "is", "None", ":", "tags", "=", "[", "]", "for", "element", "in", "xml", ":", "if", "element", ".", "text", "is", "not", "None", ":", "tags", ".", "append", "(...
Return a list of tags that contain text retrieved recursively from an XML tree.
[ "Return", "a", "list", "of", "tags", "that", "contain", "text", "retrieved", "recursively", "from", "an", "XML", "tree", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/ms_data_structures.py#L31-L44
train
SoCo/SoCo
soco/ms_data_structures.py
MusicServiceItem.from_xml
def from_xml(cls, xml, service, parent_id): """Return a Music Service item generated from xml. :param xml: Object XML. All items containing text are added to the content of the item. The class variable ``valid_fields`` of each of the classes list the valid fields (after translat...
python
def from_xml(cls, xml, service, parent_id): """Return a Music Service item generated from xml. :param xml: Object XML. All items containing text are added to the content of the item. The class variable ``valid_fields`` of each of the classes list the valid fields (after translat...
[ "def", "from_xml", "(", "cls", ",", "xml", ",", "service", ",", "parent_id", ")", ":", "# Add a few extra pieces of information", "content", "=", "{", "'description'", ":", "service", ".", "description", ",", "'service_id'", ":", "service", ".", "service_id", ",...
Return a Music Service item generated from xml. :param xml: Object XML. All items containing text are added to the content of the item. The class variable ``valid_fields`` of each of the classes list the valid fields (after translating the camel case to underscore notation)....
[ "Return", "a", "Music", "Service", "item", "generated", "from", "xml", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/ms_data_structures.py#L61-L148
train
SoCo/SoCo
soco/ms_data_structures.py
MusicServiceItem.from_dict
def from_dict(cls, dict_in): """Initialize the class from a dict. :param dict_in: The dictionary that contains the item content. Required fields are listed class variable by that name :type dict_in: dict """ kwargs = dict_in.copy() args = [kwargs.pop(key) for...
python
def from_dict(cls, dict_in): """Initialize the class from a dict. :param dict_in: The dictionary that contains the item content. Required fields are listed class variable by that name :type dict_in: dict """ kwargs = dict_in.copy() args = [kwargs.pop(key) for...
[ "def", "from_dict", "(", "cls", ",", "dict_in", ")", ":", "kwargs", "=", "dict_in", ".", "copy", "(", ")", "args", "=", "[", "kwargs", ".", "pop", "(", "key", ")", "for", "key", "in", "cls", ".", "required_fields", "]", "return", "cls", "(", "*", ...
Initialize the class from a dict. :param dict_in: The dictionary that contains the item content. Required fields are listed class variable by that name :type dict_in: dict
[ "Initialize", "the", "class", "from", "a", "dict", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/ms_data_structures.py#L151-L160
train
SoCo/SoCo
soco/ms_data_structures.py
MusicServiceItem.didl_metadata
def didl_metadata(self): """Return the DIDL metadata for a Music Service Track. The metadata is on the form: .. code :: xml <DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:r="urn:schemas-rin...
python
def didl_metadata(self): """Return the DIDL metadata for a Music Service Track. The metadata is on the form: .. code :: xml <DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:r="urn:schemas-rin...
[ "def", "didl_metadata", "(", "self", ")", ":", "# Check if this item is meant to be played", "if", "not", "self", ".", "can_play", ":", "message", "=", "'This item is not meant to be played and therefore '", "'also not to create its own didl_metadata'", "raise", "DIDLMetadataErro...
Return the DIDL metadata for a Music Service Track. The metadata is on the form: .. code :: xml <DIDL-Lite xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/" ...
[ "Return", "the", "DIDL", "metadata", "for", "a", "Music", "Service", "Track", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/ms_data_structures.py#L213-L285
train
SoCo/SoCo
soco/alarms.py
get_alarms
def get_alarms(zone=None): """Get a set of all alarms known to the Sonos system. Args: zone (`SoCo`, optional): a SoCo instance to query. If None, a random instance is used. Defaults to `None`. Returns: set: A set of `Alarm` instances Note: Any existing `Alarm` ins...
python
def get_alarms(zone=None): """Get a set of all alarms known to the Sonos system. Args: zone (`SoCo`, optional): a SoCo instance to query. If None, a random instance is used. Defaults to `None`. Returns: set: A set of `Alarm` instances Note: Any existing `Alarm` ins...
[ "def", "get_alarms", "(", "zone", "=", "None", ")", ":", "# Get a soco instance to query. It doesn't matter which.", "if", "zone", "is", "None", ":", "zone", "=", "discovery", ".", "any_soco", "(", ")", "response", "=", "zone", ".", "alarmClock", ".", "ListAlarm...
Get a set of all alarms known to the Sonos system. Args: zone (`SoCo`, optional): a SoCo instance to query. If None, a random instance is used. Defaults to `None`. Returns: set: A set of `Alarm` instances Note: Any existing `Alarm` instance will have its attributes upd...
[ "Get", "a", "set", "of", "all", "alarms", "known", "to", "the", "Sonos", "system", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L253-L325
train
SoCo/SoCo
soco/alarms.py
Alarm.play_mode
def play_mode(self, play_mode): """See `playmode`.""" play_mode = play_mode.upper() if play_mode not in PLAY_MODES: raise KeyError("'%s' is not a valid play mode" % play_mode) self._play_mode = play_mode
python
def play_mode(self, play_mode): """See `playmode`.""" play_mode = play_mode.upper() if play_mode not in PLAY_MODES: raise KeyError("'%s' is not a valid play mode" % play_mode) self._play_mode = play_mode
[ "def", "play_mode", "(", "self", ",", "play_mode", ")", ":", "play_mode", "=", "play_mode", ".", "upper", "(", ")", "if", "play_mode", "not", "in", "PLAY_MODES", ":", "raise", "KeyError", "(", "\"'%s' is not a valid play mode\"", "%", "play_mode", ")", "self",...
See `playmode`.
[ "See", "playmode", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L166-L171
train
SoCo/SoCo
soco/alarms.py
Alarm.volume
def volume(self, volume): """See `volume`.""" # max 100 volume = int(volume) self._volume = max(0, min(volume, 100))
python
def volume(self, volume): """See `volume`.""" # max 100 volume = int(volume) self._volume = max(0, min(volume, 100))
[ "def", "volume", "(", "self", ",", "volume", ")", ":", "# max 100", "volume", "=", "int", "(", "volume", ")", "self", ".", "_volume", "=", "max", "(", "0", ",", "min", "(", "volume", ",", "100", ")", ")" ]
See `volume`.
[ "See", "volume", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L179-L183
train
SoCo/SoCo
soco/alarms.py
Alarm.recurrence
def recurrence(self, recurrence): """See `recurrence`.""" if not is_valid_recurrence(recurrence): raise KeyError("'%s' is not a valid recurrence value" % recurrence) self._recurrence = recurrence
python
def recurrence(self, recurrence): """See `recurrence`.""" if not is_valid_recurrence(recurrence): raise KeyError("'%s' is not a valid recurrence value" % recurrence) self._recurrence = recurrence
[ "def", "recurrence", "(", "self", ",", "recurrence", ")", ":", "if", "not", "is_valid_recurrence", "(", "recurrence", ")", ":", "raise", "KeyError", "(", "\"'%s' is not a valid recurrence value\"", "%", "recurrence", ")", "self", ".", "_recurrence", "=", "recurren...
See `recurrence`.
[ "See", "recurrence", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L197-L202
train
SoCo/SoCo
soco/alarms.py
Alarm.save
def save(self): """Save the alarm to the Sonos system. Raises: ~soco.exceptions.SoCoUPnPException: if the alarm cannot be created because there is already an alarm for this room at the specified time. """ # pylint: disable=bad-continuation ...
python
def save(self): """Save the alarm to the Sonos system. Raises: ~soco.exceptions.SoCoUPnPException: if the alarm cannot be created because there is already an alarm for this room at the specified time. """ # pylint: disable=bad-continuation ...
[ "def", "save", "(", "self", ")", ":", "# pylint: disable=bad-continuation", "args", "=", "[", "(", "'StartLocalTime'", ",", "self", ".", "start_time", ".", "strftime", "(", "TIME_FORMAT", ")", ")", ",", "(", "'Duration'", ",", "''", "if", "self", ".", "dur...
Save the alarm to the Sonos system. Raises: ~soco.exceptions.SoCoUPnPException: if the alarm cannot be created because there is already an alarm for this room at the specified time.
[ "Save", "the", "alarm", "to", "the", "Sonos", "system", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L204-L234
train
SoCo/SoCo
soco/alarms.py
Alarm.remove
def remove(self): """Remove the alarm from the Sonos system. There is no need to call `save`. The Python instance is not deleted, and can be saved back to Sonos again if desired. """ self.zone.alarmClock.DestroyAlarm([ ('ID', self._alarm_id) ]) alarm_...
python
def remove(self): """Remove the alarm from the Sonos system. There is no need to call `save`. The Python instance is not deleted, and can be saved back to Sonos again if desired. """ self.zone.alarmClock.DestroyAlarm([ ('ID', self._alarm_id) ]) alarm_...
[ "def", "remove", "(", "self", ")", ":", "self", ".", "zone", ".", "alarmClock", ".", "DestroyAlarm", "(", "[", "(", "'ID'", ",", "self", ".", "_alarm_id", ")", "]", ")", "alarm_id", "=", "self", ".", "_alarm_id", "try", ":", "del", "Alarm", ".", "_...
Remove the alarm from the Sonos system. There is no need to call `save`. The Python instance is not deleted, and can be saved back to Sonos again if desired.
[ "Remove", "the", "alarm", "from", "the", "Sonos", "system", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/alarms.py#L236-L250
train
SoCo/SoCo
dev_tools/sonosdump.py
main
def main(): """ Run the main script """ parser = argparse.ArgumentParser( prog='', description='Dump data about Sonos services' ) parser.add_argument( '-d', '--device', default=None, help="The ip address of the device to query. " "If none is supplied,...
python
def main(): """ Run the main script """ parser = argparse.ArgumentParser( prog='', description='Dump data about Sonos services' ) parser.add_argument( '-d', '--device', default=None, help="The ip address of the device to query. " "If none is supplied,...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "''", ",", "description", "=", "'Dump data about Sonos services'", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--device'", ",", "default", "=", "Non...
Run the main script
[ "Run", "the", "main", "script" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/sonosdump.py#L15-L49
train
SoCo/SoCo
dev_tools/sonosdump.py
print_details
def print_details(srv): """ Print the details of a service """ name = srv.service_type box = "=" * 79 print("{0}\n|{1:^77}|\n{0}\n".format(box, name)) for action in srv.iter_actions(): print(action.name) print("~" * len(action.name)) print("\n Input") for arg in ...
python
def print_details(srv): """ Print the details of a service """ name = srv.service_type box = "=" * 79 print("{0}\n|{1:^77}|\n{0}\n".format(box, name)) for action in srv.iter_actions(): print(action.name) print("~" * len(action.name)) print("\n Input") for arg in ...
[ "def", "print_details", "(", "srv", ")", ":", "name", "=", "srv", ".", "service_type", "box", "=", "\"=\"", "*", "79", "print", "(", "\"{0}\\n|{1:^77}|\\n{0}\\n\"", ".", "format", "(", "box", ",", "name", ")", ")", "for", "action", "in", "srv", ".", "i...
Print the details of a service
[ "Print", "the", "details", "of", "a", "service" ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/dev_tools/sonosdump.py#L52-L68
train
SoCo/SoCo
soco/snapshot.py
Snapshot.snapshot
def snapshot(self): """Record and store the current state of a device. Returns: bool: `True` if the device is a coordinator, `False` otherwise. Useful for determining whether playing an alert on a device will ungroup it. """ # get if device co...
python
def snapshot(self): """Record and store the current state of a device. Returns: bool: `True` if the device is a coordinator, `False` otherwise. Useful for determining whether playing an alert on a device will ungroup it. """ # get if device co...
[ "def", "snapshot", "(", "self", ")", ":", "# get if device coordinator (or slave) True (or False)", "self", ".", "is_coordinator", "=", "self", ".", "device", ".", "is_coordinator", "# Get information about the currently playing media", "media_info", "=", "self", ".", "devi...
Record and store the current state of a device. Returns: bool: `True` if the device is a coordinator, `False` otherwise. Useful for determining whether playing an alert on a device will ungroup it.
[ "Record", "and", "store", "the", "current", "state", "of", "a", "device", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/snapshot.py#L87-L158
train
SoCo/SoCo
soco/snapshot.py
Snapshot._save_queue
def _save_queue(self): """Save the current state of the queue.""" if self.queue is not None: # Maximum batch is 486, anything larger will still only # return 486 batch_size = 400 total = 0 num_return = batch_size # Need to get all ...
python
def _save_queue(self): """Save the current state of the queue.""" if self.queue is not None: # Maximum batch is 486, anything larger will still only # return 486 batch_size = 400 total = 0 num_return = batch_size # Need to get all ...
[ "def", "_save_queue", "(", "self", ")", ":", "if", "self", ".", "queue", "is", "not", "None", ":", "# Maximum batch is 486, anything larger will still only", "# return 486", "batch_size", "=", "400", "total", "=", "0", "num_return", "=", "batch_size", "# Need to get...
Save the current state of the queue.
[ "Save", "the", "current", "state", "of", "the", "queue", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/snapshot.py#L255-L274
train
SoCo/SoCo
soco/snapshot.py
Snapshot._restore_queue
def _restore_queue(self): """Restore the previous state of the queue. Note: The restore currently adds the items back into the queue using the URI, for items the Sonos system already knows about this is OK, but for other items, they may be missing some of ...
python
def _restore_queue(self): """Restore the previous state of the queue. Note: The restore currently adds the items back into the queue using the URI, for items the Sonos system already knows about this is OK, but for other items, they may be missing some of ...
[ "def", "_restore_queue", "(", "self", ")", ":", "if", "self", ".", "queue", "is", "not", "None", ":", "# Clear the queue so that it can be reset", "self", ".", "device", ".", "clear_queue", "(", ")", "# Now loop around all the queue entries adding them", "for", "queue...
Restore the previous state of the queue. Note: The restore currently adds the items back into the queue using the URI, for items the Sonos system already knows about this is OK, but for other items, they may be missing some of their metadata as it will not be aut...
[ "Restore", "the", "previous", "state", "of", "the", "queue", "." ]
671937e07d7973b78c0cbee153d4f3ad68ec48c6
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/snapshot.py#L276-L291
train
ContextLab/hypertools
hypertools/_shared/params.py
default_params
def default_params(model, update_dict=None): """ Loads and updates default model parameters Parameters ---------- model : str The name of a model update_dict : dict A dict to update default parameters Returns ---------- params : dict A dictionary of param...
python
def default_params(model, update_dict=None): """ Loads and updates default model parameters Parameters ---------- model : str The name of a model update_dict : dict A dict to update default parameters Returns ---------- params : dict A dictionary of param...
[ "def", "default_params", "(", "model", ",", "update_dict", "=", "None", ")", ":", "if", "model", "in", "parameters", ":", "params", "=", "parameters", "[", "model", "]", ".", "copy", "(", ")", "else", ":", "params", "=", "None", "if", "update_dict", ":...
Loads and updates default model parameters Parameters ---------- model : str The name of a model update_dict : dict A dict to update default parameters Returns ---------- params : dict A dictionary of parameters
[ "Loads", "and", "updates", "default", "model", "parameters" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_shared/params.py#L18-L48
train
ContextLab/hypertools
hypertools/tools/describe.py
describe
def describe(x, reduce='IncrementalPCA', max_dims=None, show=True, format_data=True): """ Create plot describing covariance with as a function of number of dimensions This function correlates the raw data with reduced data to get a sense for how well the data can be summarized with n dimen...
python
def describe(x, reduce='IncrementalPCA', max_dims=None, show=True, format_data=True): """ Create plot describing covariance with as a function of number of dimensions This function correlates the raw data with reduced data to get a sense for how well the data can be summarized with n dimen...
[ "def", "describe", "(", "x", ",", "reduce", "=", "'IncrementalPCA'", ",", "max_dims", "=", "None", ",", "show", "=", "True", ",", "format_data", "=", "True", ")", ":", "warnings", ".", "warn", "(", "'When input data is large, this computation can take a long time....
Create plot describing covariance with as a function of number of dimensions This function correlates the raw data with reduced data to get a sense for how well the data can be summarized with n dimensions. Useful for evaluating quality of dimensionality reduced plots. Parameters ---------- ...
[ "Create", "plot", "describing", "covariance", "with", "as", "a", "function", "of", "number", "of", "dimensions" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/describe.py#L16-L106
train
ContextLab/hypertools
hypertools/tools/missing_inds.py
missing_inds
def missing_inds(x, format_data=True): """ Returns indices of missing data This function is useful to identify rows of your array that contain missing data or nans. The returned indices can be used to remove the rows with missing data, or label the missing data points that are interpolated usi...
python
def missing_inds(x, format_data=True): """ Returns indices of missing data This function is useful to identify rows of your array that contain missing data or nans. The returned indices can be used to remove the rows with missing data, or label the missing data points that are interpolated usi...
[ "def", "missing_inds", "(", "x", ",", "format_data", "=", "True", ")", ":", "if", "format_data", ":", "x", "=", "formatter", "(", "x", ",", "ppca", "=", "False", ")", "inds", "=", "[", "]", "for", "arr", "in", "x", ":", "if", "np", ".", "argwhere...
Returns indices of missing data This function is useful to identify rows of your array that contain missing data or nans. The returned indices can be used to remove the rows with missing data, or label the missing data points that are interpolated using PPCA. Parameters ---------- x : arr...
[ "Returns", "indices", "of", "missing", "data" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/missing_inds.py#L7-L43
train
ContextLab/hypertools
hypertools/tools/normalize.py
normalize
def normalize(x, normalize='across', internal=False, format_data=True): """ Z-transform the columns or rows of an array, or list of arrays This function normalizes the rows or columns of the input array(s). This can be useful because data reduction and machine learning techniques are sensitive to ...
python
def normalize(x, normalize='across', internal=False, format_data=True): """ Z-transform the columns or rows of an array, or list of arrays This function normalizes the rows or columns of the input array(s). This can be useful because data reduction and machine learning techniques are sensitive to ...
[ "def", "normalize", "(", "x", ",", "normalize", "=", "'across'", ",", "internal", "=", "False", ",", "format_data", "=", "True", ")", ":", "assert", "normalize", "in", "[", "'across'", ",", "'within'", ",", "'row'", ",", "False", ",", "None", "]", ",",...
Z-transform the columns or rows of an array, or list of arrays This function normalizes the rows or columns of the input array(s). This can be useful because data reduction and machine learning techniques are sensitive to scaling differences between features. By default, the function is set to normali...
[ "Z", "-", "transform", "the", "columns", "or", "rows", "of", "an", "array", "or", "list", "of", "arrays" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/normalize.py#L12-L72
train
ContextLab/hypertools
hypertools/_externals/srm.py
SRM._init_structures
def _init_structures(self, data, subjects): """Initializes data structures for SRM and preprocess the data. Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. subje...
python
def _init_structures(self, data, subjects): """Initializes data structures for SRM and preprocess the data. Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. subje...
[ "def", "_init_structures", "(", "self", ",", "data", ",", "subjects", ")", ":", "x", "=", "[", "]", "mu", "=", "[", "]", "rho2", "=", "np", ".", "zeros", "(", "subjects", ")", "trace_xtx", "=", "np", ".", "zeros", "(", "subjects", ")", "for", "su...
Initializes data structures for SRM and preprocess the data. Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. subjects : int The total number of subjects in `...
[ "Initializes", "data", "structures", "for", "SRM", "and", "preprocess", "the", "data", "." ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_externals/srm.py#L232-L270
train
ContextLab/hypertools
hypertools/_externals/srm.py
SRM._likelihood
def _likelihood(self, chol_sigma_s_rhos, log_det_psi, chol_sigma_s, trace_xt_invsigma2_x, inv_sigma_s_rhos, wt_invpsi_x, samples): """Calculate the log-likelihood function Parameters ---------- chol_sigma_s_rhos : array, shape=[features, feature...
python
def _likelihood(self, chol_sigma_s_rhos, log_det_psi, chol_sigma_s, trace_xt_invsigma2_x, inv_sigma_s_rhos, wt_invpsi_x, samples): """Calculate the log-likelihood function Parameters ---------- chol_sigma_s_rhos : array, shape=[features, feature...
[ "def", "_likelihood", "(", "self", ",", "chol_sigma_s_rhos", ",", "log_det_psi", ",", "chol_sigma_s", ",", "trace_xt_invsigma2_x", ",", "inv_sigma_s_rhos", ",", "wt_invpsi_x", ",", "samples", ")", ":", "log_det", "=", "(", "np", ".", "log", "(", "np", ".", "...
Calculate the log-likelihood function Parameters ---------- chol_sigma_s_rhos : array, shape=[features, features] Cholesky factorization of the matrix (Sigma_S + sum_i(1/rho_i^2) * I) log_det_psi : float Determinant of diagonal matrix Psi (containi...
[ "Calculate", "the", "log", "-", "likelihood", "function" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_externals/srm.py#L272-L317
train
ContextLab/hypertools
hypertools/_externals/srm.py
DetSRM.fit
def fit(self, X, y=None): """Compute the Deterministic Shared Response Model Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. y : not used """ logger....
python
def fit(self, X, y=None): """Compute the Deterministic Shared Response Model Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. y : not used """ logger....
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "logger", ".", "info", "(", "'Starting Deterministic SRM'", ")", "# Check the number of subjects", "if", "len", "(", "X", ")", "<=", "1", ":", "raise", "ValueError", "(", "\"There are no...
Compute the Deterministic Shared Response Model Parameters ---------- X : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. y : not used
[ "Compute", "the", "Deterministic", "Shared", "Response", "Model" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_externals/srm.py#L488-L523
train
ContextLab/hypertools
hypertools/_externals/srm.py
DetSRM._objective_function
def _objective_function(self, data, w, s): """Calculate the objective function Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. w : list of 2D arrays, element i h...
python
def _objective_function(self, data, w, s): """Calculate the objective function Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. w : list of 2D arrays, element i h...
[ "def", "_objective_function", "(", "self", ",", "data", ",", "w", ",", "s", ")", ":", "subjects", "=", "len", "(", "data", ")", "objective", "=", "0.0", "for", "m", "in", "range", "(", "subjects", ")", ":", "objective", "+=", "np", ".", "linalg", "...
Calculate the objective function Parameters ---------- data : list of 2D arrays, element i has shape=[voxels_i, samples] Each element in the list contains the fMRI data of one subject. w : list of 2D arrays, element i has shape=[voxels_i, features] The orthogon...
[ "Calculate", "the", "objective", "function" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_externals/srm.py#L557-L584
train
ContextLab/hypertools
hypertools/tools/text2mat.py
text2mat
def text2mat(data, vectorizer='CountVectorizer', semantic='LatentDirichletAllocation', corpus='wiki'): """ Turns a list of text samples into a matrix using a vectorizer and a text model Parameters ---------- data : list (or list of lists) of text samples The text data to trans...
python
def text2mat(data, vectorizer='CountVectorizer', semantic='LatentDirichletAllocation', corpus='wiki'): """ Turns a list of text samples into a matrix using a vectorizer and a text model Parameters ---------- data : list (or list of lists) of text samples The text data to trans...
[ "def", "text2mat", "(", "data", ",", "vectorizer", "=", "'CountVectorizer'", ",", "semantic", "=", "'LatentDirichletAllocation'", ",", "corpus", "=", "'wiki'", ")", ":", "if", "semantic", "is", "None", ":", "semantic", "=", "'LatentDirichletAllocation'", "if", "...
Turns a list of text samples into a matrix using a vectorizer and a text model Parameters ---------- data : list (or list of lists) of text samples The text data to transform vectorizer : str, dict, class or class instance The vectorizer to use. Built-in options are 'CountVectorizer' ...
[ "Turns", "a", "list", "of", "text", "samples", "into", "a", "matrix", "using", "a", "vectorizer", "and", "a", "text", "model" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/text2mat.py#L28-L148
train
ContextLab/hypertools
hypertools/_shared/helpers.py
patch_lines
def patch_lines(x): """ Draw lines between groups """ for idx in range(len(x)-1): x[idx] = np.vstack([x[idx], x[idx+1][0,:]]) return x
python
def patch_lines(x): """ Draw lines between groups """ for idx in range(len(x)-1): x[idx] = np.vstack([x[idx], x[idx+1][0,:]]) return x
[ "def", "patch_lines", "(", "x", ")", ":", "for", "idx", "in", "range", "(", "len", "(", "x", ")", "-", "1", ")", ":", "x", "[", "idx", "]", "=", "np", ".", "vstack", "(", "[", "x", "[", "idx", "]", ",", "x", "[", "idx", "+", "1", "]", "...
Draw lines between groups
[ "Draw", "lines", "between", "groups" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_shared/helpers.py#L161-L167
train
ContextLab/hypertools
hypertools/_shared/helpers.py
check_geo
def check_geo(geo): """ Checks a geo and makes sure the text fields are not binary """ geo = copy.copy(geo) def fix_item(item): if isinstance(item, six.binary_type): return item.decode() return item def fix_list(lst): return [fix_item(i) for i in lst] if isinsta...
python
def check_geo(geo): """ Checks a geo and makes sure the text fields are not binary """ geo = copy.copy(geo) def fix_item(item): if isinstance(item, six.binary_type): return item.decode() return item def fix_list(lst): return [fix_item(i) for i in lst] if isinsta...
[ "def", "check_geo", "(", "geo", ")", ":", "geo", "=", "copy", ".", "copy", "(", "geo", ")", "def", "fix_item", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "six", ".", "binary_type", ")", ":", "return", "item", ".", "decode", "(", ...
Checks a geo and makes sure the text fields are not binary
[ "Checks", "a", "geo", "and", "makes", "sure", "the", "text", "fields", "are", "not", "binary" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/_shared/helpers.py#L232-L251
train
ContextLab/hypertools
hypertools/tools/df2mat.py
df2mat
def df2mat(data, return_labels=False): """ Transforms a Pandas DataFrame into a Numpy array with binarized text columns This function transforms single-level df to an array so it can be plotted with HyperTools. Additionally, it uses the Pandas.Dataframe.get_dummies function to transform text colum...
python
def df2mat(data, return_labels=False): """ Transforms a Pandas DataFrame into a Numpy array with binarized text columns This function transforms single-level df to an array so it can be plotted with HyperTools. Additionally, it uses the Pandas.Dataframe.get_dummies function to transform text colum...
[ "def", "df2mat", "(", "data", ",", "return_labels", "=", "False", ")", ":", "df_str", "=", "data", ".", "select_dtypes", "(", "include", "=", "[", "'object'", "]", ")", "df_num", "=", "data", ".", "select_dtypes", "(", "exclude", "=", "[", "'object'", ...
Transforms a Pandas DataFrame into a Numpy array with binarized text columns This function transforms single-level df to an array so it can be plotted with HyperTools. Additionally, it uses the Pandas.Dataframe.get_dummies function to transform text columns into binary vectors, or 'dummy variables'. ...
[ "Transforms", "a", "Pandas", "DataFrame", "into", "a", "Numpy", "array", "with", "binarized", "text", "columns" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/df2mat.py#L6-L45
train
ContextLab/hypertools
hypertools/tools/load.py
load
def load(dataset, reduce=None, ndims=None, align=None, normalize=None): """ Load a .geo file or example data Parameters ---------- dataset : string The name of the example dataset. Can be a `.geo` file, or one of a number of example datasets listed below. `weights` is list...
python
def load(dataset, reduce=None, ndims=None, align=None, normalize=None): """ Load a .geo file or example data Parameters ---------- dataset : string The name of the example dataset. Can be a `.geo` file, or one of a number of example datasets listed below. `weights` is list...
[ "def", "load", "(", "dataset", ",", "reduce", "=", "None", ",", "ndims", "=", "None", ",", "align", "=", "None", ",", "normalize", "=", "None", ")", ":", "if", "dataset", "[", "-", "4", ":", "]", "==", "'.geo'", ":", "geo", "=", "dd", ".", "io"...
Load a .geo file or example data Parameters ---------- dataset : string The name of the example dataset. Can be a `.geo` file, or one of a number of example datasets listed below. `weights` is list of 2 numpy arrays, each containing average brain activity (fMRI) from 18 su...
[ "Load", "a", ".", "geo", "file", "or", "example", "data" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/load.py#L30-L129
train
ContextLab/hypertools
hypertools/datageometry.py
DataGeometry.transform
def transform(self, data=None): """ Return transformed data, or transform new data using the same model parameters Parameters ---------- data : numpy array, pandas dataframe or list of arrays/dfs The data to transform. If no data is passed, the xform_data fr...
python
def transform(self, data=None): """ Return transformed data, or transform new data using the same model parameters Parameters ---------- data : numpy array, pandas dataframe or list of arrays/dfs The data to transform. If no data is passed, the xform_data fr...
[ "def", "transform", "(", "self", ",", "data", "=", "None", ")", ":", "# if no new data passed,", "if", "data", "is", "None", ":", "return", "self", ".", "xform_data", "else", ":", "formatted", "=", "format_data", "(", "data", ",", "semantic", "=", "self", ...
Return transformed data, or transform new data using the same model parameters Parameters ---------- data : numpy array, pandas dataframe or list of arrays/dfs The data to transform. If no data is passed, the xform_data from the DataGeometry object will be retur...
[ "Return", "transformed", "data", "or", "transform", "new", "data", "using", "the", "same", "model", "parameters" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/datageometry.py#L110-L142
train
ContextLab/hypertools
hypertools/datageometry.py
DataGeometry.save
def save(self, fname, compression='blosc'): """ Save method for the data geometry object The data will be saved as a 'geo' file, which is a dictionary containing the elements of a data geometry object saved in the hd5 format using `deepdish`. Parameters --------...
python
def save(self, fname, compression='blosc'): """ Save method for the data geometry object The data will be saved as a 'geo' file, which is a dictionary containing the elements of a data geometry object saved in the hd5 format using `deepdish`. Parameters --------...
[ "def", "save", "(", "self", ",", "fname", ",", "compression", "=", "'blosc'", ")", ":", "if", "hasattr", "(", "self", ",", "'dtype'", ")", ":", "if", "'list'", "in", "self", ".", "dtype", ":", "data", "=", "np", ".", "array", "(", "self", ".", "d...
Save method for the data geometry object The data will be saved as a 'geo' file, which is a dictionary containing the elements of a data geometry object saved in the hd5 format using `deepdish`. Parameters ---------- fname : str A name for the file. If the...
[ "Save", "method", "for", "the", "data", "geometry", "object" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/datageometry.py#L191-L238
train
ContextLab/hypertools
hypertools/tools/analyze.py
analyze
def analyze(data, normalize=None, reduce=None, ndims=None, align=None, internal=False): """ Wrapper function for normalize -> reduce -> align transformations. Parameters ---------- data : numpy array, pandas df, or list of arrays/dfs The data to analyze normalize : str or False or None...
python
def analyze(data, normalize=None, reduce=None, ndims=None, align=None, internal=False): """ Wrapper function for normalize -> reduce -> align transformations. Parameters ---------- data : numpy array, pandas df, or list of arrays/dfs The data to analyze normalize : str or False or None...
[ "def", "analyze", "(", "data", ",", "normalize", "=", "None", ",", "reduce", "=", "None", ",", "ndims", "=", "None", ",", "align", "=", "None", ",", "internal", "=", "False", ")", ":", "# return processed data", "return", "aligner", "(", "reducer", "(", ...
Wrapper function for normalize -> reduce -> align transformations. Parameters ---------- data : numpy array, pandas df, or list of arrays/dfs The data to analyze normalize : str or False or None If set to 'across', the columns of the input data will be z-scored across lists (de...
[ "Wrapper", "function", "for", "normalize", "-", ">", "reduce", "-", ">", "align", "transformations", "." ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/analyze.py#L8-L54
train
ContextLab/hypertools
hypertools/tools/reduce.py
reduce
def reduce(x, reduce='IncrementalPCA', ndims=None, normalize=None, align=None, model=None, model_params=None, internal=False, format_data=True): """ Reduces dimensionality of an array, or list of arrays Parameters ---------- x : Numpy array or list of arrays Dimensionality reduct...
python
def reduce(x, reduce='IncrementalPCA', ndims=None, normalize=None, align=None, model=None, model_params=None, internal=False, format_data=True): """ Reduces dimensionality of an array, or list of arrays Parameters ---------- x : Numpy array or list of arrays Dimensionality reduct...
[ "def", "reduce", "(", "x", ",", "reduce", "=", "'IncrementalPCA'", ",", "ndims", "=", "None", ",", "normalize", "=", "None", ",", "align", "=", "None", ",", "model", "=", "None", ",", "model_params", "=", "None", ",", "internal", "=", "False", ",", "...
Reduces dimensionality of an array, or list of arrays Parameters ---------- x : Numpy array or list of arrays Dimensionality reduction using PCA is performed on this array. reduce : str or dict Decomposition/manifold learning model to use. Models supported: PCA, IncrementalPCA...
[ "Reduces", "dimensionality", "of", "an", "array", "or", "list", "of", "arrays" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/reduce.py#L36-L158
train
ContextLab/hypertools
hypertools/tools/cluster.py
cluster
def cluster(x, cluster='KMeans', n_clusters=3, ndims=None, format_data=True): """ Performs clustering analysis and returns a list of cluster labels Parameters ---------- x : A Numpy array, Pandas Dataframe or list of arrays/dfs The data to be clustered. You can pass a single array/df or a ...
python
def cluster(x, cluster='KMeans', n_clusters=3, ndims=None, format_data=True): """ Performs clustering analysis and returns a list of cluster labels Parameters ---------- x : A Numpy array, Pandas Dataframe or list of arrays/dfs The data to be clustered. You can pass a single array/df or a ...
[ "def", "cluster", "(", "x", ",", "cluster", "=", "'KMeans'", ",", "n_clusters", "=", "3", ",", "ndims", "=", "None", ",", "format_data", "=", "True", ")", ":", "if", "cluster", "==", "None", ":", "return", "x", "elif", "(", "isinstance", "(", "cluste...
Performs clustering analysis and returns a list of cluster labels Parameters ---------- x : A Numpy array, Pandas Dataframe or list of arrays/dfs The data to be clustered. You can pass a single array/df or a list. If a list is passed, the arrays will be stacked and the clustering w...
[ "Performs", "clustering", "analysis", "and", "returns", "a", "list", "of", "cluster", "labels" ]
b76c7ac8061998b560e969ff8e4f4c915088e7a0
https://github.com/ContextLab/hypertools/blob/b76c7ac8061998b560e969ff8e4f4c915088e7a0/hypertools/tools/cluster.py#L28-L100
train
lorien/grab
grab/transport/curl.py
build_grab_exception
def build_grab_exception(ex, curl): """ Build Grab exception from the pycurl exception Args: ex - the original pycurl exception curl - the Curl instance raised the exception """ # CURLE_WRITE_ERROR (23) # An error occurred when writing received data to a local file, or # an ...
python
def build_grab_exception(ex, curl): """ Build Grab exception from the pycurl exception Args: ex - the original pycurl exception curl - the Curl instance raised the exception """ # CURLE_WRITE_ERROR (23) # An error occurred when writing received data to a local file, or # an ...
[ "def", "build_grab_exception", "(", "ex", ",", "curl", ")", ":", "# CURLE_WRITE_ERROR (23)", "# An error occurred when writing received data to a local file, or", "# an error was returned to libcurl from a write callback.", "# This exception should be ignored if grab_callback_interrupted", "...
Build Grab exception from the pycurl exception Args: ex - the original pycurl exception curl - the Curl instance raised the exception
[ "Build", "Grab", "exception", "from", "the", "pycurl", "exception" ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/transport/curl.py#L587-L630
train
lorien/grab
grab/transport/curl.py
CurlTransport.body_processor
def body_processor(self, chunk): """ Process body of response. """ if self.config_nobody: self.curl.grab_callback_interrupted = True return 0 bytes_read = len(chunk) self.response_body_bytes_read += bytes_read if self.body_file: ...
python
def body_processor(self, chunk): """ Process body of response. """ if self.config_nobody: self.curl.grab_callback_interrupted = True return 0 bytes_read = len(chunk) self.response_body_bytes_read += bytes_read if self.body_file: ...
[ "def", "body_processor", "(", "self", ",", "chunk", ")", ":", "if", "self", ".", "config_nobody", ":", "self", ".", "curl", ".", "grab_callback_interrupted", "=", "True", "return", "0", "bytes_read", "=", "len", "(", "chunk", ")", "self", ".", "response_bo...
Process body of response.
[ "Process", "body", "of", "response", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/transport/curl.py#L134-L158
train
lorien/grab
grab/transport/curl.py
CurlTransport.debug_processor
def debug_processor(self, _type, text): """ Process request details. 0: CURLINFO_TEXT 1: CURLINFO_HEADER_IN 2: CURLINFO_HEADER_OUT 3: CURLINFO_DATA_IN 4: CURLINFO_DATA_OUT 5: CURLINFO_unrecognized_type """ if _type == pycurl.INFOTYPE_HEADE...
python
def debug_processor(self, _type, text): """ Process request details. 0: CURLINFO_TEXT 1: CURLINFO_HEADER_IN 2: CURLINFO_HEADER_OUT 3: CURLINFO_DATA_IN 4: CURLINFO_DATA_OUT 5: CURLINFO_unrecognized_type """ if _type == pycurl.INFOTYPE_HEADE...
[ "def", "debug_processor", "(", "self", ",", "_type", ",", "text", ")", ":", "if", "_type", "==", "pycurl", ".", "INFOTYPE_HEADER_OUT", ":", "if", "isinstance", "(", "text", ",", "six", ".", "text_type", ")", ":", "text", "=", "text", ".", "encode", "("...
Process request details. 0: CURLINFO_TEXT 1: CURLINFO_HEADER_IN 2: CURLINFO_HEADER_OUT 3: CURLINFO_DATA_IN 4: CURLINFO_DATA_OUT 5: CURLINFO_unrecognized_type
[ "Process", "request", "details", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/transport/curl.py#L160-L200
train
lorien/grab
grab/transport/curl.py
CurlTransport.extract_cookiejar
def extract_cookiejar(self): """ Extract cookies that pycurl instance knows. Returns `CookieJar` object. """ # Example of line: # www.google.com\tFALSE\t/accounts/\tFALSE\t0' # \tGoogleAccountsLocale_session\ten # Fields: # * domain # * w...
python
def extract_cookiejar(self): """ Extract cookies that pycurl instance knows. Returns `CookieJar` object. """ # Example of line: # www.google.com\tFALSE\t/accounts/\tFALSE\t0' # \tGoogleAccountsLocale_session\ten # Fields: # * domain # * w...
[ "def", "extract_cookiejar", "(", "self", ")", ":", "# Example of line:", "# www.google.com\\tFALSE\\t/accounts/\\tFALSE\\t0'", "# \\tGoogleAccountsLocale_session\\ten", "# Fields:", "# * domain", "# * whether or not all machines under that domain can", "# read the cookie's information.", "...
Extract cookies that pycurl instance knows. Returns `CookieJar` object.
[ "Extract", "cookies", "that", "pycurl", "instance", "knows", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/transport/curl.py#L525-L567
train
lorien/grab
grab/util/log.py
default_logging
def default_logging(grab_log=None, # '/tmp/grab.log', network_log=None, # '/tmp/grab.network.log', level=logging.DEBUG, mode='a', propagate_network_logger=False): """ Customize logging output to display all log messages except grab network logs. ...
python
def default_logging(grab_log=None, # '/tmp/grab.log', network_log=None, # '/tmp/grab.network.log', level=logging.DEBUG, mode='a', propagate_network_logger=False): """ Customize logging output to display all log messages except grab network logs. ...
[ "def", "default_logging", "(", "grab_log", "=", "None", ",", "# '/tmp/grab.log',", "network_log", "=", "None", ",", "# '/tmp/grab.network.log',", "level", "=", "logging", ".", "DEBUG", ",", "mode", "=", "'a'", ",", "propagate_network_logger", "=", "False", ")", ...
Customize logging output to display all log messages except grab network logs. Redirect grab network logs into file.
[ "Customize", "logging", "output", "to", "display", "all", "log", "messages", "except", "grab", "network", "logs", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/util/log.py#L7-L31
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train