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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
lorien/grab
grab/document.py
Document.text_assert_any
def text_assert_any(self, anchors, byte=False): """ If no `anchors` were found then raise `DataNotFound` exception. """ found = False for anchor in anchors: if self.text_search(anchor, byte=byte): found = True break if not found: raise DataNotFound(u'Substrings not found: %s' % ', '.join(anchors))
python
def text_assert_any(self, anchors, byte=False): """ If no `anchors` were found then raise `DataNotFound` exception. """ found = False for anchor in anchors: if self.text_search(anchor, byte=byte): found = True break if not found: raise DataNotFound(u'Substrings not found: %s' % ', '.join(anchors))
[ "def", "text_assert_any", "(", "self", ",", "anchors", ",", "byte", "=", "False", ")", ":", "found", "=", "False", "for", "anchor", "in", "anchors", ":", "if", "self", ".", "text_search", "(", "anchor", ",", "byte", "=", "byte", ")", ":", "found", "=...
If no `anchors` were found then raise `DataNotFound` exception.
[ "If", "no", "anchors", "were", "found", "then", "raise", "DataNotFound", "exception", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L440-L452
train
214,900
lorien/grab
grab/document.py
Document.rex_text
def rex_text(self, regexp, flags=0, byte=False, default=NULL): """ Search regular expression in response body and return content of first matching group. :param byte: if False then search is performed in `response.unicode_body()` else the rex is searched in `response.body`. """ # pylint: disable=no-member try: match = self.rex_search(regexp, flags=flags, byte=byte) except DataNotFound: if default is NULL: raise DataNotFound('Regexp not found') else: return default else: return normalize_space(decode_entities(match.group(1)))
python
def rex_text(self, regexp, flags=0, byte=False, default=NULL): """ Search regular expression in response body and return content of first matching group. :param byte: if False then search is performed in `response.unicode_body()` else the rex is searched in `response.body`. """ # pylint: disable=no-member try: match = self.rex_search(regexp, flags=flags, byte=byte) except DataNotFound: if default is NULL: raise DataNotFound('Regexp not found') else: return default else: return normalize_space(decode_entities(match.group(1)))
[ "def", "rex_text", "(", "self", ",", "regexp", ",", "flags", "=", "0", ",", "byte", "=", "False", ",", "default", "=", "NULL", ")", ":", "# pylint: disable=no-member", "try", ":", "match", "=", "self", ".", "rex_search", "(", "regexp", ",", "flags", "=...
Search regular expression in response body and return content of first matching group. :param byte: if False then search is performed in `response.unicode_body()` else the rex is searched in `response.body`.
[ "Search", "regular", "expression", "in", "response", "body", "and", "return", "content", "of", "first", "matching", "group", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L456-L474
train
214,901
lorien/grab
grab/document.py
Document.rex_search
def rex_search(self, regexp, flags=0, byte=False, default=NULL): """ Search the regular expression in response body. :param byte: if False then search is performed in `response.unicode_body()` else the rex is searched in `response.body`. Note: if you use default non-byte mode than do not forget to build your regular expression with re.U flag. Return found match object or None """ regexp = normalize_regexp(regexp, flags) match = None if byte: if not isinstance(regexp.pattern, six.text_type) or not six.PY3: # if six.PY3: # body = self.body_as_bytes() # else: # body = self.body match = regexp.search(self.body) else: if isinstance(regexp.pattern, six.text_type) or not six.PY3: ubody = self.unicode_body() match = regexp.search(ubody) if match: return match else: if default is NULL: raise DataNotFound('Could not find regexp: %s' % regexp) else: return default
python
def rex_search(self, regexp, flags=0, byte=False, default=NULL): """ Search the regular expression in response body. :param byte: if False then search is performed in `response.unicode_body()` else the rex is searched in `response.body`. Note: if you use default non-byte mode than do not forget to build your regular expression with re.U flag. Return found match object or None """ regexp = normalize_regexp(regexp, flags) match = None if byte: if not isinstance(regexp.pattern, six.text_type) or not six.PY3: # if six.PY3: # body = self.body_as_bytes() # else: # body = self.body match = regexp.search(self.body) else: if isinstance(regexp.pattern, six.text_type) or not six.PY3: ubody = self.unicode_body() match = regexp.search(ubody) if match: return match else: if default is NULL: raise DataNotFound('Could not find regexp: %s' % regexp) else: return default
[ "def", "rex_search", "(", "self", ",", "regexp", ",", "flags", "=", "0", ",", "byte", "=", "False", ",", "default", "=", "NULL", ")", ":", "regexp", "=", "normalize_regexp", "(", "regexp", ",", "flags", ")", "match", "=", "None", "if", "byte", ":", ...
Search the regular expression in response body. :param byte: if False then search is performed in `response.unicode_body()` else the rex is searched in `response.body`. Note: if you use default non-byte mode than do not forget to build your regular expression with re.U flag. Return found match object or None
[ "Search", "the", "regular", "expression", "in", "response", "body", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L476-L509
train
214,902
lorien/grab
grab/document.py
Document.rex_assert
def rex_assert(self, rex, byte=False): """ If `rex` expression is not found then raise `DataNotFound` exception. """ self.rex_search(rex, byte=byte)
python
def rex_assert(self, rex, byte=False): """ If `rex` expression is not found then raise `DataNotFound` exception. """ self.rex_search(rex, byte=byte)
[ "def", "rex_assert", "(", "self", ",", "rex", ",", "byte", "=", "False", ")", ":", "self", ".", "rex_search", "(", "rex", ",", "byte", "=", "byte", ")" ]
If `rex` expression is not found then raise `DataNotFound` exception.
[ "If", "rex", "expression", "is", "not", "found", "then", "raise", "DataNotFound", "exception", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L511-L516
train
214,903
lorien/grab
grab/document.py
Document.pyquery
def pyquery(self): """ Returns pyquery handler. """ if not self._pyquery: from pyquery import PyQuery self._pyquery = PyQuery(self.tree) return self._pyquery
python
def pyquery(self): """ Returns pyquery handler. """ if not self._pyquery: from pyquery import PyQuery self._pyquery = PyQuery(self.tree) return self._pyquery
[ "def", "pyquery", "(", "self", ")", ":", "if", "not", "self", ".", "_pyquery", ":", "from", "pyquery", "import", "PyQuery", "self", ".", "_pyquery", "=", "PyQuery", "(", "self", ".", "tree", ")", "return", "self", ".", "_pyquery" ]
Returns pyquery handler.
[ "Returns", "pyquery", "handler", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L521-L530
train
214,904
lorien/grab
grab/document.py
Document.unicode_body
def unicode_body(self, ignore_errors=True, fix_special_entities=True): """ Return response body as unicode string. """ if not self._unicode_body: self._unicode_body = self.convert_body_to_unicode( body=self.body, bom=self.bom, charset=self.charset, ignore_errors=ignore_errors, fix_special_entities=fix_special_entities, ) return self._unicode_body
python
def unicode_body(self, ignore_errors=True, fix_special_entities=True): """ Return response body as unicode string. """ if not self._unicode_body: self._unicode_body = self.convert_body_to_unicode( body=self.body, bom=self.bom, charset=self.charset, ignore_errors=ignore_errors, fix_special_entities=fix_special_entities, ) return self._unicode_body
[ "def", "unicode_body", "(", "self", ",", "ignore_errors", "=", "True", ",", "fix_special_entities", "=", "True", ")", ":", "if", "not", "self", ".", "_unicode_body", ":", "self", ".", "_unicode_body", "=", "self", ".", "convert_body_to_unicode", "(", "body", ...
Return response body as unicode string.
[ "Return", "response", "body", "as", "unicode", "string", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L562-L575
train
214,905
lorien/grab
grab/document.py
Document.choose_form
def choose_form(self, number=None, xpath=None, name=None, **kwargs): """ Set the default form. :param number: number of form (starting from zero) :param id: value of "id" attribute :param name: value of "name" attribute :param xpath: XPath query :raises: :class:`DataNotFound` if form not found :raises: :class:`GrabMisuseError` if method is called without parameters Selected form will be available via `form` attribute of `Grab` instance. All form methods will work with default form. Examples:: # Select second form g.choose_form(1) # Select by id g.choose_form(id="register") # Select by name g.choose_form(name="signup") # Select by xpath g.choose_form(xpath='//form[contains(@action, "/submit")]') """ id_ = kwargs.pop('id', None) if id_ is not None: try: self._lxml_form = self.select('//form[@id="%s"]' % id_).node() except IndexError: raise DataNotFound("There is no form with id: %s" % id_) elif name is not None: try: self._lxml_form = self.select( '//form[@name="%s"]' % name).node() except IndexError: raise DataNotFound('There is no form with name: %s' % name) elif number is not None: try: self._lxml_form = self.tree.forms[number] except IndexError: raise DataNotFound('There is no form with number: %s' % number) elif xpath is not None: try: self._lxml_form = self.select(xpath).node() except IndexError: raise DataNotFound( 'Could not find form with xpath: %s' % xpath) else: raise GrabMisuseError('choose_form methods requires one of ' '[number, id, name, xpath] arguments')
python
def choose_form(self, number=None, xpath=None, name=None, **kwargs): """ Set the default form. :param number: number of form (starting from zero) :param id: value of "id" attribute :param name: value of "name" attribute :param xpath: XPath query :raises: :class:`DataNotFound` if form not found :raises: :class:`GrabMisuseError` if method is called without parameters Selected form will be available via `form` attribute of `Grab` instance. All form methods will work with default form. Examples:: # Select second form g.choose_form(1) # Select by id g.choose_form(id="register") # Select by name g.choose_form(name="signup") # Select by xpath g.choose_form(xpath='//form[contains(@action, "/submit")]') """ id_ = kwargs.pop('id', None) if id_ is not None: try: self._lxml_form = self.select('//form[@id="%s"]' % id_).node() except IndexError: raise DataNotFound("There is no form with id: %s" % id_) elif name is not None: try: self._lxml_form = self.select( '//form[@name="%s"]' % name).node() except IndexError: raise DataNotFound('There is no form with name: %s' % name) elif number is not None: try: self._lxml_form = self.tree.forms[number] except IndexError: raise DataNotFound('There is no form with number: %s' % number) elif xpath is not None: try: self._lxml_form = self.select(xpath).node() except IndexError: raise DataNotFound( 'Could not find form with xpath: %s' % xpath) else: raise GrabMisuseError('choose_form methods requires one of ' '[number, id, name, xpath] arguments')
[ "def", "choose_form", "(", "self", ",", "number", "=", "None", ",", "xpath", "=", "None", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "id_", "=", "kwargs", ".", "pop", "(", "'id'", ",", "None", ")", "if", "id_", "is", "not", "N...
Set the default form. :param number: number of form (starting from zero) :param id: value of "id" attribute :param name: value of "name" attribute :param xpath: XPath query :raises: :class:`DataNotFound` if form not found :raises: :class:`GrabMisuseError` if method is called without parameters Selected form will be available via `form` attribute of `Grab` instance. All form methods will work with default form. Examples:: # Select second form g.choose_form(1) # Select by id g.choose_form(id="register") # Select by name g.choose_form(name="signup") # Select by xpath g.choose_form(xpath='//form[contains(@action, "/submit")]')
[ "Set", "the", "default", "form", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L688-L743
train
214,906
lorien/grab
grab/document.py
Document.form
def form(self): """ This attribute points to default form. If form was not selected manually then select the form which has the biggest number of input elements. The form value is just an `lxml.html` form element. Example:: g.go('some URL') # Choose form automatically print g.form # And now choose form manually g.choose_form(1) print g.form """ if self._lxml_form is None: forms = [(idx, len(list(x.fields))) for idx, x in enumerate(self.tree.forms)] if forms: idx = sorted(forms, key=lambda x: x[1], reverse=True)[0][0] self.choose_form(idx) else: raise DataNotFound('Response does not contains any form') return self._lxml_form
python
def form(self): """ This attribute points to default form. If form was not selected manually then select the form which has the biggest number of input elements. The form value is just an `lxml.html` form element. Example:: g.go('some URL') # Choose form automatically print g.form # And now choose form manually g.choose_form(1) print g.form """ if self._lxml_form is None: forms = [(idx, len(list(x.fields))) for idx, x in enumerate(self.tree.forms)] if forms: idx = sorted(forms, key=lambda x: x[1], reverse=True)[0][0] self.choose_form(idx) else: raise DataNotFound('Response does not contains any form') return self._lxml_form
[ "def", "form", "(", "self", ")", ":", "if", "self", ".", "_lxml_form", "is", "None", ":", "forms", "=", "[", "(", "idx", ",", "len", "(", "list", "(", "x", ".", "fields", ")", ")", ")", "for", "idx", ",", "x", "in", "enumerate", "(", "self", ...
This attribute points to default form. If form was not selected manually then select the form which has the biggest number of input elements. The form value is just an `lxml.html` form element. Example:: g.go('some URL') # Choose form automatically print g.form # And now choose form manually g.choose_form(1) print g.form
[ "This", "attribute", "points", "to", "default", "form", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L746-L774
train
214,907
lorien/grab
grab/document.py
Document.set_input
def set_input(self, name, value): """ Set the value of form element by its `name` attribute. :param name: name of element :param value: value which should be set to element To check/uncheck the checkbox pass boolean value. Example:: g.set_input('sex', 'male') # Check the checkbox g.set_input('accept', True) """ if self._lxml_form is None: self.choose_form_by_element('.//*[@name="%s"]' % name) elem = self.form.inputs[name] # pylint: disable=no-member processed = False if getattr(elem, 'type', None) == 'checkbox': if isinstance(value, bool): elem.checked = value processed = True if not processed: # We need to remember original values of file fields # Because lxml will convert UploadContent/UploadFile object to # string if getattr(elem, 'type', '').lower() == 'file': self._file_fields[name] = value elem.value = '' else: elem.value = value
python
def set_input(self, name, value): """ Set the value of form element by its `name` attribute. :param name: name of element :param value: value which should be set to element To check/uncheck the checkbox pass boolean value. Example:: g.set_input('sex', 'male') # Check the checkbox g.set_input('accept', True) """ if self._lxml_form is None: self.choose_form_by_element('.//*[@name="%s"]' % name) elem = self.form.inputs[name] # pylint: disable=no-member processed = False if getattr(elem, 'type', None) == 'checkbox': if isinstance(value, bool): elem.checked = value processed = True if not processed: # We need to remember original values of file fields # Because lxml will convert UploadContent/UploadFile object to # string if getattr(elem, 'type', '').lower() == 'file': self._file_fields[name] = value elem.value = '' else: elem.value = value
[ "def", "set_input", "(", "self", ",", "name", ",", "value", ")", ":", "if", "self", ".", "_lxml_form", "is", "None", ":", "self", ".", "choose_form_by_element", "(", "'.//*[@name=\"%s\"]'", "%", "name", ")", "elem", "=", "self", ".", "form", ".", "inputs...
Set the value of form element by its `name` attribute. :param name: name of element :param value: value which should be set to element To check/uncheck the checkbox pass boolean value. Example:: g.set_input('sex', 'male') # Check the checkbox g.set_input('accept', True)
[ "Set", "the", "value", "of", "form", "element", "by", "its", "name", "attribute", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L776-L811
train
214,908
lorien/grab
grab/document.py
Document.set_input_by_id
def set_input_by_id(self, _id, value): """ Set the value of form element by its `id` attribute. :param _id: id of element :param value: value which should be set to element """ xpath = './/*[@id="%s"]' % _id if self._lxml_form is None: self.choose_form_by_element(xpath) sel = XpathSelector(self.form) elem = sel.select(xpath).node() # pylint: disable=no-member return self.set_input(elem.get('name'), value)
python
def set_input_by_id(self, _id, value): """ Set the value of form element by its `id` attribute. :param _id: id of element :param value: value which should be set to element """ xpath = './/*[@id="%s"]' % _id if self._lxml_form is None: self.choose_form_by_element(xpath) sel = XpathSelector(self.form) elem = sel.select(xpath).node() # pylint: disable=no-member return self.set_input(elem.get('name'), value)
[ "def", "set_input_by_id", "(", "self", ",", "_id", ",", "value", ")", ":", "xpath", "=", "'.//*[@id=\"%s\"]'", "%", "_id", "if", "self", ".", "_lxml_form", "is", "None", ":", "self", ".", "choose_form_by_element", "(", "xpath", ")", "sel", "=", "XpathSelec...
Set the value of form element by its `id` attribute. :param _id: id of element :param value: value which should be set to element
[ "Set", "the", "value", "of", "form", "element", "by", "its", "id", "attribute", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L813-L827
train
214,909
lorien/grab
grab/document.py
Document.set_input_by_number
def set_input_by_number(self, number, value): """ Set the value of form element by its number in the form :param number: number of element :param value: value which should be set to element """ sel = XpathSelector(self.form) elem = sel.select('.//input[@type="text"]')[number].node() return self.set_input(elem.get('name'), value)
python
def set_input_by_number(self, number, value): """ Set the value of form element by its number in the form :param number: number of element :param value: value which should be set to element """ sel = XpathSelector(self.form) elem = sel.select('.//input[@type="text"]')[number].node() return self.set_input(elem.get('name'), value)
[ "def", "set_input_by_number", "(", "self", ",", "number", ",", "value", ")", ":", "sel", "=", "XpathSelector", "(", "self", ".", "form", ")", "elem", "=", "sel", ".", "select", "(", "'.//input[@type=\"text\"]'", ")", "[", "number", "]", ".", "node", "(",...
Set the value of form element by its number in the form :param number: number of element :param value: value which should be set to element
[ "Set", "the", "value", "of", "form", "element", "by", "its", "number", "in", "the", "form" ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L829-L839
train
214,910
lorien/grab
grab/document.py
Document.set_input_by_xpath
def set_input_by_xpath(self, xpath, value): """ Set the value of form element by xpath :param xpath: xpath path :param value: value which should be set to element """ elem = self.select(xpath).node() if self._lxml_form is None: # Explicitly set the default form # which contains found element parent = elem while True: parent = parent.getparent() # pylint: disable=no-member if parent.tag == 'form': self._lxml_form = parent break # pylint: disable=no-member return self.set_input(elem.get('name'), value)
python
def set_input_by_xpath(self, xpath, value): """ Set the value of form element by xpath :param xpath: xpath path :param value: value which should be set to element """ elem = self.select(xpath).node() if self._lxml_form is None: # Explicitly set the default form # which contains found element parent = elem while True: parent = parent.getparent() # pylint: disable=no-member if parent.tag == 'form': self._lxml_form = parent break # pylint: disable=no-member return self.set_input(elem.get('name'), value)
[ "def", "set_input_by_xpath", "(", "self", ",", "xpath", ",", "value", ")", ":", "elem", "=", "self", ".", "select", "(", "xpath", ")", ".", "node", "(", ")", "if", "self", ".", "_lxml_form", "is", "None", ":", "# Explicitly set the default form", "# which ...
Set the value of form element by xpath :param xpath: xpath path :param value: value which should be set to element
[ "Set", "the", "value", "of", "form", "element", "by", "xpath" ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L841-L862
train
214,911
lorien/grab
grab/document.py
Document.get_form_request
def get_form_request( self, submit_name=None, url=None, extra_post=None, remove_from_post=None): """ Submit default form. :param submit_name: name of button which should be "clicked" to submit form :param url: explicitly specify form action url :param extra_post: (dict or list of pairs) additional form data which will override data automatically extracted from the form. :param remove_from_post: list of keys to remove from the submitted data Following input elements are automatically processed: * input[type="hidden"] - default value * select: value of last option * radio - ??? * checkbox - ??? Multipart forms are correctly recognized by grab library. """ # pylint: disable=no-member post = self.form_fields() # Build list of submit buttons which have a name submit_controls = {} for elem in self.form.inputs: if (elem.tag == 'input' and elem.type == 'submit' and elem.get('name') is not None): submit_controls[elem.name] = elem # All this code need only for one reason: # to not send multiple submit keys in form data # in real life only this key is submitted whose button # was pressed if submit_controls: # If name of submit control is not given then # use the name of first submit control if submit_name is None or submit_name not in submit_controls: controls = sorted(submit_controls.values(), key=lambda x: x.name) submit_name = controls[0].name # Form data should contain only one submit control for name in submit_controls: if name != submit_name: if name in post: del post[name] if url: action_url = urljoin(self.url, url) else: action_url = urljoin(self.url, self.form.action) # Values from `extra_post` should override values in form # `extra_post` allows multiple value of one key # Process saved values of file fields if self.form.method == 'POST': if 'multipart' in self.form.get('enctype', ''): for key, obj in self._file_fields.items(): post[key] = obj post_items = list(post.items()) del post if extra_post: if isinstance(extra_post, dict): extra_post_items = extra_post.items() else: extra_post_items = extra_post # Drop existing post items with such key keys_to_drop = set([x for x, y in extra_post_items]) for key in keys_to_drop: post_items = [(x, y) for x, y in post_items if x != key] for key, value in extra_post_items: post_items.append((key, value)) if remove_from_post: post_items = [(x, y) for x, y in post_items if x not in remove_from_post] result = { 'multipart_post': None, 'post': None, 'url': None, } if self.form.method == 'POST': if 'multipart' in self.form.get('enctype', ''): result['multipart_post'] = post_items #self.grab.setup(multipart_post=post_items) else: result['post'] = post_items #self.grab.setup(post=post_items) result['url'] = action_url #self.grab.setup(url=action_url) else: url = action_url.split('?')[0] + '?' + smart_urlencode(post_items) result['url'] = url #self.grab.setup(url=url) return result
python
def get_form_request( self, submit_name=None, url=None, extra_post=None, remove_from_post=None): """ Submit default form. :param submit_name: name of button which should be "clicked" to submit form :param url: explicitly specify form action url :param extra_post: (dict or list of pairs) additional form data which will override data automatically extracted from the form. :param remove_from_post: list of keys to remove from the submitted data Following input elements are automatically processed: * input[type="hidden"] - default value * select: value of last option * radio - ??? * checkbox - ??? Multipart forms are correctly recognized by grab library. """ # pylint: disable=no-member post = self.form_fields() # Build list of submit buttons which have a name submit_controls = {} for elem in self.form.inputs: if (elem.tag == 'input' and elem.type == 'submit' and elem.get('name') is not None): submit_controls[elem.name] = elem # All this code need only for one reason: # to not send multiple submit keys in form data # in real life only this key is submitted whose button # was pressed if submit_controls: # If name of submit control is not given then # use the name of first submit control if submit_name is None or submit_name not in submit_controls: controls = sorted(submit_controls.values(), key=lambda x: x.name) submit_name = controls[0].name # Form data should contain only one submit control for name in submit_controls: if name != submit_name: if name in post: del post[name] if url: action_url = urljoin(self.url, url) else: action_url = urljoin(self.url, self.form.action) # Values from `extra_post` should override values in form # `extra_post` allows multiple value of one key # Process saved values of file fields if self.form.method == 'POST': if 'multipart' in self.form.get('enctype', ''): for key, obj in self._file_fields.items(): post[key] = obj post_items = list(post.items()) del post if extra_post: if isinstance(extra_post, dict): extra_post_items = extra_post.items() else: extra_post_items = extra_post # Drop existing post items with such key keys_to_drop = set([x for x, y in extra_post_items]) for key in keys_to_drop: post_items = [(x, y) for x, y in post_items if x != key] for key, value in extra_post_items: post_items.append((key, value)) if remove_from_post: post_items = [(x, y) for x, y in post_items if x not in remove_from_post] result = { 'multipart_post': None, 'post': None, 'url': None, } if self.form.method == 'POST': if 'multipart' in self.form.get('enctype', ''): result['multipart_post'] = post_items #self.grab.setup(multipart_post=post_items) else: result['post'] = post_items #self.grab.setup(post=post_items) result['url'] = action_url #self.grab.setup(url=action_url) else: url = action_url.split('?')[0] + '?' + smart_urlencode(post_items) result['url'] = url #self.grab.setup(url=url) return result
[ "def", "get_form_request", "(", "self", ",", "submit_name", "=", "None", ",", "url", "=", "None", ",", "extra_post", "=", "None", ",", "remove_from_post", "=", "None", ")", ":", "# pylint: disable=no-member", "post", "=", "self", ".", "form_fields", "(", ")"...
Submit default form. :param submit_name: name of button which should be "clicked" to submit form :param url: explicitly specify form action url :param extra_post: (dict or list of pairs) additional form data which will override data automatically extracted from the form. :param remove_from_post: list of keys to remove from the submitted data Following input elements are automatically processed: * input[type="hidden"] - default value * select: value of last option * radio - ??? * checkbox - ??? Multipart forms are correctly recognized by grab library.
[ "Submit", "default", "form", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L869-L978
train
214,912
lorien/grab
grab/document.py
Document.form_fields
def form_fields(self): """ Return fields of default form. Fill some fields with reasonable values. """ fields = dict(self.form.fields) # pylint: disable=no-member fields_to_remove = set() for key, val in list(fields.items()): if isinstance(val, CheckboxValues): if not len(val): # pylint: disable=len-as-condition del fields[key] elif len(val) == 1: fields[key] = val.pop() else: fields[key] = list(val) if isinstance(val, MultipleSelectOptions): if not len(val): # pylint: disable=len-as-condition del fields[key] elif len(val) == 1: fields[key] = val.pop() else: fields[key] = list(val) for elem in self.form.inputs: # pylint: disable=no-member # Ignore elements without name if not elem.get('name'): continue # Do not submit disabled fields # http://www.w3.org/TR/html4/interact/forms.html#h-17.12 if elem.get('disabled'): if elem.name in fields: fields_to_remove.add(elem.name) elif getattr(elem, 'type', None) == 'checkbox': if not elem.checked: if elem.name is not None: if elem.name in fields and fields[elem.name] is None: fields_to_remove.add(elem.name) else: if elem.name in fields_to_remove: fields_to_remove.remove(elem.name) if elem.tag == 'select': if elem.name in fields and fields[elem.name] is None: if elem.value_options: fields[elem.name] = elem.value_options[0] elif getattr(elem, 'type', None) == 'radio': if fields[elem.name] is None: fields[elem.name] = elem.get('value') for fname in fields_to_remove: del fields[fname] return fields
python
def form_fields(self): """ Return fields of default form. Fill some fields with reasonable values. """ fields = dict(self.form.fields) # pylint: disable=no-member fields_to_remove = set() for key, val in list(fields.items()): if isinstance(val, CheckboxValues): if not len(val): # pylint: disable=len-as-condition del fields[key] elif len(val) == 1: fields[key] = val.pop() else: fields[key] = list(val) if isinstance(val, MultipleSelectOptions): if not len(val): # pylint: disable=len-as-condition del fields[key] elif len(val) == 1: fields[key] = val.pop() else: fields[key] = list(val) for elem in self.form.inputs: # pylint: disable=no-member # Ignore elements without name if not elem.get('name'): continue # Do not submit disabled fields # http://www.w3.org/TR/html4/interact/forms.html#h-17.12 if elem.get('disabled'): if elem.name in fields: fields_to_remove.add(elem.name) elif getattr(elem, 'type', None) == 'checkbox': if not elem.checked: if elem.name is not None: if elem.name in fields and fields[elem.name] is None: fields_to_remove.add(elem.name) else: if elem.name in fields_to_remove: fields_to_remove.remove(elem.name) if elem.tag == 'select': if elem.name in fields and fields[elem.name] is None: if elem.value_options: fields[elem.name] = elem.value_options[0] elif getattr(elem, 'type', None) == 'radio': if fields[elem.name] is None: fields[elem.name] = elem.get('value') for fname in fields_to_remove: del fields[fname] return fields
[ "def", "form_fields", "(", "self", ")", ":", "fields", "=", "dict", "(", "self", ".", "form", ".", "fields", ")", "# pylint: disable=no-member", "fields_to_remove", "=", "set", "(", ")", "for", "key", ",", "val", "in", "list", "(", "fields", ".", "items"...
Return fields of default form. Fill some fields with reasonable values.
[ "Return", "fields", "of", "default", "form", "." ]
8b301db2a08c830245b61c589e58af6234f4db79
https://github.com/lorien/grab/blob/8b301db2a08c830245b61c589e58af6234f4db79/grab/document.py#L993-L1048
train
214,913
maxpumperla/elephas
elephas/utils/functional_utils.py
add_params
def add_params(param_list_left, param_list_right): """Add two lists of parameters one by one :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ res = [] for x, y in zip(param_list_left, param_list_right): res.append(x + y) return res
python
def add_params(param_list_left, param_list_right): """Add two lists of parameters one by one :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ res = [] for x, y in zip(param_list_left, param_list_right): res.append(x + y) return res
[ "def", "add_params", "(", "param_list_left", ",", "param_list_right", ")", ":", "res", "=", "[", "]", "for", "x", ",", "y", "in", "zip", "(", "param_list_left", ",", "param_list_right", ")", ":", "res", ".", "append", "(", "x", "+", "y", ")", "return",...
Add two lists of parameters one by one :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays
[ "Add", "two", "lists", "of", "parameters", "one", "by", "one" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L7-L17
train
214,914
maxpumperla/elephas
elephas/utils/functional_utils.py
subtract_params
def subtract_params(param_list_left, param_list_right): """Subtract two lists of parameters :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ res = [] for x, y in zip(param_list_left, param_list_right): res.append(x - y) return res
python
def subtract_params(param_list_left, param_list_right): """Subtract two lists of parameters :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ res = [] for x, y in zip(param_list_left, param_list_right): res.append(x - y) return res
[ "def", "subtract_params", "(", "param_list_left", ",", "param_list_right", ")", ":", "res", "=", "[", "]", "for", "x", ",", "y", "in", "zip", "(", "param_list_left", ",", "param_list_right", ")", ":", "res", ".", "append", "(", "x", "-", "y", ")", "ret...
Subtract two lists of parameters :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays
[ "Subtract", "two", "lists", "of", "parameters" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L20-L30
train
214,915
maxpumperla/elephas
elephas/utils/functional_utils.py
get_neutral
def get_neutral(array_list): """Get list of zero-valued numpy arrays for specified list of numpy arrays :param array_list: list of numpy arrays :return: list of zeros of same shape as input """ res = [] for x in array_list: res.append(np.zeros_like(x)) return res
python
def get_neutral(array_list): """Get list of zero-valued numpy arrays for specified list of numpy arrays :param array_list: list of numpy arrays :return: list of zeros of same shape as input """ res = [] for x in array_list: res.append(np.zeros_like(x)) return res
[ "def", "get_neutral", "(", "array_list", ")", ":", "res", "=", "[", "]", "for", "x", "in", "array_list", ":", "res", ".", "append", "(", "np", ".", "zeros_like", "(", "x", ")", ")", "return", "res" ]
Get list of zero-valued numpy arrays for specified list of numpy arrays :param array_list: list of numpy arrays :return: list of zeros of same shape as input
[ "Get", "list", "of", "zero", "-", "valued", "numpy", "arrays", "for", "specified", "list", "of", "numpy", "arrays" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L33-L43
train
214,916
maxpumperla/elephas
elephas/utils/functional_utils.py
divide_by
def divide_by(array_list, num_workers): """Divide a list of parameters by an integer num_workers. :param array_list: :param num_workers: :return: """ for i, x in enumerate(array_list): array_list[i] /= num_workers return array_list
python
def divide_by(array_list, num_workers): """Divide a list of parameters by an integer num_workers. :param array_list: :param num_workers: :return: """ for i, x in enumerate(array_list): array_list[i] /= num_workers return array_list
[ "def", "divide_by", "(", "array_list", ",", "num_workers", ")", ":", "for", "i", ",", "x", "in", "enumerate", "(", "array_list", ")", ":", "array_list", "[", "i", "]", "/=", "num_workers", "return", "array_list" ]
Divide a list of parameters by an integer num_workers. :param array_list: :param num_workers: :return:
[ "Divide", "a", "list", "of", "parameters", "by", "an", "integer", "num_workers", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/functional_utils.py#L46-L55
train
214,917
maxpumperla/elephas
elephas/parameter/server.py
HttpServer.start_flask_service
def start_flask_service(self): """Define Flask parameter server service. This HTTP server can do two things: get the current model parameters and update model parameters. After registering the `parameters` and `update` routes, the service will get started. """ app = Flask(__name__) self.app = app @app.route('/') def home(): return 'Elephas' @app.route('/parameters', methods=['GET']) def handle_get_parameters(): if self.mode == 'asynchronous': self.lock.acquire_read() self.pickled_weights = pickle.dumps(self.weights, -1) pickled_weights = self.pickled_weights if self.mode == 'asynchronous': self.lock.release() return pickled_weights @app.route('/update', methods=['POST']) def handle_update_parameters(): delta = pickle.loads(request.data) if self.mode == 'asynchronous': self.lock.acquire_write() if not self.master_network.built: self.master_network.build() # Just apply the gradient weights_before = self.weights self.weights = subtract_params(weights_before, delta) if self.mode == 'asynchronous': self.lock.release() return 'Update done' master_url = determine_master(self.port) host = master_url.split(':')[0] self.app.run(host=host, debug=self.debug, port=self.port, threaded=self.threaded, use_reloader=self.use_reloader)
python
def start_flask_service(self): """Define Flask parameter server service. This HTTP server can do two things: get the current model parameters and update model parameters. After registering the `parameters` and `update` routes, the service will get started. """ app = Flask(__name__) self.app = app @app.route('/') def home(): return 'Elephas' @app.route('/parameters', methods=['GET']) def handle_get_parameters(): if self.mode == 'asynchronous': self.lock.acquire_read() self.pickled_weights = pickle.dumps(self.weights, -1) pickled_weights = self.pickled_weights if self.mode == 'asynchronous': self.lock.release() return pickled_weights @app.route('/update', methods=['POST']) def handle_update_parameters(): delta = pickle.loads(request.data) if self.mode == 'asynchronous': self.lock.acquire_write() if not self.master_network.built: self.master_network.build() # Just apply the gradient weights_before = self.weights self.weights = subtract_params(weights_before, delta) if self.mode == 'asynchronous': self.lock.release() return 'Update done' master_url = determine_master(self.port) host = master_url.split(':')[0] self.app.run(host=host, debug=self.debug, port=self.port, threaded=self.threaded, use_reloader=self.use_reloader)
[ "def", "start_flask_service", "(", "self", ")", ":", "app", "=", "Flask", "(", "__name__", ")", "self", ".", "app", "=", "app", "@", "app", ".", "route", "(", "'/'", ")", "def", "home", "(", ")", ":", "return", "'Elephas'", "@", "app", ".", "route"...
Define Flask parameter server service. This HTTP server can do two things: get the current model parameters and update model parameters. After registering the `parameters` and `update` routes, the service will get started.
[ "Define", "Flask", "parameter", "server", "service", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/parameter/server.py#L92-L138
train
214,918
maxpumperla/elephas
elephas/mllib/adapter.py
to_matrix
def to_matrix(np_array): """Convert numpy array to MLlib Matrix """ if len(np_array.shape) == 2: return Matrices.dense(np_array.shape[0], np_array.shape[1], np_array.ravel()) else: raise Exception("An MLLib Matrix can only be created from a two-dimensional " + "numpy array, got {}".format(len(np_array.shape)))
python
def to_matrix(np_array): """Convert numpy array to MLlib Matrix """ if len(np_array.shape) == 2: return Matrices.dense(np_array.shape[0], np_array.shape[1], np_array.ravel()) else: raise Exception("An MLLib Matrix can only be created from a two-dimensional " + "numpy array, got {}".format(len(np_array.shape)))
[ "def", "to_matrix", "(", "np_array", ")", ":", "if", "len", "(", "np_array", ".", "shape", ")", "==", "2", ":", "return", "Matrices", ".", "dense", "(", "np_array", ".", "shape", "[", "0", "]", ",", "np_array", ".", "shape", "[", "1", "]", ",", "...
Convert numpy array to MLlib Matrix
[ "Convert", "numpy", "array", "to", "MLlib", "Matrix" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/mllib/adapter.py#L11-L20
train
214,919
maxpumperla/elephas
elephas/mllib/adapter.py
to_vector
def to_vector(np_array): """Convert numpy array to MLlib Vector """ if len(np_array.shape) == 1: return Vectors.dense(np_array) else: raise Exception("An MLLib Vector can only be created from a one-dimensional " + "numpy array, got {}".format(len(np_array.shape)))
python
def to_vector(np_array): """Convert numpy array to MLlib Vector """ if len(np_array.shape) == 1: return Vectors.dense(np_array) else: raise Exception("An MLLib Vector can only be created from a one-dimensional " + "numpy array, got {}".format(len(np_array.shape)))
[ "def", "to_vector", "(", "np_array", ")", ":", "if", "len", "(", "np_array", ".", "shape", ")", "==", "1", ":", "return", "Vectors", ".", "dense", "(", "np_array", ")", "else", ":", "raise", "Exception", "(", "\"An MLLib Vector can only be created from a one-d...
Convert numpy array to MLlib Vector
[ "Convert", "numpy", "array", "to", "MLlib", "Vector" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/mllib/adapter.py#L29-L36
train
214,920
maxpumperla/elephas
elephas/java/adapter.py
retrieve_keras_weights
def retrieve_keras_weights(java_model): """For a previously imported Keras model, after training it with DL4J Spark, we want to set the resulting weights back to the original Keras model. :param java_model: DL4J model (MultiLayerNetwork or ComputationGraph :return: list of numpy arrays in correct order for model.set_weights(...) of a corresponding Keras model """ weights = [] layers = java_model.getLayers() for layer in layers: params = layer.paramTable() keys = params.keySet() key_list = java_classes.ArrayList(keys) for key in key_list: weight = params.get(key) np_weight = np.squeeze(to_numpy(weight)) weights.append(np_weight) return weights
python
def retrieve_keras_weights(java_model): """For a previously imported Keras model, after training it with DL4J Spark, we want to set the resulting weights back to the original Keras model. :param java_model: DL4J model (MultiLayerNetwork or ComputationGraph :return: list of numpy arrays in correct order for model.set_weights(...) of a corresponding Keras model """ weights = [] layers = java_model.getLayers() for layer in layers: params = layer.paramTable() keys = params.keySet() key_list = java_classes.ArrayList(keys) for key in key_list: weight = params.get(key) np_weight = np.squeeze(to_numpy(weight)) weights.append(np_weight) return weights
[ "def", "retrieve_keras_weights", "(", "java_model", ")", ":", "weights", "=", "[", "]", "layers", "=", "java_model", ".", "getLayers", "(", ")", "for", "layer", "in", "layers", ":", "params", "=", "layer", ".", "paramTable", "(", ")", "keys", "=", "param...
For a previously imported Keras model, after training it with DL4J Spark, we want to set the resulting weights back to the original Keras model. :param java_model: DL4J model (MultiLayerNetwork or ComputationGraph :return: list of numpy arrays in correct order for model.set_weights(...) of a corresponding Keras model
[ "For", "a", "previously", "imported", "Keras", "model", "after", "training", "it", "with", "DL4J", "Spark", "we", "want", "to", "set", "the", "resulting", "weights", "back", "to", "the", "original", "Keras", "model", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/java/adapter.py#L35-L52
train
214,921
maxpumperla/elephas
elephas/ml_model.py
ElephasEstimator._fit
def _fit(self, df): """Private fit method of the Estimator, which trains the model. """ simple_rdd = df_to_simple_rdd(df, categorical=self.get_categorical_labels(), nb_classes=self.get_nb_classes(), features_col=self.getFeaturesCol(), label_col=self.getLabelCol()) simple_rdd = simple_rdd.repartition(self.get_num_workers()) keras_model = model_from_yaml(self.get_keras_model_config()) metrics = self.get_metrics() loss = self.get_loss() optimizer = get_optimizer(self.get_optimizer_config()) keras_model.compile(loss=loss, optimizer=optimizer, metrics=metrics) spark_model = SparkModel(model=keras_model, mode=self.get_mode(), frequency=self.get_frequency(), num_workers=self.get_num_workers()) spark_model.fit(simple_rdd, epochs=self.get_epochs(), batch_size=self.get_batch_size(), verbose=self.get_verbosity(), validation_split=self.get_validation_split()) model_weights = spark_model.master_network.get_weights() weights = simple_rdd.ctx.broadcast(model_weights) return ElephasTransformer(labelCol=self.getLabelCol(), outputCol='prediction', keras_model_config=spark_model.master_network.to_yaml(), weights=weights)
python
def _fit(self, df): """Private fit method of the Estimator, which trains the model. """ simple_rdd = df_to_simple_rdd(df, categorical=self.get_categorical_labels(), nb_classes=self.get_nb_classes(), features_col=self.getFeaturesCol(), label_col=self.getLabelCol()) simple_rdd = simple_rdd.repartition(self.get_num_workers()) keras_model = model_from_yaml(self.get_keras_model_config()) metrics = self.get_metrics() loss = self.get_loss() optimizer = get_optimizer(self.get_optimizer_config()) keras_model.compile(loss=loss, optimizer=optimizer, metrics=metrics) spark_model = SparkModel(model=keras_model, mode=self.get_mode(), frequency=self.get_frequency(), num_workers=self.get_num_workers()) spark_model.fit(simple_rdd, epochs=self.get_epochs(), batch_size=self.get_batch_size(), verbose=self.get_verbosity(), validation_split=self.get_validation_split()) model_weights = spark_model.master_network.get_weights() weights = simple_rdd.ctx.broadcast(model_weights) return ElephasTransformer(labelCol=self.getLabelCol(), outputCol='prediction', keras_model_config=spark_model.master_network.to_yaml(), weights=weights)
[ "def", "_fit", "(", "self", ",", "df", ")", ":", "simple_rdd", "=", "df_to_simple_rdd", "(", "df", ",", "categorical", "=", "self", ".", "get_categorical_labels", "(", ")", ",", "nb_classes", "=", "self", ".", "get_nb_classes", "(", ")", ",", "features_col...
Private fit method of the Estimator, which trains the model.
[ "Private", "fit", "method", "of", "the", "Estimator", "which", "trains", "the", "model", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml_model.py#L72-L99
train
214,922
maxpumperla/elephas
elephas/ml_model.py
ElephasTransformer._transform
def _transform(self, df): """Private transform method of a Transformer. This serves as batch-prediction method for our purposes. """ output_col = self.getOutputCol() label_col = self.getLabelCol() new_schema = copy.deepcopy(df.schema) new_schema.add(StructField(output_col, StringType(), True)) rdd = df.rdd.coalesce(1) features = np.asarray( rdd.map(lambda x: from_vector(x.features)).collect()) # Note that we collect, since executing this on the rdd would require model serialization once again model = model_from_yaml(self.get_keras_model_config()) model.set_weights(self.weights.value) predictions = rdd.ctx.parallelize( model.predict_classes(features)).coalesce(1) predictions = predictions.map(lambda x: tuple(str(x))) results_rdd = rdd.zip(predictions).map(lambda x: x[0] + x[1]) results_df = df.sql_ctx.createDataFrame(results_rdd, new_schema) results_df = results_df.withColumn( output_col, results_df[output_col].cast(DoubleType())) results_df = results_df.withColumn( label_col, results_df[label_col].cast(DoubleType())) return results_df
python
def _transform(self, df): """Private transform method of a Transformer. This serves as batch-prediction method for our purposes. """ output_col = self.getOutputCol() label_col = self.getLabelCol() new_schema = copy.deepcopy(df.schema) new_schema.add(StructField(output_col, StringType(), True)) rdd = df.rdd.coalesce(1) features = np.asarray( rdd.map(lambda x: from_vector(x.features)).collect()) # Note that we collect, since executing this on the rdd would require model serialization once again model = model_from_yaml(self.get_keras_model_config()) model.set_weights(self.weights.value) predictions = rdd.ctx.parallelize( model.predict_classes(features)).coalesce(1) predictions = predictions.map(lambda x: tuple(str(x))) results_rdd = rdd.zip(predictions).map(lambda x: x[0] + x[1]) results_df = df.sql_ctx.createDataFrame(results_rdd, new_schema) results_df = results_df.withColumn( output_col, results_df[output_col].cast(DoubleType())) results_df = results_df.withColumn( label_col, results_df[label_col].cast(DoubleType())) return results_df
[ "def", "_transform", "(", "self", ",", "df", ")", ":", "output_col", "=", "self", ".", "getOutputCol", "(", ")", "label_col", "=", "self", ".", "getLabelCol", "(", ")", "new_schema", "=", "copy", ".", "deepcopy", "(", "df", ".", "schema", ")", "new_sch...
Private transform method of a Transformer. This serves as batch-prediction method for our purposes.
[ "Private", "transform", "method", "of", "a", "Transformer", ".", "This", "serves", "as", "batch", "-", "prediction", "method", "for", "our", "purposes", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml_model.py#L146-L171
train
214,923
maxpumperla/elephas
elephas/java/ndarray.py
_from_numpy
def _from_numpy(np_array): """ Convert numpy array to nd4j array """ # Convert the numpy array to nd4j context dtype required_dtype = get_np_dtype(get_context_dtype()) if np_array.dtype != required_dtype: raise Exception("{} is required, got {}".format( repr(required_dtype), repr(np_array.dtype))) # Nd4j does not have 1-d vectors. # So we add a dummy dimension. if np_array.ndim == 1: np_array = np.expand_dims(np_array, 0) # We have to maintain references to all incoming # numpy arrays. Else they will get GCed # creates a Nd4j array from a numpy array # To create an Nd4j array, we need 3 things: # buffer, strides, and shape # Get the buffer # A buffer is basically an array. To get the buffer object # we need a pointer to the first element and the size. pointer_address, _ = np_array.__array_interface__['data'] _refs.append(np_array) pointer = native_ops.pointerForAddress(pointer_address) size = np_array.size mapping = { np.float64: DoublePointer, np.float32: FloatPointer, } pointer = mapping[required_dtype](pointer) buff = Nd4j.createBuffer(pointer, size) assert buff.address() == pointer_address _refs.append(buff) # Get the strides # strides = tuple of bytes to step in each # dimension when traversing an array. elem_size = buff.getElementSize() # Make sure word size is same in both python # and java worlds assert elem_size == np_array.dtype.itemsize strides = np_array.strides # numpy uses byte wise strides. We have to # convert it to word wise strides. strides = [dim / elem_size for dim in strides] # Finally, shape: shape = np_array.shape nd4j_array = Nd4j.create(buff, shape, strides, 0) assert buff.address() == nd4j_array.data().address() return nd4j_array
python
def _from_numpy(np_array): """ Convert numpy array to nd4j array """ # Convert the numpy array to nd4j context dtype required_dtype = get_np_dtype(get_context_dtype()) if np_array.dtype != required_dtype: raise Exception("{} is required, got {}".format( repr(required_dtype), repr(np_array.dtype))) # Nd4j does not have 1-d vectors. # So we add a dummy dimension. if np_array.ndim == 1: np_array = np.expand_dims(np_array, 0) # We have to maintain references to all incoming # numpy arrays. Else they will get GCed # creates a Nd4j array from a numpy array # To create an Nd4j array, we need 3 things: # buffer, strides, and shape # Get the buffer # A buffer is basically an array. To get the buffer object # we need a pointer to the first element and the size. pointer_address, _ = np_array.__array_interface__['data'] _refs.append(np_array) pointer = native_ops.pointerForAddress(pointer_address) size = np_array.size mapping = { np.float64: DoublePointer, np.float32: FloatPointer, } pointer = mapping[required_dtype](pointer) buff = Nd4j.createBuffer(pointer, size) assert buff.address() == pointer_address _refs.append(buff) # Get the strides # strides = tuple of bytes to step in each # dimension when traversing an array. elem_size = buff.getElementSize() # Make sure word size is same in both python # and java worlds assert elem_size == np_array.dtype.itemsize strides = np_array.strides # numpy uses byte wise strides. We have to # convert it to word wise strides. strides = [dim / elem_size for dim in strides] # Finally, shape: shape = np_array.shape nd4j_array = Nd4j.create(buff, shape, strides, 0) assert buff.address() == nd4j_array.data().address() return nd4j_array
[ "def", "_from_numpy", "(", "np_array", ")", ":", "# Convert the numpy array to nd4j context dtype", "required_dtype", "=", "get_np_dtype", "(", "get_context_dtype", "(", ")", ")", "if", "np_array", ".", "dtype", "!=", "required_dtype", ":", "raise", "Exception", "(", ...
Convert numpy array to nd4j array
[ "Convert", "numpy", "array", "to", "nd4j", "array" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/java/ndarray.py#L78-L133
train
214,924
maxpumperla/elephas
elephas/java/ndarray.py
_to_numpy
def _to_numpy(nd4j_array): """ Convert nd4j array to numpy array """ buff = nd4j_array.data() address = buff.pointer().address() dtype = get_context_dtype() mapping = { 'double': ctypes.c_double, 'float': ctypes.c_float } Pointer = ctypes.POINTER(mapping[dtype]) pointer = ctypes.cast(address, Pointer) np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape())) return np_array
python
def _to_numpy(nd4j_array): """ Convert nd4j array to numpy array """ buff = nd4j_array.data() address = buff.pointer().address() dtype = get_context_dtype() mapping = { 'double': ctypes.c_double, 'float': ctypes.c_float } Pointer = ctypes.POINTER(mapping[dtype]) pointer = ctypes.cast(address, Pointer) np_array = np.ctypeslib.as_array(pointer, tuple(nd4j_array.shape())) return np_array
[ "def", "_to_numpy", "(", "nd4j_array", ")", ":", "buff", "=", "nd4j_array", ".", "data", "(", ")", "address", "=", "buff", ".", "pointer", "(", ")", ".", "address", "(", ")", "dtype", "=", "get_context_dtype", "(", ")", "mapping", "=", "{", "'double'",...
Convert nd4j array to numpy array
[ "Convert", "nd4j", "array", "to", "numpy", "array" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/java/ndarray.py#L136-L150
train
214,925
maxpumperla/elephas
elephas/utils/rwlock.py
RWLock.acquire_read
def acquire_read(self): """ Acquire a read lock. Several threads can hold this typeof lock. It is exclusive with write locks. """ self.monitor.acquire() while self.rwlock < 0 or self.writers_waiting: self.readers_ok.wait() self.rwlock += 1 self.monitor.release()
python
def acquire_read(self): """ Acquire a read lock. Several threads can hold this typeof lock. It is exclusive with write locks. """ self.monitor.acquire() while self.rwlock < 0 or self.writers_waiting: self.readers_ok.wait() self.rwlock += 1 self.monitor.release()
[ "def", "acquire_read", "(", "self", ")", ":", "self", ".", "monitor", ".", "acquire", "(", ")", "while", "self", ".", "rwlock", "<", "0", "or", "self", ".", "writers_waiting", ":", "self", ".", "readers_ok", ".", "wait", "(", ")", "self", ".", "rwloc...
Acquire a read lock. Several threads can hold this typeof lock. It is exclusive with write locks.
[ "Acquire", "a", "read", "lock", ".", "Several", "threads", "can", "hold", "this", "typeof", "lock", ".", "It", "is", "exclusive", "with", "write", "locks", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rwlock.py#L25-L34
train
214,926
maxpumperla/elephas
elephas/utils/rwlock.py
RWLock.acquire_write
def acquire_write(self): """ Acquire a write lock. Only one thread can hold this lock, and only when no read locks are also held. """ self.monitor.acquire() while self.rwlock != 0: self.writers_waiting += 1 self.writers_ok.wait() self.writers_waiting -= 1 self.rwlock = -1 self.monitor.release()
python
def acquire_write(self): """ Acquire a write lock. Only one thread can hold this lock, and only when no read locks are also held. """ self.monitor.acquire() while self.rwlock != 0: self.writers_waiting += 1 self.writers_ok.wait() self.writers_waiting -= 1 self.rwlock = -1 self.monitor.release()
[ "def", "acquire_write", "(", "self", ")", ":", "self", ".", "monitor", ".", "acquire", "(", ")", "while", "self", ".", "rwlock", "!=", "0", ":", "self", ".", "writers_waiting", "+=", "1", "self", ".", "writers_ok", ".", "wait", "(", ")", "self", ".",...
Acquire a write lock. Only one thread can hold this lock, and only when no read locks are also held.
[ "Acquire", "a", "write", "lock", ".", "Only", "one", "thread", "can", "hold", "this", "lock", "and", "only", "when", "no", "read", "locks", "are", "also", "held", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rwlock.py#L36-L47
train
214,927
maxpumperla/elephas
elephas/utils/rwlock.py
RWLock.release
def release(self): """ Release a lock, whether read or write. """ self.monitor.acquire() if self.rwlock < 0: self.rwlock = 0 else: self.rwlock -= 1 wake_writers = self.writers_waiting and self.rwlock == 0 wake_readers = self.writers_waiting == 0 self.monitor.release() if wake_writers: self.writers_ok.acquire() self.writers_ok.notify() self.writers_ok.release() elif wake_readers: self.readers_ok.acquire() self.readers_ok.notifyAll() self.readers_ok.release()
python
def release(self): """ Release a lock, whether read or write. """ self.monitor.acquire() if self.rwlock < 0: self.rwlock = 0 else: self.rwlock -= 1 wake_writers = self.writers_waiting and self.rwlock == 0 wake_readers = self.writers_waiting == 0 self.monitor.release() if wake_writers: self.writers_ok.acquire() self.writers_ok.notify() self.writers_ok.release() elif wake_readers: self.readers_ok.acquire() self.readers_ok.notifyAll() self.readers_ok.release()
[ "def", "release", "(", "self", ")", ":", "self", ".", "monitor", ".", "acquire", "(", ")", "if", "self", ".", "rwlock", "<", "0", ":", "self", ".", "rwlock", "=", "0", "else", ":", "self", ".", "rwlock", "-=", "1", "wake_writers", "=", "self", "....
Release a lock, whether read or write.
[ "Release", "a", "lock", "whether", "read", "or", "write", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rwlock.py#L49-L68
train
214,928
maxpumperla/elephas
elephas/ml/adapter.py
to_data_frame
def to_data_frame(sc, features, labels, categorical=False): """Convert numpy arrays of features and labels into Spark DataFrame """ lp_rdd = to_labeled_point(sc, features, labels, categorical) sql_context = SQLContext(sc) df = sql_context.createDataFrame(lp_rdd) return df
python
def to_data_frame(sc, features, labels, categorical=False): """Convert numpy arrays of features and labels into Spark DataFrame """ lp_rdd = to_labeled_point(sc, features, labels, categorical) sql_context = SQLContext(sc) df = sql_context.createDataFrame(lp_rdd) return df
[ "def", "to_data_frame", "(", "sc", ",", "features", ",", "labels", ",", "categorical", "=", "False", ")", ":", "lp_rdd", "=", "to_labeled_point", "(", "sc", ",", "features", ",", "labels", ",", "categorical", ")", "sql_context", "=", "SQLContext", "(", "sc...
Convert numpy arrays of features and labels into Spark DataFrame
[ "Convert", "numpy", "arrays", "of", "features", "and", "labels", "into", "Spark", "DataFrame" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml/adapter.py#L9-L15
train
214,929
maxpumperla/elephas
elephas/ml/adapter.py
from_data_frame
def from_data_frame(df, categorical=False, nb_classes=None): """Convert DataFrame back to pair of numpy arrays """ lp_rdd = df.rdd.map(lambda row: LabeledPoint(row.label, row.features)) features, labels = from_labeled_point(lp_rdd, categorical, nb_classes) return features, labels
python
def from_data_frame(df, categorical=False, nb_classes=None): """Convert DataFrame back to pair of numpy arrays """ lp_rdd = df.rdd.map(lambda row: LabeledPoint(row.label, row.features)) features, labels = from_labeled_point(lp_rdd, categorical, nb_classes) return features, labels
[ "def", "from_data_frame", "(", "df", ",", "categorical", "=", "False", ",", "nb_classes", "=", "None", ")", ":", "lp_rdd", "=", "df", ".", "rdd", ".", "map", "(", "lambda", "row", ":", "LabeledPoint", "(", "row", ".", "label", ",", "row", ".", "featu...
Convert DataFrame back to pair of numpy arrays
[ "Convert", "DataFrame", "back", "to", "pair", "of", "numpy", "arrays" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml/adapter.py#L18-L23
train
214,930
maxpumperla/elephas
elephas/ml/adapter.py
df_to_simple_rdd
def df_to_simple_rdd(df, categorical=False, nb_classes=None, features_col='features', label_col='label'): """Convert DataFrame into RDD of pairs """ sql_context = df.sql_ctx sql_context.registerDataFrameAsTable(df, "temp_table") selected_df = sql_context.sql( "SELECT {0} AS features, {1} as label from temp_table".format(features_col, label_col)) if isinstance(selected_df.first().features, MLLibVector): lp_rdd = selected_df.rdd.map( lambda row: LabeledPoint(row.label, row.features)) else: lp_rdd = selected_df.rdd.map(lambda row: LabeledPoint( row.label, MLLibVectors.fromML(row.features))) rdd = lp_to_simple_rdd(lp_rdd, categorical, nb_classes) return rdd
python
def df_to_simple_rdd(df, categorical=False, nb_classes=None, features_col='features', label_col='label'): """Convert DataFrame into RDD of pairs """ sql_context = df.sql_ctx sql_context.registerDataFrameAsTable(df, "temp_table") selected_df = sql_context.sql( "SELECT {0} AS features, {1} as label from temp_table".format(features_col, label_col)) if isinstance(selected_df.first().features, MLLibVector): lp_rdd = selected_df.rdd.map( lambda row: LabeledPoint(row.label, row.features)) else: lp_rdd = selected_df.rdd.map(lambda row: LabeledPoint( row.label, MLLibVectors.fromML(row.features))) rdd = lp_to_simple_rdd(lp_rdd, categorical, nb_classes) return rdd
[ "def", "df_to_simple_rdd", "(", "df", ",", "categorical", "=", "False", ",", "nb_classes", "=", "None", ",", "features_col", "=", "'features'", ",", "label_col", "=", "'label'", ")", ":", "sql_context", "=", "df", ".", "sql_ctx", "sql_context", ".", "registe...
Convert DataFrame into RDD of pairs
[ "Convert", "DataFrame", "into", "RDD", "of", "pairs" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/ml/adapter.py#L26-L40
train
214,931
maxpumperla/elephas
elephas/spark_model.py
SparkModel.fit
def fit(self, rdd, epochs=10, batch_size=32, verbose=0, validation_split=0.1): """ Train an elephas model on an RDD. The Keras model configuration as specified in the elephas model is sent to Spark workers, abd each worker will be trained on their data partition. :param rdd: RDD with features and labels :param epochs: number of epochs used for training :param batch_size: batch size used for training :param verbose: logging verbosity level (0, 1 or 2) :param validation_split: percentage of data set aside for validation """ print('>>> Fit model') if self.num_workers: rdd = rdd.repartition(self.num_workers) if self.mode in ['asynchronous', 'synchronous', 'hogwild']: self._fit(rdd, epochs, batch_size, verbose, validation_split) else: raise ValueError( "Choose from one of the modes: asynchronous, synchronous or hogwild")
python
def fit(self, rdd, epochs=10, batch_size=32, verbose=0, validation_split=0.1): """ Train an elephas model on an RDD. The Keras model configuration as specified in the elephas model is sent to Spark workers, abd each worker will be trained on their data partition. :param rdd: RDD with features and labels :param epochs: number of epochs used for training :param batch_size: batch size used for training :param verbose: logging verbosity level (0, 1 or 2) :param validation_split: percentage of data set aside for validation """ print('>>> Fit model') if self.num_workers: rdd = rdd.repartition(self.num_workers) if self.mode in ['asynchronous', 'synchronous', 'hogwild']: self._fit(rdd, epochs, batch_size, verbose, validation_split) else: raise ValueError( "Choose from one of the modes: asynchronous, synchronous or hogwild")
[ "def", "fit", "(", "self", ",", "rdd", ",", "epochs", "=", "10", ",", "batch_size", "=", "32", ",", "verbose", "=", "0", ",", "validation_split", "=", "0.1", ")", ":", "print", "(", "'>>> Fit model'", ")", "if", "self", ".", "num_workers", ":", "rdd"...
Train an elephas model on an RDD. The Keras model configuration as specified in the elephas model is sent to Spark workers, abd each worker will be trained on their data partition. :param rdd: RDD with features and labels :param epochs: number of epochs used for training :param batch_size: batch size used for training :param verbose: logging verbosity level (0, 1 or 2) :param validation_split: percentage of data set aside for validation
[ "Train", "an", "elephas", "model", "on", "an", "RDD", ".", "The", "Keras", "model", "configuration", "as", "specified", "in", "the", "elephas", "model", "is", "sent", "to", "Spark", "workers", "abd", "each", "worker", "will", "be", "trained", "on", "their"...
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L133-L154
train
214,932
maxpumperla/elephas
elephas/spark_model.py
SparkModel._fit
def _fit(self, rdd, epochs, batch_size, verbose, validation_split): """Protected train method to make wrapping of modes easier """ self._master_network.compile(optimizer=self.master_optimizer, loss=self.master_loss, metrics=self.master_metrics) if self.mode in ['asynchronous', 'hogwild']: self.start_server() train_config = self.get_train_config( epochs, batch_size, verbose, validation_split) mode = self.parameter_server_mode freq = self.frequency optimizer = self.master_optimizer loss = self.master_loss metrics = self.master_metrics custom = self.custom_objects yaml = self._master_network.to_yaml() init = self._master_network.get_weights() parameters = rdd.context.broadcast(init) if self.mode in ['asynchronous', 'hogwild']: print('>>> Initialize workers') worker = AsynchronousSparkWorker( yaml, parameters, mode, train_config, freq, optimizer, loss, metrics, custom) print('>>> Distribute load') rdd.mapPartitions(worker.train).collect() print('>>> Async training complete.') new_parameters = self.client.get_parameters() elif self.mode == 'synchronous': worker = SparkWorker(yaml, parameters, train_config, optimizer, loss, metrics, custom) gradients = rdd.mapPartitions(worker.train).collect() new_parameters = self._master_network.get_weights() for grad in gradients: # simply accumulate gradients one by one new_parameters = subtract_params(new_parameters, grad) print('>>> Synchronous training complete.') else: raise ValueError("Unsupported mode {}".format(self.mode)) self._master_network.set_weights(new_parameters) if self.mode in ['asynchronous', 'hogwild']: self.stop_server()
python
def _fit(self, rdd, epochs, batch_size, verbose, validation_split): """Protected train method to make wrapping of modes easier """ self._master_network.compile(optimizer=self.master_optimizer, loss=self.master_loss, metrics=self.master_metrics) if self.mode in ['asynchronous', 'hogwild']: self.start_server() train_config = self.get_train_config( epochs, batch_size, verbose, validation_split) mode = self.parameter_server_mode freq = self.frequency optimizer = self.master_optimizer loss = self.master_loss metrics = self.master_metrics custom = self.custom_objects yaml = self._master_network.to_yaml() init = self._master_network.get_weights() parameters = rdd.context.broadcast(init) if self.mode in ['asynchronous', 'hogwild']: print('>>> Initialize workers') worker = AsynchronousSparkWorker( yaml, parameters, mode, train_config, freq, optimizer, loss, metrics, custom) print('>>> Distribute load') rdd.mapPartitions(worker.train).collect() print('>>> Async training complete.') new_parameters = self.client.get_parameters() elif self.mode == 'synchronous': worker = SparkWorker(yaml, parameters, train_config, optimizer, loss, metrics, custom) gradients = rdd.mapPartitions(worker.train).collect() new_parameters = self._master_network.get_weights() for grad in gradients: # simply accumulate gradients one by one new_parameters = subtract_params(new_parameters, grad) print('>>> Synchronous training complete.') else: raise ValueError("Unsupported mode {}".format(self.mode)) self._master_network.set_weights(new_parameters) if self.mode in ['asynchronous', 'hogwild']: self.stop_server()
[ "def", "_fit", "(", "self", ",", "rdd", ",", "epochs", ",", "batch_size", ",", "verbose", ",", "validation_split", ")", ":", "self", ".", "_master_network", ".", "compile", "(", "optimizer", "=", "self", ".", "master_optimizer", ",", "loss", "=", "self", ...
Protected train method to make wrapping of modes easier
[ "Protected", "train", "method", "to", "make", "wrapping", "of", "modes", "easier" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L156-L197
train
214,933
maxpumperla/elephas
elephas/spark_model.py
SparkMLlibModel.fit
def fit(self, labeled_points, epochs=10, batch_size=32, verbose=0, validation_split=0.1, categorical=False, nb_classes=None): """Train an elephas model on an RDD of LabeledPoints """ rdd = lp_to_simple_rdd(labeled_points, categorical, nb_classes) rdd = rdd.repartition(self.num_workers) self._fit(rdd=rdd, epochs=epochs, batch_size=batch_size, verbose=verbose, validation_split=validation_split)
python
def fit(self, labeled_points, epochs=10, batch_size=32, verbose=0, validation_split=0.1, categorical=False, nb_classes=None): """Train an elephas model on an RDD of LabeledPoints """ rdd = lp_to_simple_rdd(labeled_points, categorical, nb_classes) rdd = rdd.repartition(self.num_workers) self._fit(rdd=rdd, epochs=epochs, batch_size=batch_size, verbose=verbose, validation_split=validation_split)
[ "def", "fit", "(", "self", ",", "labeled_points", ",", "epochs", "=", "10", ",", "batch_size", "=", "32", ",", "verbose", "=", "0", ",", "validation_split", "=", "0.1", ",", "categorical", "=", "False", ",", "nb_classes", "=", "None", ")", ":", "rdd", ...
Train an elephas model on an RDD of LabeledPoints
[ "Train", "an", "elephas", "model", "on", "an", "RDD", "of", "LabeledPoints" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L235-L242
train
214,934
maxpumperla/elephas
elephas/spark_model.py
SparkMLlibModel.predict
def predict(self, mllib_data): """Predict probabilities for an RDD of features """ if isinstance(mllib_data, pyspark.mllib.linalg.Matrix): return to_matrix(self._master_network.predict(from_matrix(mllib_data))) elif isinstance(mllib_data, pyspark.mllib.linalg.Vector): return to_vector(self._master_network.predict(from_vector(mllib_data))) else: raise ValueError( 'Provide either an MLLib matrix or vector, got {}'.format(mllib_data.__name__))
python
def predict(self, mllib_data): """Predict probabilities for an RDD of features """ if isinstance(mllib_data, pyspark.mllib.linalg.Matrix): return to_matrix(self._master_network.predict(from_matrix(mllib_data))) elif isinstance(mllib_data, pyspark.mllib.linalg.Vector): return to_vector(self._master_network.predict(from_vector(mllib_data))) else: raise ValueError( 'Provide either an MLLib matrix or vector, got {}'.format(mllib_data.__name__))
[ "def", "predict", "(", "self", ",", "mllib_data", ")", ":", "if", "isinstance", "(", "mllib_data", ",", "pyspark", ".", "mllib", ".", "linalg", ".", "Matrix", ")", ":", "return", "to_matrix", "(", "self", ".", "_master_network", ".", "predict", "(", "fro...
Predict probabilities for an RDD of features
[ "Predict", "probabilities", "for", "an", "RDD", "of", "features" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/spark_model.py#L244-L253
train
214,935
maxpumperla/elephas
elephas/worker.py
SparkWorker.train
def train(self, data_iterator): """Train a keras model on a worker """ optimizer = get_optimizer(self.master_optimizer) self.model = model_from_yaml(self.yaml, self.custom_objects) self.model.compile(optimizer=optimizer, loss=self.master_loss, metrics=self.master_metrics) self.model.set_weights(self.parameters.value) feature_iterator, label_iterator = tee(data_iterator, 2) x_train = np.asarray([x for x, y in feature_iterator]) y_train = np.asarray([y for x, y in label_iterator]) self.model.compile(optimizer=self.master_optimizer, loss=self.master_loss, metrics=self.master_metrics) weights_before_training = self.model.get_weights() if x_train.shape[0] > self.train_config.get('batch_size'): self.model.fit(x_train, y_train, **self.train_config) weights_after_training = self.model.get_weights() deltas = subtract_params( weights_before_training, weights_after_training) yield deltas
python
def train(self, data_iterator): """Train a keras model on a worker """ optimizer = get_optimizer(self.master_optimizer) self.model = model_from_yaml(self.yaml, self.custom_objects) self.model.compile(optimizer=optimizer, loss=self.master_loss, metrics=self.master_metrics) self.model.set_weights(self.parameters.value) feature_iterator, label_iterator = tee(data_iterator, 2) x_train = np.asarray([x for x, y in feature_iterator]) y_train = np.asarray([y for x, y in label_iterator]) self.model.compile(optimizer=self.master_optimizer, loss=self.master_loss, metrics=self.master_metrics) weights_before_training = self.model.get_weights() if x_train.shape[0] > self.train_config.get('batch_size'): self.model.fit(x_train, y_train, **self.train_config) weights_after_training = self.model.get_weights() deltas = subtract_params( weights_before_training, weights_after_training) yield deltas
[ "def", "train", "(", "self", ",", "data_iterator", ")", ":", "optimizer", "=", "get_optimizer", "(", "self", ".", "master_optimizer", ")", "self", ".", "model", "=", "model_from_yaml", "(", "self", ".", "yaml", ",", "self", ".", "custom_objects", ")", "sel...
Train a keras model on a worker
[ "Train", "a", "keras", "model", "on", "a", "worker" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/worker.py#L26-L49
train
214,936
maxpumperla/elephas
elephas/worker.py
AsynchronousSparkWorker.train
def train(self, data_iterator): """Train a keras model on a worker and send asynchronous updates to parameter server """ feature_iterator, label_iterator = tee(data_iterator, 2) x_train = np.asarray([x for x, y in feature_iterator]) y_train = np.asarray([y for x, y in label_iterator]) if x_train.size == 0: return optimizer = get_optimizer(self.master_optimizer) self.model = model_from_yaml(self.yaml, self.custom_objects) self.model.compile(optimizer=optimizer, loss=self.master_loss, metrics=self.master_metrics) self.model.set_weights(self.parameters.value) epochs = self.train_config['epochs'] batch_size = self.train_config.get('batch_size') nb_train_sample = x_train.shape[0] nb_batch = int(np.ceil(nb_train_sample / float(batch_size))) index_array = np.arange(nb_train_sample) batches = [ (i * batch_size, min(nb_train_sample, (i + 1) * batch_size)) for i in range(0, nb_batch) ] if self.frequency == 'epoch': for epoch in range(epochs): weights_before_training = self.client.get_parameters() self.model.set_weights(weights_before_training) self.train_config['epochs'] = 1 if x_train.shape[0] > batch_size: self.model.fit(x_train, y_train, **self.train_config) self.train_config['epochs'] = epochs weights_after_training = self.model.get_weights() deltas = subtract_params( weights_before_training, weights_after_training) self.client.update_parameters(deltas) elif self.frequency == 'batch': for epoch in range(epochs): if x_train.shape[0] > batch_size: for (batch_start, batch_end) in batches: weights_before_training = self.client.get_parameters() self.model.set_weights(weights_before_training) batch_ids = index_array[batch_start:batch_end] x = slice_arrays(x_train, batch_ids) y = slice_arrays(y_train, batch_ids) self.model.train_on_batch(x, y) weights_after_training = self.model.get_weights() deltas = subtract_params( weights_before_training, weights_after_training) self.client.update_parameters(deltas) else: raise ValueError( 'frequency parameter can be `epoch` or `batch, got {}'.format(self.frequency)) yield []
python
def train(self, data_iterator): """Train a keras model on a worker and send asynchronous updates to parameter server """ feature_iterator, label_iterator = tee(data_iterator, 2) x_train = np.asarray([x for x, y in feature_iterator]) y_train = np.asarray([y for x, y in label_iterator]) if x_train.size == 0: return optimizer = get_optimizer(self.master_optimizer) self.model = model_from_yaml(self.yaml, self.custom_objects) self.model.compile(optimizer=optimizer, loss=self.master_loss, metrics=self.master_metrics) self.model.set_weights(self.parameters.value) epochs = self.train_config['epochs'] batch_size = self.train_config.get('batch_size') nb_train_sample = x_train.shape[0] nb_batch = int(np.ceil(nb_train_sample / float(batch_size))) index_array = np.arange(nb_train_sample) batches = [ (i * batch_size, min(nb_train_sample, (i + 1) * batch_size)) for i in range(0, nb_batch) ] if self.frequency == 'epoch': for epoch in range(epochs): weights_before_training = self.client.get_parameters() self.model.set_weights(weights_before_training) self.train_config['epochs'] = 1 if x_train.shape[0] > batch_size: self.model.fit(x_train, y_train, **self.train_config) self.train_config['epochs'] = epochs weights_after_training = self.model.get_weights() deltas = subtract_params( weights_before_training, weights_after_training) self.client.update_parameters(deltas) elif self.frequency == 'batch': for epoch in range(epochs): if x_train.shape[0] > batch_size: for (batch_start, batch_end) in batches: weights_before_training = self.client.get_parameters() self.model.set_weights(weights_before_training) batch_ids = index_array[batch_start:batch_end] x = slice_arrays(x_train, batch_ids) y = slice_arrays(y_train, batch_ids) self.model.train_on_batch(x, y) weights_after_training = self.model.get_weights() deltas = subtract_params( weights_before_training, weights_after_training) self.client.update_parameters(deltas) else: raise ValueError( 'frequency parameter can be `epoch` or `batch, got {}'.format(self.frequency)) yield []
[ "def", "train", "(", "self", ",", "data_iterator", ")", ":", "feature_iterator", ",", "label_iterator", "=", "tee", "(", "data_iterator", ",", "2", ")", "x_train", "=", "np", ".", "asarray", "(", "[", "x", "for", "x", ",", "y", "in", "feature_iterator", ...
Train a keras model on a worker and send asynchronous updates to parameter server
[ "Train", "a", "keras", "model", "on", "a", "worker", "and", "send", "asynchronous", "updates", "to", "parameter", "server" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/worker.py#L77-L133
train
214,937
maxpumperla/elephas
elephas/utils/sockets.py
determine_master
def determine_master(port=4000): """Determine address of master so that workers can connect to it. If the environment variable SPARK_LOCAL_IP is set, that address will be used. :param port: port on which the application runs :return: Master address Example usage: SPARK_LOCAL_IP=127.0.0.1 spark-submit --master \ local[8] examples/mllib_mlp.py """ if os.environ.get('SPARK_LOCAL_IP'): return os.environ['SPARK_LOCAL_IP'] + ":" + str(port) else: return gethostbyname(gethostname()) + ":" + str(port)
python
def determine_master(port=4000): """Determine address of master so that workers can connect to it. If the environment variable SPARK_LOCAL_IP is set, that address will be used. :param port: port on which the application runs :return: Master address Example usage: SPARK_LOCAL_IP=127.0.0.1 spark-submit --master \ local[8] examples/mllib_mlp.py """ if os.environ.get('SPARK_LOCAL_IP'): return os.environ['SPARK_LOCAL_IP'] + ":" + str(port) else: return gethostbyname(gethostname()) + ":" + str(port)
[ "def", "determine_master", "(", "port", "=", "4000", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'SPARK_LOCAL_IP'", ")", ":", "return", "os", ".", "environ", "[", "'SPARK_LOCAL_IP'", "]", "+", "\":\"", "+", "str", "(", "port", ")", "else", ...
Determine address of master so that workers can connect to it. If the environment variable SPARK_LOCAL_IP is set, that address will be used. :param port: port on which the application runs :return: Master address Example usage: SPARK_LOCAL_IP=127.0.0.1 spark-submit --master \ local[8] examples/mllib_mlp.py
[ "Determine", "address", "of", "master", "so", "that", "workers", "can", "connect", "to", "it", ".", "If", "the", "environment", "variable", "SPARK_LOCAL_IP", "is", "set", "that", "address", "will", "be", "used", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/sockets.py#L6-L21
train
214,938
maxpumperla/elephas
elephas/utils/sockets.py
_receive_all
def _receive_all(socket, num_bytes): """Reads `num_bytes` bytes from the specified socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data """ buffer = '' buffer_size = 0 bytes_left = num_bytes while buffer_size < num_bytes: data = socket.recv(bytes_left) delta = len(data) buffer_size += delta bytes_left -= delta buffer += data return buffer
python
def _receive_all(socket, num_bytes): """Reads `num_bytes` bytes from the specified socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data """ buffer = '' buffer_size = 0 bytes_left = num_bytes while buffer_size < num_bytes: data = socket.recv(bytes_left) delta = len(data) buffer_size += delta bytes_left -= delta buffer += data return buffer
[ "def", "_receive_all", "(", "socket", ",", "num_bytes", ")", ":", "buffer", "=", "''", "buffer_size", "=", "0", "bytes_left", "=", "num_bytes", "while", "buffer_size", "<", "num_bytes", ":", "data", "=", "socket", ".", "recv", "(", "bytes_left", ")", "delt...
Reads `num_bytes` bytes from the specified socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data
[ "Reads", "num_bytes", "bytes", "from", "the", "specified", "socket", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/sockets.py#L24-L42
train
214,939
maxpumperla/elephas
elephas/utils/sockets.py
receive
def receive(socket, num_bytes=20): """Receive data frame from open socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data """ length = int(_receive_all(socket, num_bytes).decode()) serialized_data = _receive_all(socket, length) return pickle.loads(serialized_data)
python
def receive(socket, num_bytes=20): """Receive data frame from open socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data """ length = int(_receive_all(socket, num_bytes).decode()) serialized_data = _receive_all(socket, length) return pickle.loads(serialized_data)
[ "def", "receive", "(", "socket", ",", "num_bytes", "=", "20", ")", ":", "length", "=", "int", "(", "_receive_all", "(", "socket", ",", "num_bytes", ")", ".", "decode", "(", ")", ")", "serialized_data", "=", "_receive_all", "(", "socket", ",", "length", ...
Receive data frame from open socket. :param socket: open socket instance :param num_bytes: number of bytes to read :return: received data
[ "Receive", "data", "frame", "from", "open", "socket", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/sockets.py#L45-L55
train
214,940
maxpumperla/elephas
elephas/utils/sockets.py
send
def send(socket, data, num_bytes=20): """Send data to specified socket. :param socket: open socket instance :param data: data to send :param num_bytes: number of bytes to read :return: received data """ pickled_data = pickle.dumps(data, -1) length = str(len(pickled_data)).zfill(num_bytes) socket.sendall(length.encode()) socket.sendall(pickled_data)
python
def send(socket, data, num_bytes=20): """Send data to specified socket. :param socket: open socket instance :param data: data to send :param num_bytes: number of bytes to read :return: received data """ pickled_data = pickle.dumps(data, -1) length = str(len(pickled_data)).zfill(num_bytes) socket.sendall(length.encode()) socket.sendall(pickled_data)
[ "def", "send", "(", "socket", ",", "data", ",", "num_bytes", "=", "20", ")", ":", "pickled_data", "=", "pickle", ".", "dumps", "(", "data", ",", "-", "1", ")", "length", "=", "str", "(", "len", "(", "pickled_data", ")", ")", ".", "zfill", "(", "n...
Send data to specified socket. :param socket: open socket instance :param data: data to send :param num_bytes: number of bytes to read :return: received data
[ "Send", "data", "to", "specified", "socket", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/sockets.py#L58-L71
train
214,941
maxpumperla/elephas
elephas/utils/rdd_utils.py
to_java_rdd
def to_java_rdd(jsc, features, labels, batch_size): """Convert numpy features and labels into a JavaRDD of DL4J DataSet type. :param jsc: JavaSparkContext from pyjnius :param features: numpy array with features :param labels: numpy array with labels: :return: JavaRDD<DataSet> """ data_sets = java_classes.ArrayList() num_batches = int(len(features) / batch_size) for i in range(num_batches): xi = ndarray(features[:batch_size].copy()) yi = ndarray(labels[:batch_size].copy()) data_set = java_classes.DataSet(xi.array, yi.array) data_sets.add(data_set) features = features[batch_size:] labels = labels[batch_size:] return jsc.parallelize(data_sets)
python
def to_java_rdd(jsc, features, labels, batch_size): """Convert numpy features and labels into a JavaRDD of DL4J DataSet type. :param jsc: JavaSparkContext from pyjnius :param features: numpy array with features :param labels: numpy array with labels: :return: JavaRDD<DataSet> """ data_sets = java_classes.ArrayList() num_batches = int(len(features) / batch_size) for i in range(num_batches): xi = ndarray(features[:batch_size].copy()) yi = ndarray(labels[:batch_size].copy()) data_set = java_classes.DataSet(xi.array, yi.array) data_sets.add(data_set) features = features[batch_size:] labels = labels[batch_size:] return jsc.parallelize(data_sets)
[ "def", "to_java_rdd", "(", "jsc", ",", "features", ",", "labels", ",", "batch_size", ")", ":", "data_sets", "=", "java_classes", ".", "ArrayList", "(", ")", "num_batches", "=", "int", "(", "len", "(", "features", ")", "/", "batch_size", ")", "for", "i", ...
Convert numpy features and labels into a JavaRDD of DL4J DataSet type. :param jsc: JavaSparkContext from pyjnius :param features: numpy array with features :param labels: numpy array with labels: :return: JavaRDD<DataSet>
[ "Convert", "numpy", "features", "and", "labels", "into", "a", "JavaRDD", "of", "DL4J", "DataSet", "type", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L16-L35
train
214,942
maxpumperla/elephas
elephas/utils/rdd_utils.py
to_simple_rdd
def to_simple_rdd(sc, features, labels): """Convert numpy arrays of features and labels into an RDD of pairs. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :return: Spark RDD with feature-label pairs """ pairs = [(x, y) for x, y in zip(features, labels)] return sc.parallelize(pairs)
python
def to_simple_rdd(sc, features, labels): """Convert numpy arrays of features and labels into an RDD of pairs. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :return: Spark RDD with feature-label pairs """ pairs = [(x, y) for x, y in zip(features, labels)] return sc.parallelize(pairs)
[ "def", "to_simple_rdd", "(", "sc", ",", "features", ",", "labels", ")", ":", "pairs", "=", "[", "(", "x", ",", "y", ")", "for", "x", ",", "y", "in", "zip", "(", "features", ",", "labels", ")", "]", "return", "sc", ".", "parallelize", "(", "pairs"...
Convert numpy arrays of features and labels into an RDD of pairs. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :return: Spark RDD with feature-label pairs
[ "Convert", "numpy", "arrays", "of", "features", "and", "labels", "into", "an", "RDD", "of", "pairs", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L38-L48
train
214,943
maxpumperla/elephas
elephas/utils/rdd_utils.py
to_labeled_point
def to_labeled_point(sc, features, labels, categorical=False): """Convert numpy arrays of features and labels into a LabeledPoint RDD for MLlib and ML integration. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :param categorical: boolean, whether labels are already one-hot encoded or not :return: LabeledPoint RDD with features and labels """ labeled_points = [] for x, y in zip(features, labels): if categorical: lp = LabeledPoint(np.argmax(y), to_vector(x)) else: lp = LabeledPoint(y, to_vector(x)) labeled_points.append(lp) return sc.parallelize(labeled_points)
python
def to_labeled_point(sc, features, labels, categorical=False): """Convert numpy arrays of features and labels into a LabeledPoint RDD for MLlib and ML integration. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :param categorical: boolean, whether labels are already one-hot encoded or not :return: LabeledPoint RDD with features and labels """ labeled_points = [] for x, y in zip(features, labels): if categorical: lp = LabeledPoint(np.argmax(y), to_vector(x)) else: lp = LabeledPoint(y, to_vector(x)) labeled_points.append(lp) return sc.parallelize(labeled_points)
[ "def", "to_labeled_point", "(", "sc", ",", "features", ",", "labels", ",", "categorical", "=", "False", ")", ":", "labeled_points", "=", "[", "]", "for", "x", ",", "y", "in", "zip", "(", "features", ",", "labels", ")", ":", "if", "categorical", ":", ...
Convert numpy arrays of features and labels into a LabeledPoint RDD for MLlib and ML integration. :param sc: Spark context :param features: numpy array with features :param labels: numpy array with labels :param categorical: boolean, whether labels are already one-hot encoded or not :return: LabeledPoint RDD with features and labels
[ "Convert", "numpy", "arrays", "of", "features", "and", "labels", "into", "a", "LabeledPoint", "RDD", "for", "MLlib", "and", "ML", "integration", "." ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L51-L68
train
214,944
maxpumperla/elephas
elephas/utils/rdd_utils.py
from_labeled_point
def from_labeled_point(rdd, categorical=False, nb_classes=None): """Convert a LabeledPoint RDD back to a pair of numpy arrays :param rdd: LabeledPoint RDD :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: optional int, indicating the number of class labels :return: pair of numpy arrays, features and labels """ features = np.asarray( rdd.map(lambda lp: from_vector(lp.features)).collect()) labels = np.asarray(rdd.map(lambda lp: lp.label).collect(), dtype='int32') if categorical: if not nb_classes: nb_classes = np.max(labels) + 1 temp = np.zeros((len(labels), nb_classes)) for i, label in enumerate(labels): temp[i, label] = 1. labels = temp return features, labels
python
def from_labeled_point(rdd, categorical=False, nb_classes=None): """Convert a LabeledPoint RDD back to a pair of numpy arrays :param rdd: LabeledPoint RDD :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: optional int, indicating the number of class labels :return: pair of numpy arrays, features and labels """ features = np.asarray( rdd.map(lambda lp: from_vector(lp.features)).collect()) labels = np.asarray(rdd.map(lambda lp: lp.label).collect(), dtype='int32') if categorical: if not nb_classes: nb_classes = np.max(labels) + 1 temp = np.zeros((len(labels), nb_classes)) for i, label in enumerate(labels): temp[i, label] = 1. labels = temp return features, labels
[ "def", "from_labeled_point", "(", "rdd", ",", "categorical", "=", "False", ",", "nb_classes", "=", "None", ")", ":", "features", "=", "np", ".", "asarray", "(", "rdd", ".", "map", "(", "lambda", "lp", ":", "from_vector", "(", "lp", ".", "features", ")"...
Convert a LabeledPoint RDD back to a pair of numpy arrays :param rdd: LabeledPoint RDD :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: optional int, indicating the number of class labels :return: pair of numpy arrays, features and labels
[ "Convert", "a", "LabeledPoint", "RDD", "back", "to", "a", "pair", "of", "numpy", "arrays" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L71-L89
train
214,945
maxpumperla/elephas
elephas/utils/rdd_utils.py
encode_label
def encode_label(label, nb_classes): """One-hot encoding of a single label :param label: class label (int or double without floating point digits) :param nb_classes: int, number of total classes :return: one-hot encoded vector """ encoded = np.zeros(nb_classes) encoded[int(label)] = 1. return encoded
python
def encode_label(label, nb_classes): """One-hot encoding of a single label :param label: class label (int or double without floating point digits) :param nb_classes: int, number of total classes :return: one-hot encoded vector """ encoded = np.zeros(nb_classes) encoded[int(label)] = 1. return encoded
[ "def", "encode_label", "(", "label", ",", "nb_classes", ")", ":", "encoded", "=", "np", ".", "zeros", "(", "nb_classes", ")", "encoded", "[", "int", "(", "label", ")", "]", "=", "1.", "return", "encoded" ]
One-hot encoding of a single label :param label: class label (int or double without floating point digits) :param nb_classes: int, number of total classes :return: one-hot encoded vector
[ "One", "-", "hot", "encoding", "of", "a", "single", "label" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L92-L101
train
214,946
maxpumperla/elephas
elephas/utils/rdd_utils.py
lp_to_simple_rdd
def lp_to_simple_rdd(lp_rdd, categorical=False, nb_classes=None): """Convert a LabeledPoint RDD into an RDD of feature-label pairs :param lp_rdd: LabeledPoint RDD of features and labels :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: int, number of total classes :return: Spark RDD with feature-label pairs """ if categorical: if not nb_classes: labels = np.asarray(lp_rdd.map( lambda lp: lp.label).collect(), dtype='int32') nb_classes = np.max(labels) + 1 rdd = lp_rdd.map(lambda lp: (from_vector(lp.features), encode_label(lp.label, nb_classes))) else: rdd = lp_rdd.map(lambda lp: (from_vector(lp.features), lp.label)) return rdd
python
def lp_to_simple_rdd(lp_rdd, categorical=False, nb_classes=None): """Convert a LabeledPoint RDD into an RDD of feature-label pairs :param lp_rdd: LabeledPoint RDD of features and labels :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: int, number of total classes :return: Spark RDD with feature-label pairs """ if categorical: if not nb_classes: labels = np.asarray(lp_rdd.map( lambda lp: lp.label).collect(), dtype='int32') nb_classes = np.max(labels) + 1 rdd = lp_rdd.map(lambda lp: (from_vector(lp.features), encode_label(lp.label, nb_classes))) else: rdd = lp_rdd.map(lambda lp: (from_vector(lp.features), lp.label)) return rdd
[ "def", "lp_to_simple_rdd", "(", "lp_rdd", ",", "categorical", "=", "False", ",", "nb_classes", "=", "None", ")", ":", "if", "categorical", ":", "if", "not", "nb_classes", ":", "labels", "=", "np", ".", "asarray", "(", "lp_rdd", ".", "map", "(", "lambda",...
Convert a LabeledPoint RDD into an RDD of feature-label pairs :param lp_rdd: LabeledPoint RDD of features and labels :param categorical: boolean, if labels should be one-hot encode when returned :param nb_classes: int, number of total classes :return: Spark RDD with feature-label pairs
[ "Convert", "a", "LabeledPoint", "RDD", "into", "an", "RDD", "of", "feature", "-", "label", "pairs" ]
84605acdc9564673c487637dcb27f5def128bcc7
https://github.com/maxpumperla/elephas/blob/84605acdc9564673c487637dcb27f5def128bcc7/elephas/utils/rdd_utils.py#L104-L121
train
214,947
lebinh/ngxtop
ngxtop/ngxtop.py
follow
def follow(the_file): """ Follow a given file and yield new lines when they are available, like `tail -f`. """ with open(the_file) as f: f.seek(0, 2) # seek to eof while True: line = f.readline() if not line: time.sleep(0.1) # sleep briefly before trying again continue yield line
python
def follow(the_file): """ Follow a given file and yield new lines when they are available, like `tail -f`. """ with open(the_file) as f: f.seek(0, 2) # seek to eof while True: line = f.readline() if not line: time.sleep(0.1) # sleep briefly before trying again continue yield line
[ "def", "follow", "(", "the_file", ")", ":", "with", "open", "(", "the_file", ")", "as", "f", ":", "f", ".", "seek", "(", "0", ",", "2", ")", "# seek to eof", "while", "True", ":", "line", "=", "f", ".", "readline", "(", ")", "if", "not", "line", ...
Follow a given file and yield new lines when they are available, like `tail -f`.
[ "Follow", "a", "given", "file", "and", "yield", "new", "lines", "when", "they", "are", "available", "like", "tail", "-", "f", "." ]
170caa1cd899de051ab961a3e46f7ecfbfed7764
https://github.com/lebinh/ngxtop/blob/170caa1cd899de051ab961a3e46f7ecfbfed7764/ngxtop/ngxtop.py#L116-L127
train
214,948
lebinh/ngxtop
ngxtop/ngxtop.py
map_field
def map_field(field, func, dict_sequence): """ Apply given function to value of given key in every dictionary in sequence and set the result as new value for that key. """ for item in dict_sequence: try: item[field] = func(item.get(field, None)) yield item except ValueError: pass
python
def map_field(field, func, dict_sequence): """ Apply given function to value of given key in every dictionary in sequence and set the result as new value for that key. """ for item in dict_sequence: try: item[field] = func(item.get(field, None)) yield item except ValueError: pass
[ "def", "map_field", "(", "field", ",", "func", ",", "dict_sequence", ")", ":", "for", "item", "in", "dict_sequence", ":", "try", ":", "item", "[", "field", "]", "=", "func", "(", "item", ".", "get", "(", "field", ",", "None", ")", ")", "yield", "it...
Apply given function to value of given key in every dictionary in sequence and set the result as new value for that key.
[ "Apply", "given", "function", "to", "value", "of", "given", "key", "in", "every", "dictionary", "in", "sequence", "and", "set", "the", "result", "as", "new", "value", "for", "that", "key", "." ]
170caa1cd899de051ab961a3e46f7ecfbfed7764
https://github.com/lebinh/ngxtop/blob/170caa1cd899de051ab961a3e46f7ecfbfed7764/ngxtop/ngxtop.py#L130-L140
train
214,949
lebinh/ngxtop
ngxtop/ngxtop.py
add_field
def add_field(field, func, dict_sequence): """ Apply given function to the record and store result in given field of current record. Do nothing if record already contains given field. """ for item in dict_sequence: if field not in item: item[field] = func(item) yield item
python
def add_field(field, func, dict_sequence): """ Apply given function to the record and store result in given field of current record. Do nothing if record already contains given field. """ for item in dict_sequence: if field not in item: item[field] = func(item) yield item
[ "def", "add_field", "(", "field", ",", "func", ",", "dict_sequence", ")", ":", "for", "item", "in", "dict_sequence", ":", "if", "field", "not", "in", "item", ":", "item", "[", "field", "]", "=", "func", "(", "item", ")", "yield", "item" ]
Apply given function to the record and store result in given field of current record. Do nothing if record already contains given field.
[ "Apply", "given", "function", "to", "the", "record", "and", "store", "result", "in", "given", "field", "of", "current", "record", ".", "Do", "nothing", "if", "record", "already", "contains", "given", "field", "." ]
170caa1cd899de051ab961a3e46f7ecfbfed7764
https://github.com/lebinh/ngxtop/blob/170caa1cd899de051ab961a3e46f7ecfbfed7764/ngxtop/ngxtop.py#L143-L151
train
214,950
dedupeio/dedupe
dedupe/canonical.py
getCanonicalRep
def getCanonicalRep(record_cluster): """ Given a list of records within a duplicate cluster, constructs a canonical representation of the cluster by finding canonical values for each field """ canonical_rep = {} keys = record_cluster[0].keys() for key in keys: key_values = [] for record in record_cluster: # assume non-empty values always better than empty value # for canonical record if record[key]: key_values.append(record[key]) if key_values: canonical_rep[key] = getCentroid(key_values, comparator) else: canonical_rep[key] = '' return canonical_rep
python
def getCanonicalRep(record_cluster): """ Given a list of records within a duplicate cluster, constructs a canonical representation of the cluster by finding canonical values for each field """ canonical_rep = {} keys = record_cluster[0].keys() for key in keys: key_values = [] for record in record_cluster: # assume non-empty values always better than empty value # for canonical record if record[key]: key_values.append(record[key]) if key_values: canonical_rep[key] = getCentroid(key_values, comparator) else: canonical_rep[key] = '' return canonical_rep
[ "def", "getCanonicalRep", "(", "record_cluster", ")", ":", "canonical_rep", "=", "{", "}", "keys", "=", "record_cluster", "[", "0", "]", ".", "keys", "(", ")", "for", "key", "in", "keys", ":", "key_values", "=", "[", "]", "for", "record", "in", "record...
Given a list of records within a duplicate cluster, constructs a canonical representation of the cluster by finding canonical values for each field
[ "Given", "a", "list", "of", "records", "within", "a", "duplicate", "cluster", "constructs", "a", "canonical", "representation", "of", "the", "cluster", "by", "finding", "canonical", "values", "for", "each", "field" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/canonical.py#L48-L71
train
214,951
dedupeio/dedupe
dedupe/predicates.py
nearIntegersPredicate
def nearIntegersPredicate(field): """return any integers N, N+1, and N-1""" ints = integers(field) near_ints = set() for char in ints: num = int(char) near_ints.add(str(num - 1)) near_ints.add(str(num)) near_ints.add(str(num + 1)) return near_ints
python
def nearIntegersPredicate(field): """return any integers N, N+1, and N-1""" ints = integers(field) near_ints = set() for char in ints: num = int(char) near_ints.add(str(num - 1)) near_ints.add(str(num)) near_ints.add(str(num + 1)) return near_ints
[ "def", "nearIntegersPredicate", "(", "field", ")", ":", "ints", "=", "integers", "(", "field", ")", "near_ints", "=", "set", "(", ")", "for", "char", "in", "ints", ":", "num", "=", "int", "(", "char", ")", "near_ints", ".", "add", "(", "str", "(", ...
return any integers N, N+1, and N-1
[ "return", "any", "integers", "N", "N", "+", "1", "and", "N", "-", "1" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/predicates.py#L320-L330
train
214,952
dedupeio/dedupe
dedupe/core.py
randomPairsMatch
def randomPairsMatch(n_records_A, n_records_B, sample_size): """ Return random combinations of indices for record list A and B """ n = int(n_records_A * n_records_B) if sample_size >= n: random_pairs = numpy.arange(n) else: random_pairs = numpy.array(random.sample(range(n), sample_size), dtype=int) i, j = numpy.unravel_index(random_pairs, (n_records_A, n_records_B)) return zip(i, j)
python
def randomPairsMatch(n_records_A, n_records_B, sample_size): """ Return random combinations of indices for record list A and B """ n = int(n_records_A * n_records_B) if sample_size >= n: random_pairs = numpy.arange(n) else: random_pairs = numpy.array(random.sample(range(n), sample_size), dtype=int) i, j = numpy.unravel_index(random_pairs, (n_records_A, n_records_B)) return zip(i, j)
[ "def", "randomPairsMatch", "(", "n_records_A", ",", "n_records_B", ",", "sample_size", ")", ":", "n", "=", "int", "(", "n_records_A", "*", "n_records_B", ")", "if", "sample_size", ">=", "n", ":", "random_pairs", "=", "numpy", ".", "arange", "(", "n", ")", ...
Return random combinations of indices for record list A and B
[ "Return", "random", "combinations", "of", "indices", "for", "record", "list", "A", "and", "B" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/core.py#L65-L79
train
214,953
dedupeio/dedupe
dedupe/api.py
Matching.thresholdBlocks
def thresholdBlocks(self, blocks, recall_weight=1.5): # pragma: nocover """ Returns the threshold that maximizes the expected F score, a weighted average of precision and recall for a sample of blocked data. Arguments: blocks -- Sequence of tuples of records, where each tuple is a set of records covered by a blocking predicate recall_weight -- Sets the tradeoff between precision and recall. I.e. if you care twice as much about recall as you do precision, set recall_weight to 2. """ candidate_records = itertools.chain.from_iterable(self._blockedPairs(blocks)) probability = core.scoreDuplicates(candidate_records, self.data_model, self.classifier, self.num_cores)['score'] probability = probability.copy() probability.sort() probability = probability[::-1] expected_dupes = numpy.cumsum(probability) recall = expected_dupes / expected_dupes[-1] precision = expected_dupes / numpy.arange(1, len(expected_dupes) + 1) score = recall * precision / (recall + recall_weight ** 2 * precision) i = numpy.argmax(score) logger.info('Maximum expected recall and precision') logger.info('recall: %2.3f', recall[i]) logger.info('precision: %2.3f', precision[i]) logger.info('With threshold: %2.3f', probability[i]) return probability[i]
python
def thresholdBlocks(self, blocks, recall_weight=1.5): # pragma: nocover """ Returns the threshold that maximizes the expected F score, a weighted average of precision and recall for a sample of blocked data. Arguments: blocks -- Sequence of tuples of records, where each tuple is a set of records covered by a blocking predicate recall_weight -- Sets the tradeoff between precision and recall. I.e. if you care twice as much about recall as you do precision, set recall_weight to 2. """ candidate_records = itertools.chain.from_iterable(self._blockedPairs(blocks)) probability = core.scoreDuplicates(candidate_records, self.data_model, self.classifier, self.num_cores)['score'] probability = probability.copy() probability.sort() probability = probability[::-1] expected_dupes = numpy.cumsum(probability) recall = expected_dupes / expected_dupes[-1] precision = expected_dupes / numpy.arange(1, len(expected_dupes) + 1) score = recall * precision / (recall + recall_weight ** 2 * precision) i = numpy.argmax(score) logger.info('Maximum expected recall and precision') logger.info('recall: %2.3f', recall[i]) logger.info('precision: %2.3f', precision[i]) logger.info('With threshold: %2.3f', probability[i]) return probability[i]
[ "def", "thresholdBlocks", "(", "self", ",", "blocks", ",", "recall_weight", "=", "1.5", ")", ":", "# pragma: nocover", "candidate_records", "=", "itertools", ".", "chain", ".", "from_iterable", "(", "self", ".", "_blockedPairs", "(", "blocks", ")", ")", "proba...
Returns the threshold that maximizes the expected F score, a weighted average of precision and recall for a sample of blocked data. Arguments: blocks -- Sequence of tuples of records, where each tuple is a set of records covered by a blocking predicate recall_weight -- Sets the tradeoff between precision and recall. I.e. if you care twice as much about recall as you do precision, set recall_weight to 2.
[ "Returns", "the", "threshold", "that", "maximizes", "the", "expected", "F", "score", "a", "weighted", "average", "of", "precision", "and", "recall", "for", "a", "sample", "of", "blocked", "data", "." ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/api.py#L52-L94
train
214,954
dedupeio/dedupe
dedupe/api.py
DedupeMatching.match
def match(self, data, threshold=0.5, generator=False): # pragma: no cover """Identifies records that all refer to the same entity, returns tuples containing a set of record ids and a confidence score as a float between 0 and 1. The record_ids within each set should refer to the same entity and the confidence score is a measure of our confidence that all the records in a cluster refer to the same entity. This method should only used for small to moderately sized datasets for larger data, use matchBlocks Arguments: data -- Dictionary of records, where the keys are record_ids and the values are dictionaries with the keys being field names threshold -- Number between 0 and 1 (default is .5). We will consider records as potential duplicates if the predicted probability of being a duplicate is above the threshold. Lowering the number will increase recall, raising it will increase precision """ blocked_pairs = self._blockData(data) clusters = self.matchBlocks(blocked_pairs, threshold) if generator: return clusters else: return list(clusters)
python
def match(self, data, threshold=0.5, generator=False): # pragma: no cover """Identifies records that all refer to the same entity, returns tuples containing a set of record ids and a confidence score as a float between 0 and 1. The record_ids within each set should refer to the same entity and the confidence score is a measure of our confidence that all the records in a cluster refer to the same entity. This method should only used for small to moderately sized datasets for larger data, use matchBlocks Arguments: data -- Dictionary of records, where the keys are record_ids and the values are dictionaries with the keys being field names threshold -- Number between 0 and 1 (default is .5). We will consider records as potential duplicates if the predicted probability of being a duplicate is above the threshold. Lowering the number will increase recall, raising it will increase precision """ blocked_pairs = self._blockData(data) clusters = self.matchBlocks(blocked_pairs, threshold) if generator: return clusters else: return list(clusters)
[ "def", "match", "(", "self", ",", "data", ",", "threshold", "=", "0.5", ",", "generator", "=", "False", ")", ":", "# pragma: no cover", "blocked_pairs", "=", "self", ".", "_blockData", "(", "data", ")", "clusters", "=", "self", ".", "matchBlocks", "(", "...
Identifies records that all refer to the same entity, returns tuples containing a set of record ids and a confidence score as a float between 0 and 1. The record_ids within each set should refer to the same entity and the confidence score is a measure of our confidence that all the records in a cluster refer to the same entity. This method should only used for small to moderately sized datasets for larger data, use matchBlocks Arguments: data -- Dictionary of records, where the keys are record_ids and the values are dictionaries with the keys being field names threshold -- Number between 0 and 1 (default is .5). We will consider records as potential duplicates if the predicted probability of being a duplicate is above the threshold. Lowering the number will increase recall, raising it will increase precision
[ "Identifies", "records", "that", "all", "refer", "to", "the", "same", "entity", "returns", "tuples" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/api.py#L190-L223
train
214,955
dedupeio/dedupe
dedupe/api.py
ActiveMatching.readTraining
def readTraining(self, training_file): ''' Read training from previously built training data file object Arguments: training_file -- file object containing the training data ''' logger.info('reading training from file') training_pairs = json.load(training_file, cls=serializer.dedupe_decoder) self.markPairs(training_pairs)
python
def readTraining(self, training_file): ''' Read training from previously built training data file object Arguments: training_file -- file object containing the training data ''' logger.info('reading training from file') training_pairs = json.load(training_file, cls=serializer.dedupe_decoder) self.markPairs(training_pairs)
[ "def", "readTraining", "(", "self", ",", "training_file", ")", ":", "logger", ".", "info", "(", "'reading training from file'", ")", "training_pairs", "=", "json", ".", "load", "(", "training_file", ",", "cls", "=", "serializer", ".", "dedupe_decoder", ")", "s...
Read training from previously built training data file object Arguments: training_file -- file object containing the training data
[ "Read", "training", "from", "previously", "built", "training", "data", "file", "object" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/api.py#L635-L647
train
214,956
dedupeio/dedupe
dedupe/api.py
ActiveMatching.writeTraining
def writeTraining(self, file_obj): # pragma: no cover """ Write to a json file that contains labeled examples Keyword arguments: file_obj -- file object to write training data to """ json.dump(self.training_pairs, file_obj, default=serializer._to_json, tuple_as_array=False, ensure_ascii=True)
python
def writeTraining(self, file_obj): # pragma: no cover """ Write to a json file that contains labeled examples Keyword arguments: file_obj -- file object to write training data to """ json.dump(self.training_pairs, file_obj, default=serializer._to_json, tuple_as_array=False, ensure_ascii=True)
[ "def", "writeTraining", "(", "self", ",", "file_obj", ")", ":", "# pragma: no cover", "json", ".", "dump", "(", "self", ".", "training_pairs", ",", "file_obj", ",", "default", "=", "serializer", ".", "_to_json", ",", "tuple_as_array", "=", "False", ",", "ens...
Write to a json file that contains labeled examples Keyword arguments: file_obj -- file object to write training data to
[ "Write", "to", "a", "json", "file", "that", "contains", "labeled", "examples" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/api.py#L680-L692
train
214,957
dedupeio/dedupe
dedupe/api.py
RecordLink.sample
def sample(self, data_1, data_2, sample_size=15000, blocked_proportion=.5, original_length_1=None, original_length_2=None): ''' Draws a random sample of combinations of records from the first and second datasets, and initializes active learning with this sample Arguments: data_1 -- Dictionary of records from first dataset, where the keys are record_ids and the values are dictionaries with the keys being field names data_2 -- Dictionary of records from second dataset, same form as data_1 sample_size -- Size of the sample to draw ''' self._checkData(data_1, data_2) self.active_learner = self.ActiveLearner(self.data_model) self.active_learner.sample_product(data_1, data_2, blocked_proportion, sample_size, original_length_1, original_length_2)
python
def sample(self, data_1, data_2, sample_size=15000, blocked_proportion=.5, original_length_1=None, original_length_2=None): ''' Draws a random sample of combinations of records from the first and second datasets, and initializes active learning with this sample Arguments: data_1 -- Dictionary of records from first dataset, where the keys are record_ids and the values are dictionaries with the keys being field names data_2 -- Dictionary of records from second dataset, same form as data_1 sample_size -- Size of the sample to draw ''' self._checkData(data_1, data_2) self.active_learner = self.ActiveLearner(self.data_model) self.active_learner.sample_product(data_1, data_2, blocked_proportion, sample_size, original_length_1, original_length_2)
[ "def", "sample", "(", "self", ",", "data_1", ",", "data_2", ",", "sample_size", "=", "15000", ",", "blocked_proportion", "=", ".5", ",", "original_length_1", "=", "None", ",", "original_length_2", "=", "None", ")", ":", "self", ".", "_checkData", "(", "dat...
Draws a random sample of combinations of records from the first and second datasets, and initializes active learning with this sample Arguments: data_1 -- Dictionary of records from first dataset, where the keys are record_ids and the values are dictionaries with the keys being field names data_2 -- Dictionary of records from second dataset, same form as data_1 sample_size -- Size of the sample to draw
[ "Draws", "a", "random", "sample", "of", "combinations", "of", "records", "from", "the", "first", "and", "second", "datasets", "and", "initializes", "active", "learning", "with", "this", "sample" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/api.py#L816-L841
train
214,958
dedupeio/dedupe
dedupe/clustering.py
condensedDistance
def condensedDistance(dupes): ''' Convert the pairwise list of distances in dupes to "condensed distance matrix" required by the hierarchical clustering algorithms. Also return a dictionary that maps the distance matrix to the record_ids. The formula for an index of the condensed matrix is index = {N choose 2}-{N-row choose 2} + (col-row-1) = N*(N-1)/2 - (N-row)*(N-row-1)/2 + col - row - 1 ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^ matrix_length row_step where (row,col) is index of an uncondensed square N X N distance matrix. See http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.squareform.html ''' candidate_set = numpy.unique(dupes['pairs']) i_to_id = dict(enumerate(candidate_set)) ids = candidate_set.searchsorted(dupes['pairs']) row = ids[:, 0] col = ids[:, 1] N = len(candidate_set) matrix_length = N * (N - 1) / 2 row_step = (N - row) * (N - row - 1) / 2 index = matrix_length - row_step + col - row - 1 condensed_distances = numpy.ones(int(matrix_length), 'f4') condensed_distances[index.astype(int)] = 1 - dupes['score'] return i_to_id, condensed_distances, N
python
def condensedDistance(dupes): ''' Convert the pairwise list of distances in dupes to "condensed distance matrix" required by the hierarchical clustering algorithms. Also return a dictionary that maps the distance matrix to the record_ids. The formula for an index of the condensed matrix is index = {N choose 2}-{N-row choose 2} + (col-row-1) = N*(N-1)/2 - (N-row)*(N-row-1)/2 + col - row - 1 ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^ matrix_length row_step where (row,col) is index of an uncondensed square N X N distance matrix. See http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.squareform.html ''' candidate_set = numpy.unique(dupes['pairs']) i_to_id = dict(enumerate(candidate_set)) ids = candidate_set.searchsorted(dupes['pairs']) row = ids[:, 0] col = ids[:, 1] N = len(candidate_set) matrix_length = N * (N - 1) / 2 row_step = (N - row) * (N - row - 1) / 2 index = matrix_length - row_step + col - row - 1 condensed_distances = numpy.ones(int(matrix_length), 'f4') condensed_distances[index.astype(int)] = 1 - dupes['score'] return i_to_id, condensed_distances, N
[ "def", "condensedDistance", "(", "dupes", ")", ":", "candidate_set", "=", "numpy", ".", "unique", "(", "dupes", "[", "'pairs'", "]", ")", "i_to_id", "=", "dict", "(", "enumerate", "(", "candidate_set", ")", ")", "ids", "=", "candidate_set", ".", "searchsor...
Convert the pairwise list of distances in dupes to "condensed distance matrix" required by the hierarchical clustering algorithms. Also return a dictionary that maps the distance matrix to the record_ids. The formula for an index of the condensed matrix is index = {N choose 2}-{N-row choose 2} + (col-row-1) = N*(N-1)/2 - (N-row)*(N-row-1)/2 + col - row - 1 ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^ matrix_length row_step where (row,col) is index of an uncondensed square N X N distance matrix. See http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.squareform.html
[ "Convert", "the", "pairwise", "list", "of", "distances", "in", "dupes", "to", "condensed", "distance", "matrix", "required", "by", "the", "hierarchical", "clustering", "algorithms", ".", "Also", "return", "a", "dictionary", "that", "maps", "the", "distance", "ma...
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/clustering.py#L95-L131
train
214,959
dedupeio/dedupe
dedupe/clustering.py
cluster
def cluster(dupes, threshold=.5, max_components=30000): ''' Takes in a list of duplicate pairs and clusters them in to a list records that all refer to the same entity based on a given threshold Keyword arguments: threshold -- number betweent 0 and 1 (default is .5). lowering the number will increase precision, raising it will increase recall ''' distance_threshold = 1 - threshold dupe_sub_graphs = connected_components(dupes, max_components) for sub_graph in dupe_sub_graphs: if len(sub_graph) > 1: i_to_id, condensed_distances, N = condensedDistance(sub_graph) linkage = fastcluster.linkage(condensed_distances, method='centroid', preserve_input=True) partition = hcluster.fcluster(linkage, distance_threshold, criterion='distance') clusters = defaultdict(list) for i, cluster_id in enumerate(partition): clusters[cluster_id].append(i) for cluster in viewvalues(clusters): if len(cluster) > 1: scores = confidences(cluster, condensed_distances, N) yield tuple(i_to_id[i] for i in cluster), scores else: (ids, score), = sub_graph if score > threshold: yield tuple(ids), (score,) * 2
python
def cluster(dupes, threshold=.5, max_components=30000): ''' Takes in a list of duplicate pairs and clusters them in to a list records that all refer to the same entity based on a given threshold Keyword arguments: threshold -- number betweent 0 and 1 (default is .5). lowering the number will increase precision, raising it will increase recall ''' distance_threshold = 1 - threshold dupe_sub_graphs = connected_components(dupes, max_components) for sub_graph in dupe_sub_graphs: if len(sub_graph) > 1: i_to_id, condensed_distances, N = condensedDistance(sub_graph) linkage = fastcluster.linkage(condensed_distances, method='centroid', preserve_input=True) partition = hcluster.fcluster(linkage, distance_threshold, criterion='distance') clusters = defaultdict(list) for i, cluster_id in enumerate(partition): clusters[cluster_id].append(i) for cluster in viewvalues(clusters): if len(cluster) > 1: scores = confidences(cluster, condensed_distances, N) yield tuple(i_to_id[i] for i in cluster), scores else: (ids, score), = sub_graph if score > threshold: yield tuple(ids), (score,) * 2
[ "def", "cluster", "(", "dupes", ",", "threshold", "=", ".5", ",", "max_components", "=", "30000", ")", ":", "distance_threshold", "=", "1", "-", "threshold", "dupe_sub_graphs", "=", "connected_components", "(", "dupes", ",", "max_components", ")", "for", "sub_...
Takes in a list of duplicate pairs and clusters them in to a list records that all refer to the same entity based on a given threshold Keyword arguments: threshold -- number betweent 0 and 1 (default is .5). lowering the number will increase precision, raising it will increase recall
[ "Takes", "in", "a", "list", "of", "duplicate", "pairs", "and", "clusters", "them", "in", "to", "a", "list", "records", "that", "all", "refer", "to", "the", "same", "entity", "based", "on", "a", "given", "threshold" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/clustering.py#L134-L174
train
214,960
dedupeio/dedupe
dedupe/clustering.py
confidences
def confidences(cluster, condensed_distances, d): ''' We calculate a per record score that is similar to a standard deviation. The main reason is that these record scores can be used to calculate the standard deviation of an entire cluster, which is a reasonable metric for clusters. ''' scores = dict.fromkeys(cluster, 0.0) squared_distances = condensed_distances ** 2 for i, j in itertools.combinations(cluster, 2): index = d * (d - 1) / 2 - (d - i) * (d - i - 1) / 2 + j - i - 1 squared_dist = squared_distances[int(index)] scores[i] += squared_dist scores[j] += squared_dist scores = numpy.array([score for _, score in sorted(scores.items())]) scores /= len(cluster) - 1 scores = numpy.sqrt(scores) scores = 1 - scores return scores
python
def confidences(cluster, condensed_distances, d): ''' We calculate a per record score that is similar to a standard deviation. The main reason is that these record scores can be used to calculate the standard deviation of an entire cluster, which is a reasonable metric for clusters. ''' scores = dict.fromkeys(cluster, 0.0) squared_distances = condensed_distances ** 2 for i, j in itertools.combinations(cluster, 2): index = d * (d - 1) / 2 - (d - i) * (d - i - 1) / 2 + j - i - 1 squared_dist = squared_distances[int(index)] scores[i] += squared_dist scores[j] += squared_dist scores = numpy.array([score for _, score in sorted(scores.items())]) scores /= len(cluster) - 1 scores = numpy.sqrt(scores) scores = 1 - scores return scores
[ "def", "confidences", "(", "cluster", ",", "condensed_distances", ",", "d", ")", ":", "scores", "=", "dict", ".", "fromkeys", "(", "cluster", ",", "0.0", ")", "squared_distances", "=", "condensed_distances", "**", "2", "for", "i", ",", "j", "in", "itertool...
We calculate a per record score that is similar to a standard deviation. The main reason is that these record scores can be used to calculate the standard deviation of an entire cluster, which is a reasonable metric for clusters.
[ "We", "calculate", "a", "per", "record", "score", "that", "is", "similar", "to", "a", "standard", "deviation", ".", "The", "main", "reason", "is", "that", "these", "record", "scores", "can", "be", "used", "to", "calculate", "the", "standard", "deviation", ...
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/clustering.py#L177-L196
train
214,961
dedupeio/dedupe
dedupe/convenience.py
consoleLabel
def consoleLabel(deduper): # pragma: no cover ''' Command line interface for presenting and labeling training pairs by the user Argument : A deduper object ''' finished = False use_previous = False fields = unique(field.field for field in deduper.data_model.primary_fields) buffer_len = 1 # Max number of previous operations examples_buffer = [] uncertain_pairs = [] while not finished: if use_previous: record_pair, _ = examples_buffer.pop(0) use_previous = False else: if not uncertain_pairs: uncertain_pairs = deduper.uncertainPairs() try: record_pair = uncertain_pairs.pop() except IndexError: break n_match = (len(deduper.training_pairs['match']) + sum(label == 'match' for _, label in examples_buffer)) n_distinct = (len(deduper.training_pairs['distinct']) + sum(label == 'distinct' for _, label in examples_buffer)) for pair in record_pair: for field in fields: line = "%s : %s" % (field, pair[field]) print(line, file=sys.stderr) print(file=sys.stderr) print("{0}/10 positive, {1}/10 negative".format(n_match, n_distinct), file=sys.stderr) print('Do these records refer to the same thing?', file=sys.stderr) valid_response = False user_input = '' while not valid_response: if examples_buffer: prompt = '(y)es / (n)o / (u)nsure / (f)inished / (p)revious' valid_responses = {'y', 'n', 'u', 'f', 'p'} else: prompt = '(y)es / (n)o / (u)nsure / (f)inished' valid_responses = {'y', 'n', 'u', 'f'} print(prompt, file=sys.stderr) user_input = input() if user_input in valid_responses: valid_response = True if user_input == 'y': examples_buffer.insert(0, (record_pair, 'match')) elif user_input == 'n': examples_buffer.insert(0, (record_pair, 'distinct')) elif user_input == 'u': examples_buffer.insert(0, (record_pair, 'uncertain')) elif user_input == 'f': print('Finished labeling', file=sys.stderr) finished = True elif user_input == 'p': use_previous = True uncertain_pairs.append(record_pair) if len(examples_buffer) > buffer_len: record_pair, label = examples_buffer.pop() if label in ['distinct', 'match']: examples = {'distinct': [], 'match': []} examples[label].append(record_pair) deduper.markPairs(examples) for record_pair, label in examples_buffer: if label in ['distinct', 'match']: examples = {'distinct': [], 'match': []} examples[label].append(record_pair) deduper.markPairs(examples)
python
def consoleLabel(deduper): # pragma: no cover ''' Command line interface for presenting and labeling training pairs by the user Argument : A deduper object ''' finished = False use_previous = False fields = unique(field.field for field in deduper.data_model.primary_fields) buffer_len = 1 # Max number of previous operations examples_buffer = [] uncertain_pairs = [] while not finished: if use_previous: record_pair, _ = examples_buffer.pop(0) use_previous = False else: if not uncertain_pairs: uncertain_pairs = deduper.uncertainPairs() try: record_pair = uncertain_pairs.pop() except IndexError: break n_match = (len(deduper.training_pairs['match']) + sum(label == 'match' for _, label in examples_buffer)) n_distinct = (len(deduper.training_pairs['distinct']) + sum(label == 'distinct' for _, label in examples_buffer)) for pair in record_pair: for field in fields: line = "%s : %s" % (field, pair[field]) print(line, file=sys.stderr) print(file=sys.stderr) print("{0}/10 positive, {1}/10 negative".format(n_match, n_distinct), file=sys.stderr) print('Do these records refer to the same thing?', file=sys.stderr) valid_response = False user_input = '' while not valid_response: if examples_buffer: prompt = '(y)es / (n)o / (u)nsure / (f)inished / (p)revious' valid_responses = {'y', 'n', 'u', 'f', 'p'} else: prompt = '(y)es / (n)o / (u)nsure / (f)inished' valid_responses = {'y', 'n', 'u', 'f'} print(prompt, file=sys.stderr) user_input = input() if user_input in valid_responses: valid_response = True if user_input == 'y': examples_buffer.insert(0, (record_pair, 'match')) elif user_input == 'n': examples_buffer.insert(0, (record_pair, 'distinct')) elif user_input == 'u': examples_buffer.insert(0, (record_pair, 'uncertain')) elif user_input == 'f': print('Finished labeling', file=sys.stderr) finished = True elif user_input == 'p': use_previous = True uncertain_pairs.append(record_pair) if len(examples_buffer) > buffer_len: record_pair, label = examples_buffer.pop() if label in ['distinct', 'match']: examples = {'distinct': [], 'match': []} examples[label].append(record_pair) deduper.markPairs(examples) for record_pair, label in examples_buffer: if label in ['distinct', 'match']: examples = {'distinct': [], 'match': []} examples[label].append(record_pair) deduper.markPairs(examples)
[ "def", "consoleLabel", "(", "deduper", ")", ":", "# pragma: no cover", "finished", "=", "False", "use_previous", "=", "False", "fields", "=", "unique", "(", "field", ".", "field", "for", "field", "in", "deduper", ".", "data_model", ".", "primary_fields", ")", ...
Command line interface for presenting and labeling training pairs by the user Argument : A deduper object
[ "Command", "line", "interface", "for", "presenting", "and", "labeling", "training", "pairs", "by", "the", "user" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/convenience.py#L19-L105
train
214,962
dedupeio/dedupe
dedupe/convenience.py
trainingDataLink
def trainingDataLink(data_1, data_2, common_key, training_size=50000): # pragma: nocover ''' Construct training data for consumption by the ActiveLearning markPairs method from already linked datasets. Arguments : data_1 -- Dictionary of records from first dataset, where the keys are record_ids and the values are dictionaries with the keys being field names data_2 -- Dictionary of records from second dataset, same form as data_1 common_key -- The name of the record field that uniquely identifies a match training_size -- the rough limit of the number of training examples, defaults to 50000 Warning: Every match must be identified by the sharing of a common key. This function assumes that if two records do not share a common key then they are distinct records. ''' identified_records = collections.defaultdict(lambda: [[], []]) matched_pairs = set() distinct_pairs = set() for record_id, record in data_1.items(): identified_records[record[common_key]][0].append(record_id) for record_id, record in data_2.items(): identified_records[record[common_key]][1].append(record_id) for keys_1, keys_2 in identified_records.values(): if keys_1 and keys_2: matched_pairs.update(itertools.product(keys_1, keys_2)) keys_1 = list(data_1.keys()) keys_2 = list(data_2.keys()) random_pairs = [(keys_1[i], keys_2[j]) for i, j in randomPairsMatch(len(data_1), len(data_2), training_size)] distinct_pairs = ( pair for pair in random_pairs if pair not in matched_pairs) matched_records = [(data_1[key_1], data_2[key_2]) for key_1, key_2 in matched_pairs] distinct_records = [(data_1[key_1], data_2[key_2]) for key_1, key_2 in distinct_pairs] training_pairs = {'match': matched_records, 'distinct': distinct_records} return training_pairs
python
def trainingDataLink(data_1, data_2, common_key, training_size=50000): # pragma: nocover ''' Construct training data for consumption by the ActiveLearning markPairs method from already linked datasets. Arguments : data_1 -- Dictionary of records from first dataset, where the keys are record_ids and the values are dictionaries with the keys being field names data_2 -- Dictionary of records from second dataset, same form as data_1 common_key -- The name of the record field that uniquely identifies a match training_size -- the rough limit of the number of training examples, defaults to 50000 Warning: Every match must be identified by the sharing of a common key. This function assumes that if two records do not share a common key then they are distinct records. ''' identified_records = collections.defaultdict(lambda: [[], []]) matched_pairs = set() distinct_pairs = set() for record_id, record in data_1.items(): identified_records[record[common_key]][0].append(record_id) for record_id, record in data_2.items(): identified_records[record[common_key]][1].append(record_id) for keys_1, keys_2 in identified_records.values(): if keys_1 and keys_2: matched_pairs.update(itertools.product(keys_1, keys_2)) keys_1 = list(data_1.keys()) keys_2 = list(data_2.keys()) random_pairs = [(keys_1[i], keys_2[j]) for i, j in randomPairsMatch(len(data_1), len(data_2), training_size)] distinct_pairs = ( pair for pair in random_pairs if pair not in matched_pairs) matched_records = [(data_1[key_1], data_2[key_2]) for key_1, key_2 in matched_pairs] distinct_records = [(data_1[key_1], data_2[key_2]) for key_1, key_2 in distinct_pairs] training_pairs = {'match': matched_records, 'distinct': distinct_records} return training_pairs
[ "def", "trainingDataLink", "(", "data_1", ",", "data_2", ",", "common_key", ",", "training_size", "=", "50000", ")", ":", "# pragma: nocover", "identified_records", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "[", "[", "]", ",", "[", "]", "]"...
Construct training data for consumption by the ActiveLearning markPairs method from already linked datasets. Arguments : data_1 -- Dictionary of records from first dataset, where the keys are record_ids and the values are dictionaries with the keys being field names data_2 -- Dictionary of records from second dataset, same form as data_1 common_key -- The name of the record field that uniquely identifies a match training_size -- the rough limit of the number of training examples, defaults to 50000 Warning: Every match must be identified by the sharing of a common key. This function assumes that if two records do not share a common key then they are distinct records.
[ "Construct", "training", "data", "for", "consumption", "by", "the", "ActiveLearning", "markPairs", "method", "from", "already", "linked", "datasets", "." ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/convenience.py#L108-L167
train
214,963
dedupeio/dedupe
dedupe/convenience.py
trainingDataDedupe
def trainingDataDedupe(data, common_key, training_size=50000): # pragma: nocover ''' Construct training data for consumption by the ActiveLearning markPairs method from an already deduplicated dataset. Arguments : data -- Dictionary of records, where the keys are record_ids and the values are dictionaries with the keys being field names common_key -- The name of the record field that uniquely identifies a match training_size -- the rough limit of the number of training examples, defaults to 50000 Warning: Every match must be identified by the sharing of a common key. This function assumes that if two records do not share a common key then they are distinct records. ''' identified_records = collections.defaultdict(list) matched_pairs = set() distinct_pairs = set() unique_record_ids = set() # a list of record_ids associated with each common_key for record_id, record in data.items(): unique_record_ids.add(record_id) identified_records[record[common_key]].append(record_id) # all combinations of matched_pairs from each common_key group for record_ids in identified_records.values(): if len(record_ids) > 1: matched_pairs.update(itertools.combinations(sorted(record_ids), 2)) # calculate indices using dedupe.core.randomPairs to avoid # the memory cost of enumerating all possible pairs unique_record_ids = list(unique_record_ids) pair_indices = randomPairs(len(unique_record_ids), training_size) distinct_pairs = set() for i, j in pair_indices: distinct_pairs.add((unique_record_ids[i], unique_record_ids[j])) distinct_pairs -= matched_pairs matched_records = [(data[key_1], data[key_2]) for key_1, key_2 in matched_pairs] distinct_records = [(data[key_1], data[key_2]) for key_1, key_2 in distinct_pairs] training_pairs = {'match': matched_records, 'distinct': distinct_records} return training_pairs
python
def trainingDataDedupe(data, common_key, training_size=50000): # pragma: nocover ''' Construct training data for consumption by the ActiveLearning markPairs method from an already deduplicated dataset. Arguments : data -- Dictionary of records, where the keys are record_ids and the values are dictionaries with the keys being field names common_key -- The name of the record field that uniquely identifies a match training_size -- the rough limit of the number of training examples, defaults to 50000 Warning: Every match must be identified by the sharing of a common key. This function assumes that if two records do not share a common key then they are distinct records. ''' identified_records = collections.defaultdict(list) matched_pairs = set() distinct_pairs = set() unique_record_ids = set() # a list of record_ids associated with each common_key for record_id, record in data.items(): unique_record_ids.add(record_id) identified_records[record[common_key]].append(record_id) # all combinations of matched_pairs from each common_key group for record_ids in identified_records.values(): if len(record_ids) > 1: matched_pairs.update(itertools.combinations(sorted(record_ids), 2)) # calculate indices using dedupe.core.randomPairs to avoid # the memory cost of enumerating all possible pairs unique_record_ids = list(unique_record_ids) pair_indices = randomPairs(len(unique_record_ids), training_size) distinct_pairs = set() for i, j in pair_indices: distinct_pairs.add((unique_record_ids[i], unique_record_ids[j])) distinct_pairs -= matched_pairs matched_records = [(data[key_1], data[key_2]) for key_1, key_2 in matched_pairs] distinct_records = [(data[key_1], data[key_2]) for key_1, key_2 in distinct_pairs] training_pairs = {'match': matched_records, 'distinct': distinct_records} return training_pairs
[ "def", "trainingDataDedupe", "(", "data", ",", "common_key", ",", "training_size", "=", "50000", ")", ":", "# pragma: nocover", "identified_records", "=", "collections", ".", "defaultdict", "(", "list", ")", "matched_pairs", "=", "set", "(", ")", "distinct_pairs",...
Construct training data for consumption by the ActiveLearning markPairs method from an already deduplicated dataset. Arguments : data -- Dictionary of records, where the keys are record_ids and the values are dictionaries with the keys being field names common_key -- The name of the record field that uniquely identifies a match training_size -- the rough limit of the number of training examples, defaults to 50000 Warning: Every match must be identified by the sharing of a common key. This function assumes that if two records do not share a common key then they are distinct records.
[ "Construct", "training", "data", "for", "consumption", "by", "the", "ActiveLearning", "markPairs", "method", "from", "an", "already", "deduplicated", "dataset", "." ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/convenience.py#L170-L228
train
214,964
dedupeio/dedupe
dedupe/labeler.py
unique
def unique(seq): """Return the unique elements of a collection even if those elements are unhashable and unsortable, like dicts and sets""" cleaned = [] for each in seq: if each not in cleaned: cleaned.append(each) return cleaned
python
def unique(seq): """Return the unique elements of a collection even if those elements are unhashable and unsortable, like dicts and sets""" cleaned = [] for each in seq: if each not in cleaned: cleaned.append(each) return cleaned
[ "def", "unique", "(", "seq", ")", ":", "cleaned", "=", "[", "]", "for", "each", "in", "seq", ":", "if", "each", "not", "in", "cleaned", ":", "cleaned", ".", "append", "(", "each", ")", "return", "cleaned" ]
Return the unique elements of a collection even if those elements are unhashable and unsortable, like dicts and sets
[ "Return", "the", "unique", "elements", "of", "a", "collection", "even", "if", "those", "elements", "are", "unhashable", "and", "unsortable", "like", "dicts", "and", "sets" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/labeler.py#L383-L390
train
214,965
dedupeio/dedupe
dedupe/training.py
BlockLearner.learn
def learn(self, matches, recall): ''' Takes in a set of training pairs and predicates and tries to find a good set of blocking rules. ''' compound_length = 2 dupe_cover = Cover(self.blocker.predicates, matches) dupe_cover.dominators(cost=self.total_cover) dupe_cover.compound(compound_length) comparison_count = self.comparisons(dupe_cover, compound_length) dupe_cover.dominators(cost=comparison_count, comparison=True) coverable_dupes = set.union(*viewvalues(dupe_cover)) uncoverable_dupes = [pair for i, pair in enumerate(matches) if i not in coverable_dupes] epsilon = int((1.0 - recall) * len(matches)) if len(uncoverable_dupes) > epsilon: logger.warning(OUT_OF_PREDICATES_WARNING) logger.debug(uncoverable_dupes) epsilon = 0 else: epsilon -= len(uncoverable_dupes) for pred in dupe_cover: pred.count = comparison_count[pred] searcher = BranchBound(len(coverable_dupes) - epsilon, 2500) final_predicates = searcher.search(dupe_cover) logger.info('Final predicate set:') for predicate in final_predicates: logger.info(predicate) return final_predicates
python
def learn(self, matches, recall): ''' Takes in a set of training pairs and predicates and tries to find a good set of blocking rules. ''' compound_length = 2 dupe_cover = Cover(self.blocker.predicates, matches) dupe_cover.dominators(cost=self.total_cover) dupe_cover.compound(compound_length) comparison_count = self.comparisons(dupe_cover, compound_length) dupe_cover.dominators(cost=comparison_count, comparison=True) coverable_dupes = set.union(*viewvalues(dupe_cover)) uncoverable_dupes = [pair for i, pair in enumerate(matches) if i not in coverable_dupes] epsilon = int((1.0 - recall) * len(matches)) if len(uncoverable_dupes) > epsilon: logger.warning(OUT_OF_PREDICATES_WARNING) logger.debug(uncoverable_dupes) epsilon = 0 else: epsilon -= len(uncoverable_dupes) for pred in dupe_cover: pred.count = comparison_count[pred] searcher = BranchBound(len(coverable_dupes) - epsilon, 2500) final_predicates = searcher.search(dupe_cover) logger.info('Final predicate set:') for predicate in final_predicates: logger.info(predicate) return final_predicates
[ "def", "learn", "(", "self", ",", "matches", ",", "recall", ")", ":", "compound_length", "=", "2", "dupe_cover", "=", "Cover", "(", "self", ".", "blocker", ".", "predicates", ",", "matches", ")", "dupe_cover", ".", "dominators", "(", "cost", "=", "self",...
Takes in a set of training pairs and predicates and tries to find a good set of blocking rules.
[ "Takes", "in", "a", "set", "of", "training", "pairs", "and", "predicates", "and", "tries", "to", "find", "a", "good", "set", "of", "blocking", "rules", "." ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/training.py#L24-L62
train
214,966
dedupeio/dedupe
dedupe/blocking.py
Blocker.unindex
def unindex(self, data, field): '''Remove index of a given set of data''' indices = extractIndices(self.index_fields[field]) for doc in data: if doc: for _, index, preprocess in indices: index.unindex(preprocess(doc)) for index_type, index, _ in indices: index._index.initSearch() for predicate in self.index_fields[field][index_type]: logger.debug("Canopy: %s", str(predicate)) predicate.index = index
python
def unindex(self, data, field): '''Remove index of a given set of data''' indices = extractIndices(self.index_fields[field]) for doc in data: if doc: for _, index, preprocess in indices: index.unindex(preprocess(doc)) for index_type, index, _ in indices: index._index.initSearch() for predicate in self.index_fields[field][index_type]: logger.debug("Canopy: %s", str(predicate)) predicate.index = index
[ "def", "unindex", "(", "self", ",", "data", ",", "field", ")", ":", "indices", "=", "extractIndices", "(", "self", ".", "index_fields", "[", "field", "]", ")", "for", "doc", "in", "data", ":", "if", "doc", ":", "for", "_", ",", "index", ",", "prepr...
Remove index of a given set of data
[ "Remove", "index", "of", "a", "given", "set", "of", "data" ]
9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b
https://github.com/dedupeio/dedupe/blob/9f7c9f84473a4bcacf0f2b11152d8ed3eb35d48b/dedupe/blocking.py#L80-L95
train
214,967
marcgibbons/django-rest-swagger
example_app/snippets/models.py
Snippet.save
def save(self, *args, **kwargs): """ Use the `pygments` library to create a highlighted HTML representation of the code snippet. """ lexer = get_lexer_by_name(self.language) linenos = self.linenos and 'table' or False options = self.title and {'title': self.title} or {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(*args, **kwargs) # limit the number of instances retained snippets = Snippet.objects.all() if len(snippets) > 100: snippets[0].delete()
python
def save(self, *args, **kwargs): """ Use the `pygments` library to create a highlighted HTML representation of the code snippet. """ lexer = get_lexer_by_name(self.language) linenos = self.linenos and 'table' or False options = self.title and {'title': self.title} or {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(*args, **kwargs) # limit the number of instances retained snippets = Snippet.objects.all() if len(snippets) > 100: snippets[0].delete()
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lexer", "=", "get_lexer_by_name", "(", "self", ".", "language", ")", "linenos", "=", "self", ".", "linenos", "and", "'table'", "or", "False", "options", "=", "self", "....
Use the `pygments` library to create a highlighted HTML representation of the code snippet.
[ "Use", "the", "pygments", "library", "to", "create", "a", "highlighted", "HTML", "representation", "of", "the", "code", "snippet", "." ]
102d22eaefb7898342ba2fb5af5618b9e3a32f1d
https://github.com/marcgibbons/django-rest-swagger/blob/102d22eaefb7898342ba2fb5af5618b9e3a32f1d/example_app/snippets/models.py#L38-L54
train
214,968
adafruit/Adafruit_Blinka
src/adafruit_blinka/microcontroller/generic_linux/i2c.py
I2C.scan
def scan(self): """Try to read a byte from each address, if you get an OSError it means the device isnt there""" found = [] for addr in range(0,0x80): try: self._i2c_bus.read_byte(addr) except OSError: continue found.append(addr) return found
python
def scan(self): """Try to read a byte from each address, if you get an OSError it means the device isnt there""" found = [] for addr in range(0,0x80): try: self._i2c_bus.read_byte(addr) except OSError: continue found.append(addr) return found
[ "def", "scan", "(", "self", ")", ":", "found", "=", "[", "]", "for", "addr", "in", "range", "(", "0", ",", "0x80", ")", ":", "try", ":", "self", ".", "_i2c_bus", ".", "read_byte", "(", "addr", ")", "except", "OSError", ":", "continue", "found", "...
Try to read a byte from each address, if you get an OSError it means the device isnt there
[ "Try", "to", "read", "a", "byte", "from", "each", "address", "if", "you", "get", "an", "OSError", "it", "means", "the", "device", "isnt", "there" ]
b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff
https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/generic_linux/i2c.py#L24-L33
train
214,969
adafruit/Adafruit_Blinka
src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py
final
def final(): """In case the program is cancelled or quit, we need to clean up the PulseIn helper process and also the message queue, this is called at exit to do so""" if DEBUG: print("Cleaning up message queues", queues) print("Cleaning up processes", procs) for q in queues: q.remove() for proc in procs: proc.terminate()
python
def final(): """In case the program is cancelled or quit, we need to clean up the PulseIn helper process and also the message queue, this is called at exit to do so""" if DEBUG: print("Cleaning up message queues", queues) print("Cleaning up processes", procs) for q in queues: q.remove() for proc in procs: proc.terminate()
[ "def", "final", "(", ")", ":", "if", "DEBUG", ":", "print", "(", "\"Cleaning up message queues\"", ",", "queues", ")", "print", "(", "\"Cleaning up processes\"", ",", "procs", ")", "for", "q", "in", "queues", ":", "q", ".", "remove", "(", ")", "for", "pr...
In case the program is cancelled or quit, we need to clean up the PulseIn helper process and also the message queue, this is called at exit to do so
[ "In", "case", "the", "program", "is", "cancelled", "or", "quit", "we", "need", "to", "clean", "up", "the", "PulseIn", "helper", "process", "and", "also", "the", "message", "queue", "this", "is", "called", "at", "exit", "to", "do", "so" ]
b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff
https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L16-L25
train
214,970
adafruit/Adafruit_Blinka
src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py
PulseIn._wait_receive_msg
def _wait_receive_msg(self, timeout=0.25, type=2): """Internal helper that will wait for new messages of a given type, and throw an exception on timeout""" stamp = time.monotonic() while (time.monotonic() - stamp) < timeout: try: message = self._mq.receive(block=False, type=2) return message except sysv_ipc.BusyError: time.sleep(0.001) # wait a bit then retry! # uh-oh timed out raise RuntimeError("Timed out waiting for PulseIn message")
python
def _wait_receive_msg(self, timeout=0.25, type=2): """Internal helper that will wait for new messages of a given type, and throw an exception on timeout""" stamp = time.monotonic() while (time.monotonic() - stamp) < timeout: try: message = self._mq.receive(block=False, type=2) return message except sysv_ipc.BusyError: time.sleep(0.001) # wait a bit then retry! # uh-oh timed out raise RuntimeError("Timed out waiting for PulseIn message")
[ "def", "_wait_receive_msg", "(", "self", ",", "timeout", "=", "0.25", ",", "type", "=", "2", ")", ":", "stamp", "=", "time", ".", "monotonic", "(", ")", "while", "(", "time", ".", "monotonic", "(", ")", "-", "stamp", ")", "<", "timeout", ":", "try"...
Internal helper that will wait for new messages of a given type, and throw an exception on timeout
[ "Internal", "helper", "that", "will", "wait", "for", "new", "messages", "of", "a", "given", "type", "and", "throw", "an", "exception", "on", "timeout" ]
b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff
https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L69-L80
train
214,971
adafruit/Adafruit_Blinka
src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py
PulseIn.deinit
def deinit(self): """Deinitialises the PulseIn and releases any hardware and software resources for reuse.""" # Clean up after ourselves self._process.terminate() procs.remove(self._process) self._mq.remove() queues.remove(self._mq)
python
def deinit(self): """Deinitialises the PulseIn and releases any hardware and software resources for reuse.""" # Clean up after ourselves self._process.terminate() procs.remove(self._process) self._mq.remove() queues.remove(self._mq)
[ "def", "deinit", "(", "self", ")", ":", "# Clean up after ourselves", "self", ".", "_process", ".", "terminate", "(", ")", "procs", ".", "remove", "(", "self", ".", "_process", ")", "self", ".", "_mq", ".", "remove", "(", ")", "queues", ".", "remove", ...
Deinitialises the PulseIn and releases any hardware and software resources for reuse.
[ "Deinitialises", "the", "PulseIn", "and", "releases", "any", "hardware", "and", "software", "resources", "for", "reuse", "." ]
b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff
https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L82-L89
train
214,972
adafruit/Adafruit_Blinka
src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py
PulseIn.resume
def resume(self, trigger_duration=0): """Resumes pulse capture after an optional trigger pulse.""" if trigger_duration != 0: self._mq.send("t%d" % trigger_duration, True, type=1) else: self._mq.send("r", True, type=1) self._paused = False
python
def resume(self, trigger_duration=0): """Resumes pulse capture after an optional trigger pulse.""" if trigger_duration != 0: self._mq.send("t%d" % trigger_duration, True, type=1) else: self._mq.send("r", True, type=1) self._paused = False
[ "def", "resume", "(", "self", ",", "trigger_duration", "=", "0", ")", ":", "if", "trigger_duration", "!=", "0", ":", "self", ".", "_mq", ".", "send", "(", "\"t%d\"", "%", "trigger_duration", ",", "True", ",", "type", "=", "1", ")", "else", ":", "self...
Resumes pulse capture after an optional trigger pulse.
[ "Resumes", "pulse", "capture", "after", "an", "optional", "trigger", "pulse", "." ]
b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff
https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L99-L105
train
214,973
adafruit/Adafruit_Blinka
src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py
PulseIn.pause
def pause(self): """Pause pulse capture""" self._mq.send("p", True, type=1) self._paused = True
python
def pause(self): """Pause pulse capture""" self._mq.send("p", True, type=1) self._paused = True
[ "def", "pause", "(", "self", ")", ":", "self", ".", "_mq", ".", "send", "(", "\"p\"", ",", "True", ",", "type", "=", "1", ")", "self", ".", "_paused", "=", "True" ]
Pause pulse capture
[ "Pause", "pulse", "capture" ]
b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff
https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L107-L110
train
214,974
adafruit/Adafruit_Blinka
src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py
PulseIn.popleft
def popleft(self): """Removes and returns the oldest read pulse.""" self._mq.send("^", True, type=1) message = self._wait_receive_msg() reply = int(message[0].decode('utf-8')) #print(reply) if reply == -1: raise IndexError("pop from empty list") return reply
python
def popleft(self): """Removes and returns the oldest read pulse.""" self._mq.send("^", True, type=1) message = self._wait_receive_msg() reply = int(message[0].decode('utf-8')) #print(reply) if reply == -1: raise IndexError("pop from empty list") return reply
[ "def", "popleft", "(", "self", ")", ":", "self", ".", "_mq", ".", "send", "(", "\"^\"", ",", "True", ",", "type", "=", "1", ")", "message", "=", "self", ".", "_wait_receive_msg", "(", ")", "reply", "=", "int", "(", "message", "[", "0", "]", ".", ...
Removes and returns the oldest read pulse.
[ "Removes", "and", "returns", "the", "oldest", "read", "pulse", "." ]
b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff
https://github.com/adafruit/Adafruit_Blinka/blob/b4a2b3bf7d8cc88477027b827bd0a8e9b19588ff/src/adafruit_blinka/microcontroller/bcm283x/pulseio/PulseIn.py#L128-L136
train
214,975
jupyter-widgets/ipyleaflet
ipyleaflet/leaflet.py
LayerGroup._validate_layers
def _validate_layers(self, proposal): '''Validate layers list. Makes sure only one instance of any given layer can exist in the layers list. ''' self._layer_ids = [l.model_id for l in proposal.value] if len(set(self._layer_ids)) != len(self._layer_ids): raise LayerException('duplicate layer detected, only use each layer once') return proposal.value
python
def _validate_layers(self, proposal): '''Validate layers list. Makes sure only one instance of any given layer can exist in the layers list. ''' self._layer_ids = [l.model_id for l in proposal.value] if len(set(self._layer_ids)) != len(self._layer_ids): raise LayerException('duplicate layer detected, only use each layer once') return proposal.value
[ "def", "_validate_layers", "(", "self", ",", "proposal", ")", ":", "self", ".", "_layer_ids", "=", "[", "l", ".", "model_id", "for", "l", "in", "proposal", ".", "value", "]", "if", "len", "(", "set", "(", "self", ".", "_layer_ids", ")", ")", "!=", ...
Validate layers list. Makes sure only one instance of any given layer can exist in the layers list.
[ "Validate", "layers", "list", "." ]
74488d4699a5663fc28aabf94ebf08d956a30598
https://github.com/jupyter-widgets/ipyleaflet/blob/74488d4699a5663fc28aabf94ebf08d956a30598/ipyleaflet/leaflet.py#L431-L440
train
214,976
jupyter-widgets/ipyleaflet
ipyleaflet/leaflet.py
GeoJSON.on_hover
def on_hover(self, callback, remove=False): ''' The hover callback takes an unpacked set of keyword arguments. ''' self._hover_callbacks.register_callback(callback, remove=remove)
python
def on_hover(self, callback, remove=False): ''' The hover callback takes an unpacked set of keyword arguments. ''' self._hover_callbacks.register_callback(callback, remove=remove)
[ "def", "on_hover", "(", "self", ",", "callback", ",", "remove", "=", "False", ")", ":", "self", ".", "_hover_callbacks", ".", "register_callback", "(", "callback", ",", "remove", "=", "remove", ")" ]
The hover callback takes an unpacked set of keyword arguments.
[ "The", "hover", "callback", "takes", "an", "unpacked", "set", "of", "keyword", "arguments", "." ]
74488d4699a5663fc28aabf94ebf08d956a30598
https://github.com/jupyter-widgets/ipyleaflet/blob/74488d4699a5663fc28aabf94ebf08d956a30598/ipyleaflet/leaflet.py#L490-L494
train
214,977
jupyter-widgets/ipyleaflet
ipyleaflet/leaflet.py
Map._validate_controls
def _validate_controls(self, proposal): '''Validate controls list. Makes sure only one instance of any given layer can exist in the controls list. ''' self._control_ids = [c.model_id for c in proposal.value] if len(set(self._control_ids)) != len(self._control_ids): raise ControlException('duplicate control detected, only use each control once') return proposal.value
python
def _validate_controls(self, proposal): '''Validate controls list. Makes sure only one instance of any given layer can exist in the controls list. ''' self._control_ids = [c.model_id for c in proposal.value] if len(set(self._control_ids)) != len(self._control_ids): raise ControlException('duplicate control detected, only use each control once') return proposal.value
[ "def", "_validate_controls", "(", "self", ",", "proposal", ")", ":", "self", ".", "_control_ids", "=", "[", "c", ".", "model_id", "for", "c", "in", "proposal", ".", "value", "]", "if", "len", "(", "set", "(", "self", ".", "_control_ids", ")", ")", "!...
Validate controls list. Makes sure only one instance of any given layer can exist in the controls list.
[ "Validate", "controls", "list", "." ]
74488d4699a5663fc28aabf94ebf08d956a30598
https://github.com/jupyter-widgets/ipyleaflet/blob/74488d4699a5663fc28aabf94ebf08d956a30598/ipyleaflet/leaflet.py#L881-L890
train
214,978
mbedmicro/pyOCD
pyocd/debug/context.py
DebugContext.read_core_register
def read_core_register(self, reg): """ read CPU register Unpack floating point register values """ regIndex = register_name_to_index(reg) regValue = self.read_core_register_raw(regIndex) # Convert int to float. if is_single_float_register(regIndex): regValue = conversion.u32_to_float32(regValue) elif is_double_float_register(regIndex): regValue = conversion.u64_to_float64(regValue) return regValue
python
def read_core_register(self, reg): """ read CPU register Unpack floating point register values """ regIndex = register_name_to_index(reg) regValue = self.read_core_register_raw(regIndex) # Convert int to float. if is_single_float_register(regIndex): regValue = conversion.u32_to_float32(regValue) elif is_double_float_register(regIndex): regValue = conversion.u64_to_float64(regValue) return regValue
[ "def", "read_core_register", "(", "self", ",", "reg", ")", ":", "regIndex", "=", "register_name_to_index", "(", "reg", ")", "regValue", "=", "self", ".", "read_core_register_raw", "(", "regIndex", ")", "# Convert int to float.", "if", "is_single_float_register", "("...
read CPU register Unpack floating point register values
[ "read", "CPU", "register", "Unpack", "floating", "point", "register", "values" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/debug/context.py#L58-L70
train
214,979
mbedmicro/pyOCD
pyocd/debug/context.py
DebugContext.write_core_register
def write_core_register(self, reg, data): """ write a CPU register. Will need to pack floating point register values before writing. """ regIndex = register_name_to_index(reg) # Convert float to int. if is_single_float_register(regIndex) and type(data) is float: data = conversion.float32_to_u32(data) elif is_double_float_register(regIndex) and type(data) is float: data = conversion.float64_to_u64(data) self.write_core_register_raw(regIndex, data)
python
def write_core_register(self, reg, data): """ write a CPU register. Will need to pack floating point register values before writing. """ regIndex = register_name_to_index(reg) # Convert float to int. if is_single_float_register(regIndex) and type(data) is float: data = conversion.float32_to_u32(data) elif is_double_float_register(regIndex) and type(data) is float: data = conversion.float64_to_u64(data) self.write_core_register_raw(regIndex, data)
[ "def", "write_core_register", "(", "self", ",", "reg", ",", "data", ")", ":", "regIndex", "=", "register_name_to_index", "(", "reg", ")", "# Convert float to int.", "if", "is_single_float_register", "(", "regIndex", ")", "and", "type", "(", "data", ")", "is", ...
write a CPU register. Will need to pack floating point register values before writing.
[ "write", "a", "CPU", "register", ".", "Will", "need", "to", "pack", "floating", "point", "register", "values", "before", "writing", "." ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/debug/context.py#L84-L95
train
214,980
mbedmicro/pyOCD
pyocd/probe/cmsis_dap_probe.py
CMSISDAPProbe.connect
def connect(self, protocol=None): """Initialize DAP IO pins for JTAG or SWD""" # Convert protocol to port enum. if protocol is not None: port = self.PORT_MAP[protocol] else: port = DAPAccess.PORT.DEFAULT try: self._link.connect(port) except DAPAccess.Error as exc: six.raise_from(self._convert_exception(exc), exc) # Read the current mode and save it. actualMode = self._link.get_swj_mode() self._protocol = self.PORT_MAP[actualMode] self._invalidate_cached_registers()
python
def connect(self, protocol=None): """Initialize DAP IO pins for JTAG or SWD""" # Convert protocol to port enum. if protocol is not None: port = self.PORT_MAP[protocol] else: port = DAPAccess.PORT.DEFAULT try: self._link.connect(port) except DAPAccess.Error as exc: six.raise_from(self._convert_exception(exc), exc) # Read the current mode and save it. actualMode = self._link.get_swj_mode() self._protocol = self.PORT_MAP[actualMode] self._invalidate_cached_registers()
[ "def", "connect", "(", "self", ",", "protocol", "=", "None", ")", ":", "# Convert protocol to port enum.", "if", "protocol", "is", "not", "None", ":", "port", "=", "self", ".", "PORT_MAP", "[", "protocol", "]", "else", ":", "port", "=", "DAPAccess", ".", ...
Initialize DAP IO pins for JTAG or SWD
[ "Initialize", "DAP", "IO", "pins", "for", "JTAG", "or", "SWD" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/cmsis_dap_probe.py#L165-L182
train
214,981
mbedmicro/pyOCD
pyocd/probe/cmsis_dap_probe.py
CMSISDAPProbe.set_clock
def set_clock(self, frequency): """Set the frequency for JTAG and SWD in Hz This function is safe to call before connect is called. """ try: self._link.set_clock(frequency) except DAPAccess.Error as exc: six.raise_from(self._convert_exception(exc), exc)
python
def set_clock(self, frequency): """Set the frequency for JTAG and SWD in Hz This function is safe to call before connect is called. """ try: self._link.set_clock(frequency) except DAPAccess.Error as exc: six.raise_from(self._convert_exception(exc), exc)
[ "def", "set_clock", "(", "self", ",", "frequency", ")", ":", "try", ":", "self", ".", "_link", ".", "set_clock", "(", "frequency", ")", "except", "DAPAccess", ".", "Error", "as", "exc", ":", "six", ".", "raise_from", "(", "self", ".", "_convert_exception...
Set the frequency for JTAG and SWD in Hz This function is safe to call before connect is called.
[ "Set", "the", "frequency", "for", "JTAG", "and", "SWD", "in", "Hz" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/cmsis_dap_probe.py#L201-L209
train
214,982
mbedmicro/pyOCD
pyocd/probe/cmsis_dap_probe.py
CMSISDAPProbe.reset
def reset(self): """Reset the target""" try: self._invalidate_cached_registers() self._link.reset() except DAPAccess.Error as exc: six.raise_from(self._convert_exception(exc), exc)
python
def reset(self): """Reset the target""" try: self._invalidate_cached_registers() self._link.reset() except DAPAccess.Error as exc: six.raise_from(self._convert_exception(exc), exc)
[ "def", "reset", "(", "self", ")", ":", "try", ":", "self", ".", "_invalidate_cached_registers", "(", ")", "self", ".", "_link", ".", "reset", "(", ")", "except", "DAPAccess", ".", "Error", "as", "exc", ":", "six", ".", "raise_from", "(", "self", ".", ...
Reset the target
[ "Reset", "the", "target" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/cmsis_dap_probe.py#L211-L217
train
214,983
mbedmicro/pyOCD
pyocd/probe/cmsis_dap_probe.py
CMSISDAPProbe.assert_reset
def assert_reset(self, asserted): """Assert or de-assert target reset line""" try: self._invalidate_cached_registers() self._link.assert_reset(asserted) except DAPAccess.Error as exc: six.raise_from(self._convert_exception(exc), exc)
python
def assert_reset(self, asserted): """Assert or de-assert target reset line""" try: self._invalidate_cached_registers() self._link.assert_reset(asserted) except DAPAccess.Error as exc: six.raise_from(self._convert_exception(exc), exc)
[ "def", "assert_reset", "(", "self", ",", "asserted", ")", ":", "try", ":", "self", ".", "_invalidate_cached_registers", "(", ")", "self", ".", "_link", ".", "assert_reset", "(", "asserted", ")", "except", "DAPAccess", ".", "Error", "as", "exc", ":", "six",...
Assert or de-assert target reset line
[ "Assert", "or", "de", "-", "assert", "target", "reset", "line" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/probe/cmsis_dap_probe.py#L219-L225
train
214,984
mbedmicro/pyOCD
pyocd/debug/svd/parser.py
_get_text
def _get_text(node, tag, default=None): """Get the text for the provided tag from the provided node""" try: return node.find(tag).text except AttributeError: return default
python
def _get_text(node, tag, default=None): """Get the text for the provided tag from the provided node""" try: return node.find(tag).text except AttributeError: return default
[ "def", "_get_text", "(", "node", ",", "tag", ",", "default", "=", "None", ")", ":", "try", ":", "return", "node", ".", "find", "(", "tag", ")", ".", "text", "except", "AttributeError", ":", "return", "default" ]
Get the text for the provided tag from the provided node
[ "Get", "the", "text", "for", "the", "provided", "tag", "from", "the", "provided", "node" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/debug/svd/parser.py#L33-L38
train
214,985
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.init
def init(self): """ Cortex M initialization. The bus must be accessible when this method is called. """ if not self.call_delegate('will_start_debug_core', core=self): if self.halt_on_connect: self.halt() self._read_core_type() self._check_for_fpu() self.build_target_xml() self.sw_bp.init() self.call_delegate('did_start_debug_core', core=self)
python
def init(self): """ Cortex M initialization. The bus must be accessible when this method is called. """ if not self.call_delegate('will_start_debug_core', core=self): if self.halt_on_connect: self.halt() self._read_core_type() self._check_for_fpu() self.build_target_xml() self.sw_bp.init() self.call_delegate('did_start_debug_core', core=self)
[ "def", "init", "(", "self", ")", ":", "if", "not", "self", ".", "call_delegate", "(", "'will_start_debug_core'", ",", "core", "=", "self", ")", ":", "if", "self", ".", "halt_on_connect", ":", "self", ".", "halt", "(", ")", "self", ".", "_read_core_type",...
Cortex M initialization. The bus must be accessible when this method is called.
[ "Cortex", "M", "initialization", ".", "The", "bus", "must", "be", "accessible", "when", "this", "method", "is", "called", "." ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L478-L490
train
214,986
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.write_memory
def write_memory(self, addr, value, transfer_size=32): """ write a memory location. By default the transfer size is a word """ self.ap.write_memory(addr, value, transfer_size)
python
def write_memory(self, addr, value, transfer_size=32): """ write a memory location. By default the transfer size is a word """ self.ap.write_memory(addr, value, transfer_size)
[ "def", "write_memory", "(", "self", ",", "addr", ",", "value", ",", "transfer_size", "=", "32", ")", ":", "self", ".", "ap", ".", "write_memory", "(", "addr", ",", "value", ",", "transfer_size", ")" ]
write a memory location. By default the transfer size is a word
[ "write", "a", "memory", "location", ".", "By", "default", "the", "transfer", "size", "is", "a", "word" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L592-L597
train
214,987
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.read_memory
def read_memory(self, addr, transfer_size=32, now=True): """ read a memory location. By default, a word will be read """ result = self.ap.read_memory(addr, transfer_size, now) # Read callback returned for async reads. def read_memory_cb(): return self.bp_manager.filter_memory(addr, transfer_size, result()) if now: return self.bp_manager.filter_memory(addr, transfer_size, result) else: return read_memory_cb
python
def read_memory(self, addr, transfer_size=32, now=True): """ read a memory location. By default, a word will be read """ result = self.ap.read_memory(addr, transfer_size, now) # Read callback returned for async reads. def read_memory_cb(): return self.bp_manager.filter_memory(addr, transfer_size, result()) if now: return self.bp_manager.filter_memory(addr, transfer_size, result) else: return read_memory_cb
[ "def", "read_memory", "(", "self", ",", "addr", ",", "transfer_size", "=", "32", ",", "now", "=", "True", ")", ":", "result", "=", "self", ".", "ap", ".", "read_memory", "(", "addr", ",", "transfer_size", ",", "now", ")", "# Read callback returned for asyn...
read a memory location. By default, a word will be read
[ "read", "a", "memory", "location", ".", "By", "default", "a", "word", "will", "be", "read" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L599-L613
train
214,988
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.read_memory_block8
def read_memory_block8(self, addr, size): """ read a block of unaligned bytes in memory. Returns an array of byte values """ data = self.ap.read_memory_block8(addr, size) return self.bp_manager.filter_memory_unaligned_8(addr, size, data)
python
def read_memory_block8(self, addr, size): """ read a block of unaligned bytes in memory. Returns an array of byte values """ data = self.ap.read_memory_block8(addr, size) return self.bp_manager.filter_memory_unaligned_8(addr, size, data)
[ "def", "read_memory_block8", "(", "self", ",", "addr", ",", "size", ")", ":", "data", "=", "self", ".", "ap", ".", "read_memory_block8", "(", "addr", ",", "size", ")", "return", "self", ".", "bp_manager", ".", "filter_memory_unaligned_8", "(", "addr", ",",...
read a block of unaligned bytes in memory. Returns an array of byte values
[ "read", "a", "block", "of", "unaligned", "bytes", "in", "memory", ".", "Returns", "an", "array", "of", "byte", "values" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L615-L621
train
214,989
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.read_memory_block32
def read_memory_block32(self, addr, size): """ read a block of aligned words in memory. Returns an array of word values """ data = self.ap.read_memory_block32(addr, size) return self.bp_manager.filter_memory_aligned_32(addr, size, data)
python
def read_memory_block32(self, addr, size): """ read a block of aligned words in memory. Returns an array of word values """ data = self.ap.read_memory_block32(addr, size) return self.bp_manager.filter_memory_aligned_32(addr, size, data)
[ "def", "read_memory_block32", "(", "self", ",", "addr", ",", "size", ")", ":", "data", "=", "self", ".", "ap", ".", "read_memory_block32", "(", "addr", ",", "size", ")", "return", "self", ".", "bp_manager", ".", "filter_memory_aligned_32", "(", "addr", ","...
read a block of aligned words in memory. Returns an array of word values
[ "read", "a", "block", "of", "aligned", "words", "in", "memory", ".", "Returns", "an", "array", "of", "word", "values" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L635-L641
train
214,990
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.halt
def halt(self): """ halt the core """ self.notify(Notification(event=Target.EVENT_PRE_HALT, source=self, data=Target.HALT_REASON_USER)) self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_HALT) self.flush() self.notify(Notification(event=Target.EVENT_POST_HALT, source=self, data=Target.HALT_REASON_USER))
python
def halt(self): """ halt the core """ self.notify(Notification(event=Target.EVENT_PRE_HALT, source=self, data=Target.HALT_REASON_USER)) self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_HALT) self.flush() self.notify(Notification(event=Target.EVENT_POST_HALT, source=self, data=Target.HALT_REASON_USER))
[ "def", "halt", "(", "self", ")", ":", "self", ".", "notify", "(", "Notification", "(", "event", "=", "Target", ".", "EVENT_PRE_HALT", ",", "source", "=", "self", ",", "data", "=", "Target", ".", "HALT_REASON_USER", ")", ")", "self", ".", "write_memory", ...
halt the core
[ "halt", "the", "core" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L643-L650
train
214,991
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.step
def step(self, disable_interrupts=True, start=0, end=0): """ perform an instruction level step. This function preserves the previous interrupt mask state """ # Was 'if self.get_state() != TARGET_HALTED:' # but now value of dhcsr is saved dhcsr = self.read_memory(CortexM.DHCSR) if not (dhcsr & (CortexM.C_STEP | CortexM.C_HALT)): logging.error('cannot step: target not halted') return self.notify(Notification(event=Target.EVENT_PRE_RUN, source=self, data=Target.RUN_TYPE_STEP)) self.clear_debug_cause_bits() # Save previous interrupt mask state interrupts_masked = (CortexM.C_MASKINTS & dhcsr) != 0 # Mask interrupts - C_HALT must be set when changing to C_MASKINTS if not interrupts_masked and disable_interrupts: self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_HALT | CortexM.C_MASKINTS) # Single step using current C_MASKINTS setting while True: if disable_interrupts or interrupts_masked: self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_MASKINTS | CortexM.C_STEP) else: self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_STEP) # Wait for halt to auto set (This should be done before the first read) while not self.read_memory(CortexM.DHCSR) & CortexM.C_HALT: pass # Range is empty, 'range step' will degenerate to 'step' if start == end: break # Read program counter and compare to [start, end) program_counter = self.read_core_register(CORE_REGISTER['pc']) if program_counter < start or end <= program_counter: break # Check other stop reasons if self.read_memory(CortexM.DFSR) & (CortexM.DFSR_DWTTRAP | CortexM.DFSR_BKPT): break # Restore interrupt mask state if not interrupts_masked and disable_interrupts: # Unmask interrupts - C_HALT must be set when changing to C_MASKINTS self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_HALT) self.flush() self._run_token += 1 self.notify(Notification(event=Target.EVENT_POST_RUN, source=self, data=Target.RUN_TYPE_STEP))
python
def step(self, disable_interrupts=True, start=0, end=0): """ perform an instruction level step. This function preserves the previous interrupt mask state """ # Was 'if self.get_state() != TARGET_HALTED:' # but now value of dhcsr is saved dhcsr = self.read_memory(CortexM.DHCSR) if not (dhcsr & (CortexM.C_STEP | CortexM.C_HALT)): logging.error('cannot step: target not halted') return self.notify(Notification(event=Target.EVENT_PRE_RUN, source=self, data=Target.RUN_TYPE_STEP)) self.clear_debug_cause_bits() # Save previous interrupt mask state interrupts_masked = (CortexM.C_MASKINTS & dhcsr) != 0 # Mask interrupts - C_HALT must be set when changing to C_MASKINTS if not interrupts_masked and disable_interrupts: self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_HALT | CortexM.C_MASKINTS) # Single step using current C_MASKINTS setting while True: if disable_interrupts or interrupts_masked: self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_MASKINTS | CortexM.C_STEP) else: self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_STEP) # Wait for halt to auto set (This should be done before the first read) while not self.read_memory(CortexM.DHCSR) & CortexM.C_HALT: pass # Range is empty, 'range step' will degenerate to 'step' if start == end: break # Read program counter and compare to [start, end) program_counter = self.read_core_register(CORE_REGISTER['pc']) if program_counter < start or end <= program_counter: break # Check other stop reasons if self.read_memory(CortexM.DFSR) & (CortexM.DFSR_DWTTRAP | CortexM.DFSR_BKPT): break # Restore interrupt mask state if not interrupts_masked and disable_interrupts: # Unmask interrupts - C_HALT must be set when changing to C_MASKINTS self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN | CortexM.C_HALT) self.flush() self._run_token += 1 self.notify(Notification(event=Target.EVENT_POST_RUN, source=self, data=Target.RUN_TYPE_STEP))
[ "def", "step", "(", "self", ",", "disable_interrupts", "=", "True", ",", "start", "=", "0", ",", "end", "=", "0", ")", ":", "# Was 'if self.get_state() != TARGET_HALTED:'", "# but now value of dhcsr is saved", "dhcsr", "=", "self", ".", "read_memory", "(", "Cortex...
perform an instruction level step. This function preserves the previous interrupt mask state
[ "perform", "an", "instruction", "level", "step", ".", "This", "function", "preserves", "the", "previous", "interrupt", "mask", "state" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L652-L708
train
214,992
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.reset_and_halt
def reset_and_halt(self, reset_type=None): """ perform a reset and stop the core on the reset handler """ delegateResult = self.call_delegate('set_reset_catch', core=self, reset_type=reset_type) # halt the target if not delegateResult: self.halt() # Save CortexM.DEMCR demcr = self.read_memory(CortexM.DEMCR) # enable the vector catch if not delegateResult: self.write_memory(CortexM.DEMCR, demcr | CortexM.DEMCR_VC_CORERESET) self.reset(reset_type) # wait until the unit resets with timeout.Timeout(2.0) as t_o: while t_o.check(): if self.get_state() not in (Target.TARGET_RESET, Target.TARGET_RUNNING): break sleep(0.01) # Make sure the thumb bit is set in XPSR in case the reset handler # points to an invalid address. xpsr = self.read_core_register('xpsr') if xpsr & self.XPSR_THUMB == 0: self.write_core_register('xpsr', xpsr | self.XPSR_THUMB) self.call_delegate('clear_reset_catch', core=self, reset_type=reset_type) # restore vector catch setting self.write_memory(CortexM.DEMCR, demcr)
python
def reset_and_halt(self, reset_type=None): """ perform a reset and stop the core on the reset handler """ delegateResult = self.call_delegate('set_reset_catch', core=self, reset_type=reset_type) # halt the target if not delegateResult: self.halt() # Save CortexM.DEMCR demcr = self.read_memory(CortexM.DEMCR) # enable the vector catch if not delegateResult: self.write_memory(CortexM.DEMCR, demcr | CortexM.DEMCR_VC_CORERESET) self.reset(reset_type) # wait until the unit resets with timeout.Timeout(2.0) as t_o: while t_o.check(): if self.get_state() not in (Target.TARGET_RESET, Target.TARGET_RUNNING): break sleep(0.01) # Make sure the thumb bit is set in XPSR in case the reset handler # points to an invalid address. xpsr = self.read_core_register('xpsr') if xpsr & self.XPSR_THUMB == 0: self.write_core_register('xpsr', xpsr | self.XPSR_THUMB) self.call_delegate('clear_reset_catch', core=self, reset_type=reset_type) # restore vector catch setting self.write_memory(CortexM.DEMCR, demcr)
[ "def", "reset_and_halt", "(", "self", ",", "reset_type", "=", "None", ")", ":", "delegateResult", "=", "self", ".", "call_delegate", "(", "'set_reset_catch'", ",", "core", "=", "self", ",", "reset_type", "=", "reset_type", ")", "# halt the target", "if", "not"...
perform a reset and stop the core on the reset handler
[ "perform", "a", "reset", "and", "stop", "the", "core", "on", "the", "reset", "handler" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L889-L925
train
214,993
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.resume
def resume(self): """ resume the execution """ if self.get_state() != Target.TARGET_HALTED: logging.debug('cannot resume: target not halted') return self.notify(Notification(event=Target.EVENT_PRE_RUN, source=self, data=Target.RUN_TYPE_RESUME)) self._run_token += 1 self.clear_debug_cause_bits() self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN) self.flush() self.notify(Notification(event=Target.EVENT_POST_RUN, source=self, data=Target.RUN_TYPE_RESUME))
python
def resume(self): """ resume the execution """ if self.get_state() != Target.TARGET_HALTED: logging.debug('cannot resume: target not halted') return self.notify(Notification(event=Target.EVENT_PRE_RUN, source=self, data=Target.RUN_TYPE_RESUME)) self._run_token += 1 self.clear_debug_cause_bits() self.write_memory(CortexM.DHCSR, CortexM.DBGKEY | CortexM.C_DEBUGEN) self.flush() self.notify(Notification(event=Target.EVENT_POST_RUN, source=self, data=Target.RUN_TYPE_RESUME))
[ "def", "resume", "(", "self", ")", ":", "if", "self", ".", "get_state", "(", ")", "!=", "Target", ".", "TARGET_HALTED", ":", "logging", ".", "debug", "(", "'cannot resume: target not halted'", ")", "return", "self", ".", "notify", "(", "Notification", "(", ...
resume the execution
[ "resume", "the", "execution" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L956-L968
train
214,994
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.read_core_registers_raw
def read_core_registers_raw(self, reg_list): """ Read one or more core registers Read core registers in reg_list and return a list of values. If any register in reg_list is a string, find the number associated to this register in the lookup table CORE_REGISTER. """ # convert to index only reg_list = [register_name_to_index(reg) for reg in reg_list] # Sanity check register values for reg in reg_list: if reg not in CORE_REGISTER.values(): raise ValueError("unknown reg: %d" % reg) elif is_fpu_register(reg) and (not self.has_fpu): raise ValueError("attempt to read FPU register without FPU") # Handle doubles. doubles = [reg for reg in reg_list if is_double_float_register(reg)] hasDoubles = len(doubles) > 0 if hasDoubles: originalRegList = reg_list # Strip doubles from reg_list. reg_list = [reg for reg in reg_list if not is_double_float_register(reg)] # Read float regs required to build doubles. singleRegList = [] for reg in doubles: singleRegList += (-reg, -reg + 1) singleValues = self.read_core_registers_raw(singleRegList) # Begin all reads and writes dhcsr_cb_list = [] reg_cb_list = [] for reg in reg_list: if is_cfbp_subregister(reg): reg = CORE_REGISTER['cfbp'] elif is_psr_subregister(reg): reg = CORE_REGISTER['xpsr'] # write id in DCRSR self.write_memory(CortexM.DCRSR, reg) # Technically, we need to poll S_REGRDY in DHCSR here before reading DCRDR. But # we're running so slow compared to the target that it's not necessary. # Read it and assert that S_REGRDY is set dhcsr_cb = self.read_memory(CortexM.DHCSR, now=False) reg_cb = self.read_memory(CortexM.DCRDR, now=False) dhcsr_cb_list.append(dhcsr_cb) reg_cb_list.append(reg_cb) # Read all results reg_vals = [] for reg, reg_cb, dhcsr_cb in zip(reg_list, reg_cb_list, dhcsr_cb_list): dhcsr_val = dhcsr_cb() assert dhcsr_val & CortexM.S_REGRDY val = reg_cb() # Special handling for registers that are combined into a single DCRSR number. if is_cfbp_subregister(reg): val = (val >> ((-reg - 1) * 8)) & 0xff elif is_psr_subregister(reg): val &= sysm_to_psr_mask(reg) reg_vals.append(val) # Merge double regs back into result list. if hasDoubles: results = [] for reg in originalRegList: # Double if is_double_float_register(reg): doubleIndex = doubles.index(reg) singleLow = singleValues[doubleIndex * 2] singleHigh = singleValues[doubleIndex * 2 + 1] double = (singleHigh << 32) | singleLow results.append(double) # Other register else: results.append(reg_vals[reg_list.index(reg)]) reg_vals = results return reg_vals
python
def read_core_registers_raw(self, reg_list): """ Read one or more core registers Read core registers in reg_list and return a list of values. If any register in reg_list is a string, find the number associated to this register in the lookup table CORE_REGISTER. """ # convert to index only reg_list = [register_name_to_index(reg) for reg in reg_list] # Sanity check register values for reg in reg_list: if reg not in CORE_REGISTER.values(): raise ValueError("unknown reg: %d" % reg) elif is_fpu_register(reg) and (not self.has_fpu): raise ValueError("attempt to read FPU register without FPU") # Handle doubles. doubles = [reg for reg in reg_list if is_double_float_register(reg)] hasDoubles = len(doubles) > 0 if hasDoubles: originalRegList = reg_list # Strip doubles from reg_list. reg_list = [reg for reg in reg_list if not is_double_float_register(reg)] # Read float regs required to build doubles. singleRegList = [] for reg in doubles: singleRegList += (-reg, -reg + 1) singleValues = self.read_core_registers_raw(singleRegList) # Begin all reads and writes dhcsr_cb_list = [] reg_cb_list = [] for reg in reg_list: if is_cfbp_subregister(reg): reg = CORE_REGISTER['cfbp'] elif is_psr_subregister(reg): reg = CORE_REGISTER['xpsr'] # write id in DCRSR self.write_memory(CortexM.DCRSR, reg) # Technically, we need to poll S_REGRDY in DHCSR here before reading DCRDR. But # we're running so slow compared to the target that it's not necessary. # Read it and assert that S_REGRDY is set dhcsr_cb = self.read_memory(CortexM.DHCSR, now=False) reg_cb = self.read_memory(CortexM.DCRDR, now=False) dhcsr_cb_list.append(dhcsr_cb) reg_cb_list.append(reg_cb) # Read all results reg_vals = [] for reg, reg_cb, dhcsr_cb in zip(reg_list, reg_cb_list, dhcsr_cb_list): dhcsr_val = dhcsr_cb() assert dhcsr_val & CortexM.S_REGRDY val = reg_cb() # Special handling for registers that are combined into a single DCRSR number. if is_cfbp_subregister(reg): val = (val >> ((-reg - 1) * 8)) & 0xff elif is_psr_subregister(reg): val &= sysm_to_psr_mask(reg) reg_vals.append(val) # Merge double regs back into result list. if hasDoubles: results = [] for reg in originalRegList: # Double if is_double_float_register(reg): doubleIndex = doubles.index(reg) singleLow = singleValues[doubleIndex * 2] singleHigh = singleValues[doubleIndex * 2 + 1] double = (singleHigh << 32) | singleLow results.append(double) # Other register else: results.append(reg_vals[reg_list.index(reg)]) reg_vals = results return reg_vals
[ "def", "read_core_registers_raw", "(", "self", ",", "reg_list", ")", ":", "# convert to index only", "reg_list", "=", "[", "register_name_to_index", "(", "reg", ")", "for", "reg", "in", "reg_list", "]", "# Sanity check register values", "for", "reg", "in", "reg_list...
Read one or more core registers Read core registers in reg_list and return a list of values. If any register in reg_list is a string, find the number associated to this register in the lookup table CORE_REGISTER.
[ "Read", "one", "or", "more", "core", "registers" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L996-L1081
train
214,995
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.write_core_registers_raw
def write_core_registers_raw(self, reg_list, data_list): """ Write one or more core registers Write core registers in reg_list with the associated value in data_list. If any register in reg_list is a string, find the number associated to this register in the lookup table CORE_REGISTER. """ assert len(reg_list) == len(data_list) # convert to index only reg_list = [register_name_to_index(reg) for reg in reg_list] # Sanity check register values for reg in reg_list: if reg not in CORE_REGISTER.values(): raise ValueError("unknown reg: %d" % reg) elif is_fpu_register(reg) and (not self.has_fpu): raise ValueError("attempt to write FPU register without FPU") # Read special register if it is present in the list and # convert doubles to single float register writes. cfbpValue = None xpsrValue = None reg_data_list = [] for reg, data in zip(reg_list, data_list): if is_double_float_register(reg): # Replace double with two single float register writes. For instance, # a write of D2 gets converted to writes to S4 and S5. singleLow = data & 0xffffffff singleHigh = (data >> 32) & 0xffffffff reg_data_list += [(-reg, singleLow), (-reg + 1, singleHigh)] elif is_cfbp_subregister(reg) and cfbpValue is None: cfbpValue = self.read_core_register_raw(CORE_REGISTER['cfbp']) elif is_psr_subregister(reg) and xpsrValue is None: xpsrValue = self.read_core_register_raw(CORE_REGISTER['xpsr']) else: # Other register, just copy directly. reg_data_list.append((reg, data)) # Write out registers dhcsr_cb_list = [] for reg, data in reg_data_list: if is_cfbp_subregister(reg): # Mask in the new special register value so we don't modify the other register # values that share the same DCRSR number. shift = (-reg - 1) * 8 mask = 0xffffffff ^ (0xff << shift) data = (cfbpValue & mask) | ((data & 0xff) << shift) cfbpValue = data # update special register for other writes that might be in the list reg = CORE_REGISTER['cfbp'] elif is_psr_subregister(reg): mask = sysm_to_psr_mask(reg) data = (xpsrValue & (0xffffffff ^ mask)) | (data & mask) xpsrValue = data reg = CORE_REGISTER['xpsr'] # write DCRDR self.write_memory(CortexM.DCRDR, data) # write id in DCRSR and flag to start write transfer self.write_memory(CortexM.DCRSR, reg | CortexM.DCRSR_REGWnR) # Technically, we need to poll S_REGRDY in DHCSR here to ensure the # register write has completed. # Read it and assert that S_REGRDY is set dhcsr_cb = self.read_memory(CortexM.DHCSR, now=False) dhcsr_cb_list.append(dhcsr_cb) # Make sure S_REGRDY was set for all register # writes for dhcsr_cb in dhcsr_cb_list: dhcsr_val = dhcsr_cb() assert dhcsr_val & CortexM.S_REGRDY
python
def write_core_registers_raw(self, reg_list, data_list): """ Write one or more core registers Write core registers in reg_list with the associated value in data_list. If any register in reg_list is a string, find the number associated to this register in the lookup table CORE_REGISTER. """ assert len(reg_list) == len(data_list) # convert to index only reg_list = [register_name_to_index(reg) for reg in reg_list] # Sanity check register values for reg in reg_list: if reg not in CORE_REGISTER.values(): raise ValueError("unknown reg: %d" % reg) elif is_fpu_register(reg) and (not self.has_fpu): raise ValueError("attempt to write FPU register without FPU") # Read special register if it is present in the list and # convert doubles to single float register writes. cfbpValue = None xpsrValue = None reg_data_list = [] for reg, data in zip(reg_list, data_list): if is_double_float_register(reg): # Replace double with two single float register writes. For instance, # a write of D2 gets converted to writes to S4 and S5. singleLow = data & 0xffffffff singleHigh = (data >> 32) & 0xffffffff reg_data_list += [(-reg, singleLow), (-reg + 1, singleHigh)] elif is_cfbp_subregister(reg) and cfbpValue is None: cfbpValue = self.read_core_register_raw(CORE_REGISTER['cfbp']) elif is_psr_subregister(reg) and xpsrValue is None: xpsrValue = self.read_core_register_raw(CORE_REGISTER['xpsr']) else: # Other register, just copy directly. reg_data_list.append((reg, data)) # Write out registers dhcsr_cb_list = [] for reg, data in reg_data_list: if is_cfbp_subregister(reg): # Mask in the new special register value so we don't modify the other register # values that share the same DCRSR number. shift = (-reg - 1) * 8 mask = 0xffffffff ^ (0xff << shift) data = (cfbpValue & mask) | ((data & 0xff) << shift) cfbpValue = data # update special register for other writes that might be in the list reg = CORE_REGISTER['cfbp'] elif is_psr_subregister(reg): mask = sysm_to_psr_mask(reg) data = (xpsrValue & (0xffffffff ^ mask)) | (data & mask) xpsrValue = data reg = CORE_REGISTER['xpsr'] # write DCRDR self.write_memory(CortexM.DCRDR, data) # write id in DCRSR and flag to start write transfer self.write_memory(CortexM.DCRSR, reg | CortexM.DCRSR_REGWnR) # Technically, we need to poll S_REGRDY in DHCSR here to ensure the # register write has completed. # Read it and assert that S_REGRDY is set dhcsr_cb = self.read_memory(CortexM.DHCSR, now=False) dhcsr_cb_list.append(dhcsr_cb) # Make sure S_REGRDY was set for all register # writes for dhcsr_cb in dhcsr_cb_list: dhcsr_val = dhcsr_cb() assert dhcsr_val & CortexM.S_REGRDY
[ "def", "write_core_registers_raw", "(", "self", ",", "reg_list", ",", "data_list", ")", ":", "assert", "len", "(", "reg_list", ")", "==", "len", "(", "data_list", ")", "# convert to index only", "reg_list", "=", "[", "register_name_to_index", "(", "reg", ")", ...
Write one or more core registers Write core registers in reg_list with the associated value in data_list. If any register in reg_list is a string, find the number associated to this register in the lookup table CORE_REGISTER.
[ "Write", "one", "or", "more", "core", "registers" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L1104-L1176
train
214,996
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.set_watchpoint
def set_watchpoint(self, addr, size, type): """ set a hardware watchpoint """ return self.dwt.set_watchpoint(addr, size, type)
python
def set_watchpoint(self, addr, size, type): """ set a hardware watchpoint """ return self.dwt.set_watchpoint(addr, size, type)
[ "def", "set_watchpoint", "(", "self", ",", "addr", ",", "size", ",", "type", ")", ":", "return", "self", ".", "dwt", ".", "set_watchpoint", "(", "addr", ",", "size", ",", "type", ")" ]
set a hardware watchpoint
[ "set", "a", "hardware", "watchpoint" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L1199-L1203
train
214,997
mbedmicro/pyOCD
pyocd/coresight/cortex_m.py
CortexM.remove_watchpoint
def remove_watchpoint(self, addr, size, type): """ remove a hardware watchpoint """ return self.dwt.remove_watchpoint(addr, size, type)
python
def remove_watchpoint(self, addr, size, type): """ remove a hardware watchpoint """ return self.dwt.remove_watchpoint(addr, size, type)
[ "def", "remove_watchpoint", "(", "self", ",", "addr", ",", "size", ",", "type", ")", ":", "return", "self", ".", "dwt", ".", "remove_watchpoint", "(", "addr", ",", "size", ",", "type", ")" ]
remove a hardware watchpoint
[ "remove", "a", "hardware", "watchpoint" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/coresight/cortex_m.py#L1205-L1209
train
214,998
mbedmicro/pyOCD
pyocd/target/builtin/target_CC3220SF.py
Flash_cc3220sf.init
def init(self): """ Download the flash algorithm in RAM """ self.target.halt() self.target.reset_and_halt() # update core register to execute the init subroutine result = self._call_function_and_wait(self.flash_algo['pc_init'], init=True) # check the return code if result != 0: logging.error('init error: %i', result) # erase the cookie which take up one page self.erase_sector(0x01000000) time.sleep(.5) #do a hardware reset which will put the pc looping in rom self.target.dp.reset() time.sleep(1.3) # reconnect to the board self.target.dp.init() self.target.dp.power_up_debug() self.target.halt() self.target.reset_and_halt() # update core register to execute the init subroutine result = self._call_function_and_wait(self.flash_algo['pc_init'], init=True) # check the return code if result != 0: logging.error('init error: %i', result)
python
def init(self): """ Download the flash algorithm in RAM """ self.target.halt() self.target.reset_and_halt() # update core register to execute the init subroutine result = self._call_function_and_wait(self.flash_algo['pc_init'], init=True) # check the return code if result != 0: logging.error('init error: %i', result) # erase the cookie which take up one page self.erase_sector(0x01000000) time.sleep(.5) #do a hardware reset which will put the pc looping in rom self.target.dp.reset() time.sleep(1.3) # reconnect to the board self.target.dp.init() self.target.dp.power_up_debug() self.target.halt() self.target.reset_and_halt() # update core register to execute the init subroutine result = self._call_function_and_wait(self.flash_algo['pc_init'], init=True) # check the return code if result != 0: logging.error('init error: %i', result)
[ "def", "init", "(", "self", ")", ":", "self", ".", "target", ".", "halt", "(", ")", "self", ".", "target", ".", "reset_and_halt", "(", ")", "# update core register to execute the init subroutine", "result", "=", "self", ".", "_call_function_and_wait", "(", "self...
Download the flash algorithm in RAM
[ "Download", "the", "flash", "algorithm", "in", "RAM" ]
41a174718a9739f3cbe785c2ba21cb7fd1310c6f
https://github.com/mbedmicro/pyOCD/blob/41a174718a9739f3cbe785c2ba21cb7fd1310c6f/pyocd/target/builtin/target_CC3220SF.py#L75-L111
train
214,999