id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
49,600
deontologician/restnavigator
restnavigator/halnav.py
Navigator.hal
def hal(root, apiname=None, default_curie=None, auth=None, headers=None, session=None, ): '''Create a HALNavigator''' root = utils.fix_scheme(root) halnav = HALNavigator( link=Link(uri=root), core...
python
def hal(root, apiname=None, default_curie=None, auth=None, headers=None, session=None, ): '''Create a HALNavigator''' root = utils.fix_scheme(root) halnav = HALNavigator( link=Link(uri=root), core...
[ "def", "hal", "(", "root", ",", "apiname", "=", "None", ",", "default_curie", "=", "None", ",", "auth", "=", "None", ",", "headers", "=", "None", ",", "session", "=", "None", ",", ")", ":", "root", "=", "utils", ".", "fix_scheme", "(", "root", ")",...
Create a HALNavigator
[ "Create", "a", "HALNavigator" ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L170-L194
49,601
deontologician/restnavigator
restnavigator/halnav.py
HALNavigatorBase.docsfor
def docsfor(self, rel): # pragma: nocover '''Obtains the documentation for a link relation. Opens in a webbrowser window''' prefix, _rel = rel.split(':') if prefix in self.curies: doc_url = uritemplate.expand(self.curies[prefix], {'rel': _rel}) else: doc_...
python
def docsfor(self, rel): # pragma: nocover '''Obtains the documentation for a link relation. Opens in a webbrowser window''' prefix, _rel = rel.split(':') if prefix in self.curies: doc_url = uritemplate.expand(self.curies[prefix], {'rel': _rel}) else: doc_...
[ "def", "docsfor", "(", "self", ",", "rel", ")", ":", "# pragma: nocover", "prefix", ",", "_rel", "=", "rel", ".", "split", "(", "':'", ")", "if", "prefix", "in", "self", ".", "curies", ":", "doc_url", "=", "uritemplate", ".", "expand", "(", "self", "...
Obtains the documentation for a link relation. Opens in a webbrowser window
[ "Obtains", "the", "documentation", "for", "a", "link", "relation", ".", "Opens", "in", "a", "webbrowser", "window" ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L373-L382
49,602
deontologician/restnavigator
restnavigator/halnav.py
HALNavigatorBase._make_links_from
def _make_links_from(self, body): '''Creates linked navigators from a HAL response body''' ld = utils.CurieDict(self._core.default_curie, {}) for rel, link in body.get('_links', {}).items(): if rel != 'curies': if isinstance(link, list): ld[rel] = ...
python
def _make_links_from(self, body): '''Creates linked navigators from a HAL response body''' ld = utils.CurieDict(self._core.default_curie, {}) for rel, link in body.get('_links', {}).items(): if rel != 'curies': if isinstance(link, list): ld[rel] = ...
[ "def", "_make_links_from", "(", "self", ",", "body", ")", ":", "ld", "=", "utils", ".", "CurieDict", "(", "self", ".", "_core", ".", "default_curie", ",", "{", "}", ")", "for", "rel", ",", "link", "in", "body", ".", "get", "(", "'_links'", ",", "{"...
Creates linked navigators from a HAL response body
[ "Creates", "linked", "navigators", "from", "a", "HAL", "response", "body" ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L384-L394
49,603
deontologician/restnavigator
restnavigator/halnav.py
HALNavigatorBase._make_embedded_from
def _make_embedded_from(self, doc): '''Creates embedded navigators from a HAL response doc''' ld = utils.CurieDict(self._core.default_curie, {}) for rel, doc in doc.get('_embedded', {}).items(): if isinstance(doc, list): ld[rel] = [self._recursively_embed(d) for d in ...
python
def _make_embedded_from(self, doc): '''Creates embedded navigators from a HAL response doc''' ld = utils.CurieDict(self._core.default_curie, {}) for rel, doc in doc.get('_embedded', {}).items(): if isinstance(doc, list): ld[rel] = [self._recursively_embed(d) for d in ...
[ "def", "_make_embedded_from", "(", "self", ",", "doc", ")", ":", "ld", "=", "utils", ".", "CurieDict", "(", "self", ".", "_core", ".", "default_curie", ",", "{", "}", ")", "for", "rel", ",", "doc", "in", "doc", ".", "get", "(", "'_embedded'", ",", ...
Creates embedded navigators from a HAL response doc
[ "Creates", "embedded", "navigators", "from", "a", "HAL", "response", "doc" ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L396-L404
49,604
deontologician/restnavigator
restnavigator/halnav.py
HALNavigatorBase._recursively_embed
def _recursively_embed(self, doc, update_state=True): '''Crafts a navigator from a hal-json embedded document''' self_link = None self_uri = utils.getpath(doc, '_links.self.href') if self_uri is not None: uri = urlparse.urljoin(self.uri, self_uri) self_link = Link...
python
def _recursively_embed(self, doc, update_state=True): '''Crafts a navigator from a hal-json embedded document''' self_link = None self_uri = utils.getpath(doc, '_links.self.href') if self_uri is not None: uri = urlparse.urljoin(self.uri, self_uri) self_link = Link...
[ "def", "_recursively_embed", "(", "self", ",", "doc", ",", "update_state", "=", "True", ")", ":", "self_link", "=", "None", "self_uri", "=", "utils", ".", "getpath", "(", "doc", ",", "'_links.self.href'", ")", "if", "self_uri", "is", "not", "None", ":", ...
Crafts a navigator from a hal-json embedded document
[ "Crafts", "a", "navigator", "from", "a", "hal", "-", "json", "embedded", "document" ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L406-L444
49,605
deontologician/restnavigator
restnavigator/halnav.py
HALNavigatorBase._navigator_or_thunk
def _navigator_or_thunk(self, link): '''Crafts a navigator or from a hal-json link dict. If the link is relative, the returned navigator will have a uri that relative to this navigator's uri. If the link passed in is templated, a PartialNavigator will be returned instead. ...
python
def _navigator_or_thunk(self, link): '''Crafts a navigator or from a hal-json link dict. If the link is relative, the returned navigator will have a uri that relative to this navigator's uri. If the link passed in is templated, a PartialNavigator will be returned instead. ...
[ "def", "_navigator_or_thunk", "(", "self", ",", "link", ")", ":", "# resolve relative uris against the current uri", "uri", "=", "urlparse", ".", "urljoin", "(", "self", ".", "uri", ",", "link", "[", "'href'", "]", ")", "link_obj", "=", "Link", "(", "uri", "...
Crafts a navigator or from a hal-json link dict. If the link is relative, the returned navigator will have a uri that relative to this navigator's uri. If the link passed in is templated, a PartialNavigator will be returned instead.
[ "Crafts", "a", "navigator", "or", "from", "a", "hal", "-", "json", "link", "dict", "." ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L447-L463
49,606
deontologician/restnavigator
restnavigator/halnav.py
HALNavigatorBase._can_parse
def _can_parse(self, content_type): '''Whether this navigator can parse the given content-type. Checks that the content_type matches one of the types specified in the 'Accept' header of the request, if supplied. If not supplied, matches against the default''' content_type, conten...
python
def _can_parse(self, content_type): '''Whether this navigator can parse the given content-type. Checks that the content_type matches one of the types specified in the 'Accept' header of the request, if supplied. If not supplied, matches against the default''' content_type, conten...
[ "def", "_can_parse", "(", "self", ",", "content_type", ")", ":", "content_type", ",", "content_subtype", ",", "content_param", "=", "utils", ".", "parse_media_type", "(", "content_type", ")", "for", "accepted", "in", "self", ".", "headers", ".", "get", "(", ...
Whether this navigator can parse the given content-type. Checks that the content_type matches one of the types specified in the 'Accept' header of the request, if supplied. If not supplied, matches against the default
[ "Whether", "this", "navigator", "can", "parse", "the", "given", "content", "-", "type", ".", "Checks", "that", "the", "content_type", "matches", "one", "of", "the", "types", "specified", "in", "the", "Accept", "header", "of", "the", "request", "if", "supplie...
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L465-L481
49,607
deontologician/restnavigator
restnavigator/halnav.py
HALNavigatorBase._parse_content
def _parse_content(self, text): '''Parses the content of a response doc into the correct format for .state. ''' try: return json.loads(text) except ValueError: raise exc.UnexpectedlyNotJSON( "The resource at {.uri} wasn't valid JSON", self)
python
def _parse_content(self, text): '''Parses the content of a response doc into the correct format for .state. ''' try: return json.loads(text) except ValueError: raise exc.UnexpectedlyNotJSON( "The resource at {.uri} wasn't valid JSON", self)
[ "def", "_parse_content", "(", "self", ",", "text", ")", ":", "try", ":", "return", "json", ".", "loads", "(", "text", ")", "except", "ValueError", ":", "raise", "exc", ".", "UnexpectedlyNotJSON", "(", "\"The resource at {.uri} wasn't valid JSON\"", ",", "self", ...
Parses the content of a response doc into the correct format for .state.
[ "Parses", "the", "content", "of", "a", "response", "doc", "into", "the", "correct", "format", "for", ".", "state", "." ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L483-L491
49,608
deontologician/restnavigator
restnavigator/halnav.py
HALNavigatorBase._update_self_link
def _update_self_link(self, link, headers): '''Update the self link of this navigator''' self.self.props.update(link) # Set the self.type to the content_type of the returned document self.self.props['type'] = headers.get( 'Content-Type', self.DEFAULT_CONTENT_TYPE) sel...
python
def _update_self_link(self, link, headers): '''Update the self link of this navigator''' self.self.props.update(link) # Set the self.type to the content_type of the returned document self.self.props['type'] = headers.get( 'Content-Type', self.DEFAULT_CONTENT_TYPE) sel...
[ "def", "_update_self_link", "(", "self", ",", "link", ",", "headers", ")", ":", "self", ".", "self", ".", "props", ".", "update", "(", "link", ")", "# Set the self.type to the content_type of the returned document", "self", ".", "self", ".", "props", "[", "'type...
Update the self link of this navigator
[ "Update", "the", "self", "link", "of", "this", "navigator" ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L493-L499
49,609
deontologician/restnavigator
restnavigator/halnav.py
HALNavigatorBase._ingest_response
def _ingest_response(self, response): '''Takes a response object and ingests state, links, embedded documents and updates the self link of this navigator to correspond. This will only work if the response is valid JSON ''' self.response = response if self._can_par...
python
def _ingest_response(self, response): '''Takes a response object and ingests state, links, embedded documents and updates the self link of this navigator to correspond. This will only work if the response is valid JSON ''' self.response = response if self._can_par...
[ "def", "_ingest_response", "(", "self", ",", "response", ")", ":", "self", ".", "response", "=", "response", "if", "self", ".", "_can_parse", "(", "response", ".", "headers", "[", "'Content-Type'", "]", ")", ":", "hal_json", "=", "self", ".", "_parse_conte...
Takes a response object and ingests state, links, embedded documents and updates the self link of this navigator to correspond. This will only work if the response is valid JSON
[ "Takes", "a", "response", "object", "and", "ingests", "state", "links", "embedded", "documents", "and", "updates", "the", "self", "link", "of", "this", "navigator", "to", "correspond", ".", "This", "will", "only", "work", "if", "the", "response", "is", "vali...
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L501-L532
49,610
deontologician/restnavigator
restnavigator/halnav.py
HALNavigator._create_navigator
def _create_navigator(self, response, raise_exc=True): '''Create the appropriate navigator from an api response''' method = response.request.method # TODO: refactor once hooks in place if method in (POST, PUT, PATCH, DELETE) \ and response.status_code in ( http...
python
def _create_navigator(self, response, raise_exc=True): '''Create the appropriate navigator from an api response''' method = response.request.method # TODO: refactor once hooks in place if method in (POST, PUT, PATCH, DELETE) \ and response.status_code in ( http...
[ "def", "_create_navigator", "(", "self", ",", "response", ",", "raise_exc", "=", "True", ")", ":", "method", "=", "response", ".", "request", ".", "method", "# TODO: refactor once hooks in place", "if", "method", "in", "(", "POST", ",", "PUT", ",", "PATCH", ...
Create the appropriate navigator from an api response
[ "Create", "the", "appropriate", "navigator", "from", "an", "api", "response" ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L544-L576
49,611
deontologician/restnavigator
restnavigator/halnav.py
HALNavigator._request
def _request(self, method, body=None, raise_exc=True, headers=None, files=None): '''Fetches HTTP response using the passed http method. Raises HALNavigatorError if response is in the 400-500 range.''' headers = headers or {} if body and 'Content-Type' not in headers: headers....
python
def _request(self, method, body=None, raise_exc=True, headers=None, files=None): '''Fetches HTTP response using the passed http method. Raises HALNavigatorError if response is in the 400-500 range.''' headers = headers or {} if body and 'Content-Type' not in headers: headers....
[ "def", "_request", "(", "self", ",", "method", ",", "body", "=", "None", ",", "raise_exc", "=", "True", ",", "headers", "=", "None", ",", "files", "=", "None", ")", ":", "headers", "=", "headers", "or", "{", "}", "if", "body", "and", "'Content-Type'"...
Fetches HTTP response using the passed http method. Raises HALNavigatorError if response is in the 400-500 range.
[ "Fetches", "HTTP", "response", "using", "the", "passed", "http", "method", ".", "Raises", "HALNavigatorError", "if", "response", "is", "in", "the", "400", "-", "500", "range", "." ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L578-L602
49,612
deontologician/restnavigator
restnavigator/halnav.py
HALNavigator.fetch
def fetch(self, raise_exc=True): '''Performs a GET request to the uri of this navigator''' self._request(GET, raise_exc=raise_exc) # ingests response self.fetched = True return self.state.copy()
python
def fetch(self, raise_exc=True): '''Performs a GET request to the uri of this navigator''' self._request(GET, raise_exc=raise_exc) # ingests response self.fetched = True return self.state.copy()
[ "def", "fetch", "(", "self", ",", "raise_exc", "=", "True", ")", ":", "self", ".", "_request", "(", "GET", ",", "raise_exc", "=", "raise_exc", ")", "# ingests response", "self", ".", "fetched", "=", "True", "return", "self", ".", "state", ".", "copy", ...
Performs a GET request to the uri of this navigator
[ "Performs", "a", "GET", "request", "to", "the", "uri", "of", "this", "navigator" ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L604-L608
49,613
deontologician/restnavigator
restnavigator/halnav.py
HALNavigator.create
def create(self, body=None, raise_exc=True, headers=None, **kwargs): '''Performs an HTTP POST to the server, to create a subordinate resource. Returns a new HALNavigator representing that resource. `body` may either be a string or a dictionary representing json `headers` are add...
python
def create(self, body=None, raise_exc=True, headers=None, **kwargs): '''Performs an HTTP POST to the server, to create a subordinate resource. Returns a new HALNavigator representing that resource. `body` may either be a string or a dictionary representing json `headers` are add...
[ "def", "create", "(", "self", ",", "body", "=", "None", ",", "raise_exc", "=", "True", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_request", "(", "POST", ",", "body", ",", "raise_exc", ",", "headers", ",...
Performs an HTTP POST to the server, to create a subordinate resource. Returns a new HALNavigator representing that resource. `body` may either be a string or a dictionary representing json `headers` are additional headers to send in the request
[ "Performs", "an", "HTTP", "POST", "to", "the", "server", "to", "create", "a", "subordinate", "resource", ".", "Returns", "a", "new", "HALNavigator", "representing", "that", "resource", "." ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L610-L618
49,614
deontologician/restnavigator
restnavigator/halnav.py
HALNavigator.upsert
def upsert(self, body, raise_exc=True, headers=False, files=None): '''Performs an HTTP PUT to the server. This is an idempotent call that will create the resource this navigator is pointing to, or will update it if it already exists. `body` may either be a string or a dictionary represe...
python
def upsert(self, body, raise_exc=True, headers=False, files=None): '''Performs an HTTP PUT to the server. This is an idempotent call that will create the resource this navigator is pointing to, or will update it if it already exists. `body` may either be a string or a dictionary represe...
[ "def", "upsert", "(", "self", ",", "body", ",", "raise_exc", "=", "True", ",", "headers", "=", "False", ",", "files", "=", "None", ")", ":", "return", "self", ".", "_request", "(", "PUT", ",", "body", ",", "raise_exc", ",", "headers", ",", "files", ...
Performs an HTTP PUT to the server. This is an idempotent call that will create the resource this navigator is pointing to, or will update it if it already exists. `body` may either be a string or a dictionary representing json `headers` are additional headers to send in the request
[ "Performs", "an", "HTTP", "PUT", "to", "the", "server", ".", "This", "is", "an", "idempotent", "call", "that", "will", "create", "the", "resource", "this", "navigator", "is", "pointing", "to", "or", "will", "update", "it", "if", "it", "already", "exists", ...
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L627-L635
49,615
deontologician/restnavigator
restnavigator/halnav.py
HALNavigator.patch
def patch(self, body, raise_exc=True, headers=False, files=None): '''Performs an HTTP PATCH to the server. This is a non-idempotent call that may update all or a portion of the resource this navigator is pointing to. The format of the patch body is up to implementations. `body` ...
python
def patch(self, body, raise_exc=True, headers=False, files=None): '''Performs an HTTP PATCH to the server. This is a non-idempotent call that may update all or a portion of the resource this navigator is pointing to. The format of the patch body is up to implementations. `body` ...
[ "def", "patch", "(", "self", ",", "body", ",", "raise_exc", "=", "True", ",", "headers", "=", "False", ",", "files", "=", "None", ")", ":", "return", "self", ".", "_request", "(", "PATCH", ",", "body", ",", "raise_exc", ",", "headers", ",", "files", ...
Performs an HTTP PATCH to the server. This is a non-idempotent call that may update all or a portion of the resource this navigator is pointing to. The format of the patch body is up to implementations. `body` may either be a string or a dictionary representing json `headers` ar...
[ "Performs", "an", "HTTP", "PATCH", "to", "the", "server", ".", "This", "is", "a", "non", "-", "idempotent", "call", "that", "may", "update", "all", "or", "a", "portion", "of", "the", "resource", "this", "navigator", "is", "pointing", "to", ".", "The", ...
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L637-L646
49,616
deontologician/restnavigator
restnavigator/halnav.py
OrphanHALNavigator._parse_content
def _parse_content(self, text): '''Try to parse as HAL, but on failure use an empty dict''' try: return super(OrphanHALNavigator, self)._parse_content(text) except exc.UnexpectedlyNotJSON: return {}
python
def _parse_content(self, text): '''Try to parse as HAL, but on failure use an empty dict''' try: return super(OrphanHALNavigator, self)._parse_content(text) except exc.UnexpectedlyNotJSON: return {}
[ "def", "_parse_content", "(", "self", ",", "text", ")", ":", "try", ":", "return", "super", "(", "OrphanHALNavigator", ",", "self", ")", ".", "_parse_content", "(", "text", ")", "except", "exc", ".", "UnexpectedlyNotJSON", ":", "return", "{", "}" ]
Try to parse as HAL, but on failure use an empty dict
[ "Try", "to", "parse", "as", "HAL", "but", "on", "failure", "use", "an", "empty", "dict" ]
453b9de4e70e602009d3e3ffafcf77d23c8b07c5
https://github.com/deontologician/restnavigator/blob/453b9de4e70e602009d3e3ffafcf77d23c8b07c5/restnavigator/halnav.py#L682-L687
49,617
NICTA/revrand
revrand/mathfun/special.py
logsumexp
def logsumexp(X, axis=0): """ Log-sum-exp trick for matrix X for summation along a specified axis. This performs the following operation in a stable fashion, .. math:: \log \sum^K_{k=1} \exp\{x_k\} Parameters ---------- X: ndarray 2D array of shape (N, D) to apply...
python
def logsumexp(X, axis=0): """ Log-sum-exp trick for matrix X for summation along a specified axis. This performs the following operation in a stable fashion, .. math:: \log \sum^K_{k=1} \exp\{x_k\} Parameters ---------- X: ndarray 2D array of shape (N, D) to apply...
[ "def", "logsumexp", "(", "X", ",", "axis", "=", "0", ")", ":", "mx", "=", "X", ".", "max", "(", "axis", "=", "axis", ")", "if", "(", "X", ".", "ndim", ">", "1", ")", ":", "mx", "=", "np", ".", "atleast_2d", "(", "mx", ")", ".", "T", "if",...
Log-sum-exp trick for matrix X for summation along a specified axis. This performs the following operation in a stable fashion, .. math:: \log \sum^K_{k=1} \exp\{x_k\} Parameters ---------- X: ndarray 2D array of shape (N, D) to apply the log-sum-exp trick. axis: ...
[ "Log", "-", "sum", "-", "exp", "trick", "for", "matrix", "X", "for", "summation", "along", "a", "specified", "axis", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/mathfun/special.py#L22-L51
49,618
NICTA/revrand
revrand/mathfun/special.py
softmax
def softmax(X, axis=0): """ Pass X through a softmax function in a numerically stable way using the log-sum-exp trick. This transformation is: .. math:: \\frac{\exp\{X_k\}}{\sum^K_{j=1} \exp\{X_j\}} and is appliedx to each row/column, `k`, of X. Parameters ---------- ...
python
def softmax(X, axis=0): """ Pass X through a softmax function in a numerically stable way using the log-sum-exp trick. This transformation is: .. math:: \\frac{\exp\{X_k\}}{\sum^K_{j=1} \exp\{X_j\}} and is appliedx to each row/column, `k`, of X. Parameters ---------- ...
[ "def", "softmax", "(", "X", ",", "axis", "=", "0", ")", ":", "if", "axis", "==", "1", ":", "return", "np", ".", "exp", "(", "X", "-", "logsumexp", "(", "X", ",", "axis", "=", "1", ")", "[", ":", ",", "np", ".", "newaxis", "]", ")", "elif", ...
Pass X through a softmax function in a numerically stable way using the log-sum-exp trick. This transformation is: .. math:: \\frac{\exp\{X_k\}}{\sum^K_{j=1} \exp\{X_j\}} and is appliedx to each row/column, `k`, of X. Parameters ---------- X: ndarray 2D array of ...
[ "Pass", "X", "through", "a", "softmax", "function", "in", "a", "numerically", "stable", "way", "using", "the", "log", "-", "sum", "-", "exp", "trick", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/mathfun/special.py#L54-L88
49,619
joshleeb/creditcard
creditcard/formatter.py
is_visa
def is_visa(n): """Checks if credit card number fits the visa format.""" n, length = str(n), len(str(n)) if length >= 13 and length <= 16: if n[0] == '4': return True return False
python
def is_visa(n): """Checks if credit card number fits the visa format.""" n, length = str(n), len(str(n)) if length >= 13 and length <= 16: if n[0] == '4': return True return False
[ "def", "is_visa", "(", "n", ")", ":", "n", ",", "length", "=", "str", "(", "n", ")", ",", "len", "(", "str", "(", "n", ")", ")", "if", "length", ">=", "13", "and", "length", "<=", "16", ":", "if", "n", "[", "0", "]", "==", "'4'", ":", "re...
Checks if credit card number fits the visa format.
[ "Checks", "if", "credit", "card", "number", "fits", "the", "visa", "format", "." ]
8cff49ba80029026c7e221764eb2387eb2e04a4c
https://github.com/joshleeb/creditcard/blob/8cff49ba80029026c7e221764eb2387eb2e04a4c/creditcard/formatter.py#L1-L8
49,620
joshleeb/creditcard
creditcard/formatter.py
is_visa_electron
def is_visa_electron(n): """Checks if credit card number fits the visa electron format.""" n, length = str(n), len(str(n)) form = ['026', '508', '844', '913', '917'] if length == 16: if n[0] == '4': if ''.join(n[1:4]) in form or ''.join(n[1:6]) == '17500': return Tru...
python
def is_visa_electron(n): """Checks if credit card number fits the visa electron format.""" n, length = str(n), len(str(n)) form = ['026', '508', '844', '913', '917'] if length == 16: if n[0] == '4': if ''.join(n[1:4]) in form or ''.join(n[1:6]) == '17500': return Tru...
[ "def", "is_visa_electron", "(", "n", ")", ":", "n", ",", "length", "=", "str", "(", "n", ")", ",", "len", "(", "str", "(", "n", ")", ")", "form", "=", "[", "'026'", ",", "'508'", ",", "'844'", ",", "'913'", ",", "'917'", "]", "if", "length", ...
Checks if credit card number fits the visa electron format.
[ "Checks", "if", "credit", "card", "number", "fits", "the", "visa", "electron", "format", "." ]
8cff49ba80029026c7e221764eb2387eb2e04a4c
https://github.com/joshleeb/creditcard/blob/8cff49ba80029026c7e221764eb2387eb2e04a4c/creditcard/formatter.py#L11-L20
49,621
joshleeb/creditcard
creditcard/formatter.py
is_mastercard
def is_mastercard(n): """Checks if credit card number fits the mastercard format.""" n, length = str(n), len(str(n)) if length >= 16 and length <= 19: if ''.join(n[:2]) in strings_between(51, 56): return True return False
python
def is_mastercard(n): """Checks if credit card number fits the mastercard format.""" n, length = str(n), len(str(n)) if length >= 16 and length <= 19: if ''.join(n[:2]) in strings_between(51, 56): return True return False
[ "def", "is_mastercard", "(", "n", ")", ":", "n", ",", "length", "=", "str", "(", "n", ")", ",", "len", "(", "str", "(", "n", ")", ")", "if", "length", ">=", "16", "and", "length", "<=", "19", ":", "if", "''", ".", "join", "(", "n", "[", ":"...
Checks if credit card number fits the mastercard format.
[ "Checks", "if", "credit", "card", "number", "fits", "the", "mastercard", "format", "." ]
8cff49ba80029026c7e221764eb2387eb2e04a4c
https://github.com/joshleeb/creditcard/blob/8cff49ba80029026c7e221764eb2387eb2e04a4c/creditcard/formatter.py#L23-L30
49,622
joshleeb/creditcard
creditcard/formatter.py
is_amex
def is_amex(n): """Checks if credit card number fits the american express format.""" n, length = str(n), len(str(n)) if length == 15: if n[0] == '3' and (n[1] == '4' or n[1] == '7'): return True return False
python
def is_amex(n): """Checks if credit card number fits the american express format.""" n, length = str(n), len(str(n)) if length == 15: if n[0] == '3' and (n[1] == '4' or n[1] == '7'): return True return False
[ "def", "is_amex", "(", "n", ")", ":", "n", ",", "length", "=", "str", "(", "n", ")", ",", "len", "(", "str", "(", "n", ")", ")", "if", "length", "==", "15", ":", "if", "n", "[", "0", "]", "==", "'3'", "and", "(", "n", "[", "1", "]", "==...
Checks if credit card number fits the american express format.
[ "Checks", "if", "credit", "card", "number", "fits", "the", "american", "express", "format", "." ]
8cff49ba80029026c7e221764eb2387eb2e04a4c
https://github.com/joshleeb/creditcard/blob/8cff49ba80029026c7e221764eb2387eb2e04a4c/creditcard/formatter.py#L33-L40
49,623
joshleeb/creditcard
creditcard/formatter.py
is_discover
def is_discover(n): """Checks if credit card number fits the discover card format.""" n, length = str(n), len(str(n)) if length == 16: if n[0] == '6': if ''.join(n[1:4]) == '011' or n[1] == '5': return True elif n[1] == '4' and n[2] in strings_between(4, 10):...
python
def is_discover(n): """Checks if credit card number fits the discover card format.""" n, length = str(n), len(str(n)) if length == 16: if n[0] == '6': if ''.join(n[1:4]) == '011' or n[1] == '5': return True elif n[1] == '4' and n[2] in strings_between(4, 10):...
[ "def", "is_discover", "(", "n", ")", ":", "n", ",", "length", "=", "str", "(", "n", ")", ",", "len", "(", "str", "(", "n", ")", ")", "if", "length", "==", "16", ":", "if", "n", "[", "0", "]", "==", "'6'", ":", "if", "''", ".", "join", "("...
Checks if credit card number fits the discover card format.
[ "Checks", "if", "credit", "card", "number", "fits", "the", "discover", "card", "format", "." ]
8cff49ba80029026c7e221764eb2387eb2e04a4c
https://github.com/joshleeb/creditcard/blob/8cff49ba80029026c7e221764eb2387eb2e04a4c/creditcard/formatter.py#L55-L67
49,624
joshleeb/creditcard
creditcard/formatter.py
get_format
def get_format(n): """Gets a list of the formats a credit card number fits.""" formats = [] if is_visa(n): formats.append('visa') if is_visa_electron(n): formats.append('visa electron') if is_mastercard(n): formats.append('mastercard') if is_amex(n): formats.appe...
python
def get_format(n): """Gets a list of the formats a credit card number fits.""" formats = [] if is_visa(n): formats.append('visa') if is_visa_electron(n): formats.append('visa electron') if is_mastercard(n): formats.append('mastercard') if is_amex(n): formats.appe...
[ "def", "get_format", "(", "n", ")", ":", "formats", "=", "[", "]", "if", "is_visa", "(", "n", ")", ":", "formats", ".", "append", "(", "'visa'", ")", "if", "is_visa_electron", "(", "n", ")", ":", "formats", ".", "append", "(", "'visa electron'", ")",...
Gets a list of the formats a credit card number fits.
[ "Gets", "a", "list", "of", "the", "formats", "a", "credit", "card", "number", "fits", "." ]
8cff49ba80029026c7e221764eb2387eb2e04a4c
https://github.com/joshleeb/creditcard/blob/8cff49ba80029026c7e221764eb2387eb2e04a4c/creditcard/formatter.py#L70-L87
49,625
rtfd/sphinxcontrib-dotnetdomain
sphinxcontrib/dotnetdomain.py
DotNetSignature.full_name
def full_name(self): """Return full name of member""" if self.prefix is not None: return '.'.join([self.prefix, self.member]) return self.member
python
def full_name(self): """Return full name of member""" if self.prefix is not None: return '.'.join([self.prefix, self.member]) return self.member
[ "def", "full_name", "(", "self", ")", ":", "if", "self", ".", "prefix", "is", "not", "None", ":", "return", "'.'", ".", "join", "(", "[", "self", ".", "prefix", ",", "self", ".", "member", "]", ")", "return", "self", ".", "member" ]
Return full name of member
[ "Return", "full", "name", "of", "member" ]
fbc6a81b9993dc5d06866c4483593421b53b9a61
https://github.com/rtfd/sphinxcontrib-dotnetdomain/blob/fbc6a81b9993dc5d06866c4483593421b53b9a61/sphinxcontrib/dotnetdomain.py#L70-L74
49,626
rtfd/sphinxcontrib-dotnetdomain
sphinxcontrib/dotnetdomain.py
DotNetObject.parse_signature
def parse_signature(cls, signature): """Parse signature declartion string Uses :py:attr:`signature_pattern` to parse out pieces of constraint signatures. Pattern should provide the following named groups: prefix Object prefix, such as a namespace member...
python
def parse_signature(cls, signature): """Parse signature declartion string Uses :py:attr:`signature_pattern` to parse out pieces of constraint signatures. Pattern should provide the following named groups: prefix Object prefix, such as a namespace member...
[ "def", "parse_signature", "(", "cls", ",", "signature", ")", ":", "assert", "cls", ".", "signature_pattern", "is", "not", "None", "pattern", "=", "re", ".", "compile", "(", "cls", ".", "signature_pattern", ",", "re", ".", "VERBOSE", ")", "match", "=", "p...
Parse signature declartion string Uses :py:attr:`signature_pattern` to parse out pieces of constraint signatures. Pattern should provide the following named groups: prefix Object prefix, such as a namespace member Object member name ...
[ "Parse", "signature", "declartion", "string" ]
fbc6a81b9993dc5d06866c4483593421b53b9a61
https://github.com/rtfd/sphinxcontrib-dotnetdomain/blob/fbc6a81b9993dc5d06866c4483593421b53b9a61/sphinxcontrib/dotnetdomain.py#L119-L150
49,627
rtfd/sphinxcontrib-dotnetdomain
sphinxcontrib/dotnetdomain.py
DotNetObject.handle_signature
def handle_signature(self, sig, signode): """Parses out pieces from construct signatures Parses out prefix and argument list from construct definition. This is assuming that the .NET languages this will support will be in a common format, such as:: Namespace.Class.method(ar...
python
def handle_signature(self, sig, signode): """Parses out pieces from construct signatures Parses out prefix and argument list from construct definition. This is assuming that the .NET languages this will support will be in a common format, such as:: Namespace.Class.method(ar...
[ "def", "handle_signature", "(", "self", ",", "sig", ",", "signode", ")", ":", "try", ":", "sig", "=", "self", ".", "parse_signature", "(", "sig", ".", "strip", "(", ")", ")", "except", "ValueError", ":", "self", ".", "env", ".", "warn", "(", "self", ...
Parses out pieces from construct signatures Parses out prefix and argument list from construct definition. This is assuming that the .NET languages this will support will be in a common format, such as:: Namespace.Class.method(argument, argument, ...) The namespace and cla...
[ "Parses", "out", "pieces", "from", "construct", "signatures" ]
fbc6a81b9993dc5d06866c4483593421b53b9a61
https://github.com/rtfd/sphinxcontrib-dotnetdomain/blob/fbc6a81b9993dc5d06866c4483593421b53b9a61/sphinxcontrib/dotnetdomain.py#L152-L208
49,628
rtfd/sphinxcontrib-dotnetdomain
sphinxcontrib/dotnetdomain.py
DotNetObject.add_target_and_index
def add_target_and_index(self, name, sig, signode): """Add objects to the domain list of objects This uses the directive short name along with the full object name to create objects and nodes that are type and name unique. """ full_name = name[0] target_name = '{0}-{1}'....
python
def add_target_and_index(self, name, sig, signode): """Add objects to the domain list of objects This uses the directive short name along with the full object name to create objects and nodes that are type and name unique. """ full_name = name[0] target_name = '{0}-{1}'....
[ "def", "add_target_and_index", "(", "self", ",", "name", ",", "sig", ",", "signode", ")", ":", "full_name", "=", "name", "[", "0", "]", "target_name", "=", "'{0}-{1}'", ".", "format", "(", "self", ".", "short_name", ",", "full_name", ")", "if", "target_n...
Add objects to the domain list of objects This uses the directive short name along with the full object name to create objects and nodes that are type and name unique.
[ "Add", "objects", "to", "the", "domain", "list", "of", "objects" ]
fbc6a81b9993dc5d06866c4483593421b53b9a61
https://github.com/rtfd/sphinxcontrib-dotnetdomain/blob/fbc6a81b9993dc5d06866c4483593421b53b9a61/sphinxcontrib/dotnetdomain.py#L210-L245
49,629
rtfd/sphinxcontrib-dotnetdomain
sphinxcontrib/dotnetdomain.py
DotNetObject.get_index_text
def get_index_text(self, prefix, name_obj): """Produce index text by directive attributes""" (name, _) = name_obj msg = '{name} ({obj_type})' parts = { 'name': name, 'prefix': prefix, 'obj_type': self.long_name, } try: (obj_...
python
def get_index_text(self, prefix, name_obj): """Produce index text by directive attributes""" (name, _) = name_obj msg = '{name} ({obj_type})' parts = { 'name': name, 'prefix': prefix, 'obj_type': self.long_name, } try: (obj_...
[ "def", "get_index_text", "(", "self", ",", "prefix", ",", "name_obj", ")", ":", "(", "name", ",", "_", ")", "=", "name_obj", "msg", "=", "'{name} ({obj_type})'", "parts", "=", "{", "'name'", ":", "name", ",", "'prefix'", ":", "prefix", ",", "'obj_type'",...
Produce index text by directive attributes
[ "Produce", "index", "text", "by", "directive", "attributes" ]
fbc6a81b9993dc5d06866c4483593421b53b9a61
https://github.com/rtfd/sphinxcontrib-dotnetdomain/blob/fbc6a81b9993dc5d06866c4483593421b53b9a61/sphinxcontrib/dotnetdomain.py#L247-L264
49,630
rtfd/sphinxcontrib-dotnetdomain
sphinxcontrib/dotnetdomain.py
DotNetObjectNested.run
def run(self): """If element is considered hidden, drop the desc_signature node The default handling of signatures by :py:cls:`ObjectDescription` returns a list of nodes with the signature nodes. We are going to remove them if this is a hidden declaration. """ nodes = su...
python
def run(self): """If element is considered hidden, drop the desc_signature node The default handling of signatures by :py:cls:`ObjectDescription` returns a list of nodes with the signature nodes. We are going to remove them if this is a hidden declaration. """ nodes = su...
[ "def", "run", "(", "self", ")", ":", "nodes", "=", "super", "(", "DotNetObjectNested", ",", "self", ")", ".", "run", "(", ")", "if", "'hidden'", "in", "self", ".", "options", ":", "for", "node", "in", "nodes", ":", "if", "isinstance", "(", "node", ...
If element is considered hidden, drop the desc_signature node The default handling of signatures by :py:cls:`ObjectDescription` returns a list of nodes with the signature nodes. We are going to remove them if this is a hidden declaration.
[ "If", "element", "is", "considered", "hidden", "drop", "the", "desc_signature", "node" ]
fbc6a81b9993dc5d06866c4483593421b53b9a61
https://github.com/rtfd/sphinxcontrib-dotnetdomain/blob/fbc6a81b9993dc5d06866c4483593421b53b9a61/sphinxcontrib/dotnetdomain.py#L285-L299
49,631
rtfd/sphinxcontrib-dotnetdomain
sphinxcontrib/dotnetdomain.py
DotNetObjectNested.before_content
def before_content(self): """Build up prefix history for nested elements The following keys are used in :py:attr:`self.env.ref_context`: dn:prefixes Stores the prefix history. With each nested element, we add the prefix to a list of prefixes. When we exit th...
python
def before_content(self): """Build up prefix history for nested elements The following keys are used in :py:attr:`self.env.ref_context`: dn:prefixes Stores the prefix history. With each nested element, we add the prefix to a list of prefixes. When we exit th...
[ "def", "before_content", "(", "self", ")", ":", "super", "(", "DotNetObjectNested", ",", "self", ")", ".", "before_content", "(", ")", "if", "self", ".", "names", ":", "(", "_", ",", "prefix", ")", "=", "self", ".", "names", ".", "pop", "(", ")", "...
Build up prefix history for nested elements The following keys are used in :py:attr:`self.env.ref_context`: dn:prefixes Stores the prefix history. With each nested element, we add the prefix to a list of prefixes. When we exit that object's nesting l...
[ "Build", "up", "prefix", "history", "for", "nested", "elements" ]
fbc6a81b9993dc5d06866c4483593421b53b9a61
https://github.com/rtfd/sphinxcontrib-dotnetdomain/blob/fbc6a81b9993dc5d06866c4483593421b53b9a61/sphinxcontrib/dotnetdomain.py#L301-L324
49,632
rtfd/sphinxcontrib-dotnetdomain
sphinxcontrib/dotnetdomain.py
DotNetXRefRole.process_link
def process_link(self, env, refnode, has_explicit_title, title, target): """This handles some special cases for reference links in .NET First, the standard Sphinx reference syntax of ``:ref:`Title<Link>```, where a reference to ``Link`` is created with title ``Title``, causes problems f...
python
def process_link(self, env, refnode, has_explicit_title, title, target): """This handles some special cases for reference links in .NET First, the standard Sphinx reference syntax of ``:ref:`Title<Link>```, where a reference to ``Link`` is created with title ``Title``, causes problems f...
[ "def", "process_link", "(", "self", ",", "env", ",", "refnode", ",", "has_explicit_title", ",", "title", ",", "target", ")", ":", "result", "=", "super", "(", "DotNetXRefRole", ",", "self", ")", ".", "process_link", "(", "env", ",", "refnode", ",", "has_...
This handles some special cases for reference links in .NET First, the standard Sphinx reference syntax of ``:ref:`Title<Link>```, where a reference to ``Link`` is created with title ``Title``, causes problems for the generic .NET syntax of ``:dn:cls:`FooBar<T>```. So, here we assume th...
[ "This", "handles", "some", "special", "cases", "for", "reference", "links", "in", ".", "NET" ]
fbc6a81b9993dc5d06866c4483593421b53b9a61
https://github.com/rtfd/sphinxcontrib-dotnetdomain/blob/fbc6a81b9993dc5d06866c4483593421b53b9a61/sphinxcontrib/dotnetdomain.py#L572-L603
49,633
rtfd/sphinxcontrib-dotnetdomain
sphinxcontrib/dotnetdomain.py
DotNetDomain.find_obj
def find_obj(self, env, prefix, name, obj_type, searchorder=0): """Find object reference :param env: Build environment :param prefix: Object prefix :param name: Object name :param obj_type: Object type :param searchorder: Search for exact match """ # Skip...
python
def find_obj(self, env, prefix, name, obj_type, searchorder=0): """Find object reference :param env: Build environment :param prefix: Object prefix :param name: Object name :param obj_type: Object type :param searchorder: Search for exact match """ # Skip...
[ "def", "find_obj", "(", "self", ",", "env", ",", "prefix", ",", "name", ",", "obj_type", ",", "searchorder", "=", "0", ")", ":", "# Skip parens", "if", "name", "[", "-", "2", ":", "]", "==", "'()'", ":", "name", "=", "name", "[", ":", "-", "2", ...
Find object reference :param env: Build environment :param prefix: Object prefix :param name: Object name :param obj_type: Object type :param searchorder: Search for exact match
[ "Find", "object", "reference" ]
fbc6a81b9993dc5d06866c4483593421b53b9a61
https://github.com/rtfd/sphinxcontrib-dotnetdomain/blob/fbc6a81b9993dc5d06866c4483593421b53b9a61/sphinxcontrib/dotnetdomain.py#L715-L761
49,634
rtfd/sphinxcontrib-dotnetdomain
sphinxcontrib/dotnetdomain.py
DotNetDomain.resolve_any_xref
def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): """Look for any references, without object type This always searches in "refspecific" mode """ prefix = node.get('dn:prefix') results = [] match = self.find_obj(env, ...
python
def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): """Look for any references, without object type This always searches in "refspecific" mode """ prefix = node.get('dn:prefix') results = [] match = self.find_obj(env, ...
[ "def", "resolve_any_xref", "(", "self", ",", "env", ",", "fromdocname", ",", "builder", ",", "target", ",", "node", ",", "contnode", ")", ":", "prefix", "=", "node", ".", "get", "(", "'dn:prefix'", ")", "results", "=", "[", "]", "match", "=", "self", ...
Look for any references, without object type This always searches in "refspecific" mode
[ "Look", "for", "any", "references", "without", "object", "type" ]
fbc6a81b9993dc5d06866c4483593421b53b9a61
https://github.com/rtfd/sphinxcontrib-dotnetdomain/blob/fbc6a81b9993dc5d06866c4483593421b53b9a61/sphinxcontrib/dotnetdomain.py#L782-L797
49,635
dead-beef/markovchain
markovchain/image/type.py
ImageType.create
def create(self, width, height): """Create an image of type. Parameters ---------- width: `int` Image width. height: `int` Image height. Returns ------- `PIL.Image.Image` """ return Image.new(self.mode, (width, hei...
python
def create(self, width, height): """Create an image of type. Parameters ---------- width: `int` Image width. height: `int` Image height. Returns ------- `PIL.Image.Image` """ return Image.new(self.mode, (width, hei...
[ "def", "create", "(", "self", ",", "width", ",", "height", ")", ":", "return", "Image", ".", "new", "(", "self", ".", "mode", ",", "(", "width", ",", "height", ")", ")" ]
Create an image of type. Parameters ---------- width: `int` Image width. height: `int` Image height. Returns ------- `PIL.Image.Image`
[ "Create", "an", "image", "of", "type", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/image/type.py#L43-L57
49,636
dead-beef/markovchain
markovchain/image/type.py
ImageType.merge
def merge(self, imgs): """Merge image channels. Parameters ---------- imgs : `list` of `PIL.Image.Image` Returns ------- `PIL.Image.Image` Raises ------ ValueError If image channel list is empty. """ if not im...
python
def merge(self, imgs): """Merge image channels. Parameters ---------- imgs : `list` of `PIL.Image.Image` Returns ------- `PIL.Image.Image` Raises ------ ValueError If image channel list is empty. """ if not im...
[ "def", "merge", "(", "self", ",", "imgs", ")", ":", "if", "not", "imgs", ":", "raise", "ValueError", "(", "'empty channel list'", ")", "if", "len", "(", "imgs", ")", "==", "1", ":", "return", "imgs", "[", "0", "]", "return", "Image", ".", "merge", ...
Merge image channels. Parameters ---------- imgs : `list` of `PIL.Image.Image` Returns ------- `PIL.Image.Image` Raises ------ ValueError If image channel list is empty.
[ "Merge", "image", "channels", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/image/type.py#L77-L97
49,637
faide/py3o.template
py3o/template/main.py
detect_keep_boundary
def detect_keep_boundary(start, end, namespaces): """a helper to inspect a link and see if we should keep the link boundary """ result_start, result_end = False, False parent_start = start.getparent() parent_end = end.getparent() if parent_start.tag == "{%s}p" % namespaces['text']: # mo...
python
def detect_keep_boundary(start, end, namespaces): """a helper to inspect a link and see if we should keep the link boundary """ result_start, result_end = False, False parent_start = start.getparent() parent_end = end.getparent() if parent_start.tag == "{%s}p" % namespaces['text']: # mo...
[ "def", "detect_keep_boundary", "(", "start", ",", "end", ",", "namespaces", ")", ":", "result_start", ",", "result_end", "=", "False", ",", "False", "parent_start", "=", "start", ".", "getparent", "(", ")", "parent_end", "=", "end", ".", "getparent", "(", ...
a helper to inspect a link and see if we should keep the link boundary
[ "a", "helper", "to", "inspect", "a", "link", "and", "see", "if", "we", "should", "keep", "the", "link", "boundary" ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L49-L66
49,638
faide/py3o.template
py3o/template/main.py
Template.__prepare_namespaces
def __prepare_namespaces(self): """create proper namespaces for our document """ # create needed namespaces self.namespaces = dict( text="urn:text", draw="urn:draw", table="urn:table", office="urn:office", xlink="urn:xlink", ...
python
def __prepare_namespaces(self): """create proper namespaces for our document """ # create needed namespaces self.namespaces = dict( text="urn:text", draw="urn:draw", table="urn:table", office="urn:office", xlink="urn:xlink", ...
[ "def", "__prepare_namespaces", "(", "self", ")", ":", "# create needed namespaces", "self", ".", "namespaces", "=", "dict", "(", "text", "=", "\"urn:text\"", ",", "draw", "=", "\"urn:draw\"", ",", "table", "=", "\"urn:table\"", ",", "office", "=", "\"urn:office\...
create proper namespaces for our document
[ "create", "proper", "namespaces", "for", "our", "document" ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L208-L232
49,639
faide/py3o.template
py3o/template/main.py
Template.get_user_instructions
def get_user_instructions(self): """ Public method to help report engine to find all instructions """ res = [] # TODO: Check if instructions can be stored in other content_trees for e in get_instructions(self.content_trees[0], self.namespaces): childs = e.getchildren(...
python
def get_user_instructions(self): """ Public method to help report engine to find all instructions """ res = [] # TODO: Check if instructions can be stored in other content_trees for e in get_instructions(self.content_trees[0], self.namespaces): childs = e.getchildren(...
[ "def", "get_user_instructions", "(", "self", ")", ":", "res", "=", "[", "]", "# TODO: Check if instructions can be stored in other content_trees", "for", "e", "in", "get_instructions", "(", "self", ".", "content_trees", "[", "0", "]", ",", "self", ".", "namespaces",...
Public method to help report engine to find all instructions
[ "Public", "method", "to", "help", "report", "engine", "to", "find", "all", "instructions" ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L234-L245
49,640
faide/py3o.template
py3o/template/main.py
Template.get_user_instructions_mapping
def get_user_instructions_mapping(self): """ Public method to get the mapping of all variables defined in the template """ instructions = self.get_user_instructions() user_variables = self.get_user_variables() # For now we just want for loops instructions = [i fo...
python
def get_user_instructions_mapping(self): """ Public method to get the mapping of all variables defined in the template """ instructions = self.get_user_instructions() user_variables = self.get_user_variables() # For now we just want for loops instructions = [i fo...
[ "def", "get_user_instructions_mapping", "(", "self", ")", ":", "instructions", "=", "self", ".", "get_user_instructions", "(", ")", "user_variables", "=", "self", ".", "get_user_variables", "(", ")", "# For now we just want for loops", "instructions", "=", "[", "i", ...
Public method to get the mapping of all variables defined in the template
[ "Public", "method", "to", "get", "the", "mapping", "of", "all", "variables", "defined", "in", "the", "template" ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L252-L299
49,641
faide/py3o.template
py3o/template/main.py
Template.handle_link
def handle_link(self, link, py3o_base, closing_link): """transform a py3o link into a proper Genshi statement rebase a py3o link at a proper place in the tree to be ready for Genshi replacement """ # OLD open office version if link.text is not None and link.text.strip(): ...
python
def handle_link(self, link, py3o_base, closing_link): """transform a py3o link into a proper Genshi statement rebase a py3o link at a proper place in the tree to be ready for Genshi replacement """ # OLD open office version if link.text is not None and link.text.strip(): ...
[ "def", "handle_link", "(", "self", ",", "link", ",", "py3o_base", ",", "closing_link", ")", ":", "# OLD open office version", "if", "link", ".", "text", "is", "not", "None", "and", "link", ".", "text", ".", "strip", "(", ")", ":", "if", "not", "link", ...
transform a py3o link into a proper Genshi statement rebase a py3o link at a proper place in the tree to be ready for Genshi replacement
[ "transform", "a", "py3o", "link", "into", "a", "proper", "Genshi", "statement", "rebase", "a", "py3o", "link", "at", "a", "proper", "place", "in", "the", "tree", "to", "be", "ready", "for", "Genshi", "replacement" ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L329-L412
49,642
faide/py3o.template
py3o/template/main.py
Template.get_user_variables
def get_user_variables(self): """a public method to help report engines to introspect a template and find what data it needs and how it will be used returns a list of user variable names without starting 'py3o.'""" # TODO: Check if some user fields are stored in other content_tre...
python
def get_user_variables(self): """a public method to help report engines to introspect a template and find what data it needs and how it will be used returns a list of user variable names without starting 'py3o.'""" # TODO: Check if some user fields are stored in other content_tre...
[ "def", "get_user_variables", "(", "self", ")", ":", "# TODO: Check if some user fields are stored in other content_trees", "return", "[", "e", ".", "get", "(", "'{%s}name'", "%", "e", ".", "nsmap", ".", "get", "(", "'text'", ")", ")", "[", "5", ":", "]", "for"...
a public method to help report engines to introspect a template and find what data it needs and how it will be used returns a list of user variable names without starting 'py3o.
[ "a", "public", "method", "to", "help", "report", "engines", "to", "introspect", "a", "template", "and", "find", "what", "data", "it", "needs", "and", "how", "it", "will", "be", "used", "returns", "a", "list", "of", "user", "variable", "names", "without", ...
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L414-L423
49,643
faide/py3o.template
py3o/template/main.py
Template.__prepare_usertexts
def __prepare_usertexts(self): """Replace user-type text fields that start with "py3o." with genshi instructions. """ field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]" for content_tree in self.content_trees: for userfield in content_tree.xpath(...
python
def __prepare_usertexts(self): """Replace user-type text fields that start with "py3o." with genshi instructions. """ field_expr = "//text:user-field-get[starts-with(@text:name, 'py3o.')]" for content_tree in self.content_trees: for userfield in content_tree.xpath(...
[ "def", "__prepare_usertexts", "(", "self", ")", ":", "field_expr", "=", "\"//text:user-field-get[starts-with(@text:name, 'py3o.')]\"", "for", "content_tree", "in", "self", ".", "content_trees", ":", "for", "userfield", "in", "content_tree", ".", "xpath", "(", "field_exp...
Replace user-type text fields that start with "py3o." with genshi instructions.
[ "Replace", "user", "-", "type", "text", "fields", "that", "start", "with", "py3o", ".", "with", "genshi", "instructions", "." ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L452-L532
49,644
faide/py3o.template
py3o/template/main.py
Template.__add_images_to_manifest
def __add_images_to_manifest(self): """Add entries for py3o images into the manifest file.""" xpath_expr = "//manifest:manifest[1]" for content_tree in self.content_trees: # Find manifest:manifest tags. manifest_e = content_tree.xpath( xpath_expr, ...
python
def __add_images_to_manifest(self): """Add entries for py3o images into the manifest file.""" xpath_expr = "//manifest:manifest[1]" for content_tree in self.content_trees: # Find manifest:manifest tags. manifest_e = content_tree.xpath( xpath_expr, ...
[ "def", "__add_images_to_manifest", "(", "self", ")", ":", "xpath_expr", "=", "\"//manifest:manifest[1]\"", "for", "content_tree", "in", "self", ".", "content_trees", ":", "# Find manifest:manifest tags.", "manifest_e", "=", "content_tree", ".", "xpath", "(", "xpath_expr...
Add entries for py3o images into the manifest file.
[ "Add", "entries", "for", "py3o", "images", "into", "the", "manifest", "file", "." ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L571-L597
49,645
faide/py3o.template
py3o/template/main.py
Template.render_tree
def render_tree(self, data): """prepare the flows without saving to file this method has been decoupled from render_flow to allow better unit testing """ # TODO: find a way to make this localization aware... # because ATM it formats texts using French style numbers... ...
python
def render_tree(self, data): """prepare the flows without saving to file this method has been decoupled from render_flow to allow better unit testing """ # TODO: find a way to make this localization aware... # because ATM it formats texts using French style numbers... ...
[ "def", "render_tree", "(", "self", ",", "data", ")", ":", "# TODO: find a way to make this localization aware...", "# because ATM it formats texts using French style numbers...", "# best way would be to let the user inject its own vars...", "# but this would not work on fusion servers...", "...
prepare the flows without saving to file this method has been decoupled from render_flow to allow better unit testing
[ "prepare", "the", "flows", "without", "saving", "to", "file", "this", "method", "has", "been", "decoupled", "from", "render_flow", "to", "allow", "better", "unit", "testing" ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L599-L680
49,646
faide/py3o.template
py3o/template/main.py
Template.render_flow
def render_flow(self, data): """render the OpenDocument with the user data @param data: the input stream of user data. This should be a dictionary mapping, keys being the values accessible to your report. @type data: dictionary """ self.render_tree(data) # then...
python
def render_flow(self, data): """render the OpenDocument with the user data @param data: the input stream of user data. This should be a dictionary mapping, keys being the values accessible to your report. @type data: dictionary """ self.render_tree(data) # then...
[ "def", "render_flow", "(", "self", ",", "data", ")", ":", "self", ".", "render_tree", "(", "data", ")", "# then reconstruct a new ODT document with the generated content", "for", "status", "in", "self", ".", "__save_output", "(", ")", ":", "yield", "status" ]
render the OpenDocument with the user data @param data: the input stream of user data. This should be a dictionary mapping, keys being the values accessible to your report. @type data: dictionary
[ "render", "the", "OpenDocument", "with", "the", "user", "data" ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L682-L694
49,647
faide/py3o.template
py3o/template/main.py
Template.set_image_path
def set_image_path(self, identifier, path): """Set data for an image mentioned in the template. @param identifier: Identifier of the image; refer to the image in the template by setting "py3o.[identifier]" as the name of that image. @type identifier: string @param path: Image p...
python
def set_image_path(self, identifier, path): """Set data for an image mentioned in the template. @param identifier: Identifier of the image; refer to the image in the template by setting "py3o.[identifier]" as the name of that image. @type identifier: string @param path: Image p...
[ "def", "set_image_path", "(", "self", ",", "identifier", ",", "path", ")", ":", "f", "=", "open", "(", "path", ",", "'rb'", ")", "self", ".", "set_image_data", "(", "identifier", ",", "f", ".", "read", "(", ")", ")", "f", ".", "close", "(", ")" ]
Set data for an image mentioned in the template. @param identifier: Identifier of the image; refer to the image in the template by setting "py3o.[identifier]" as the name of that image. @type identifier: string @param path: Image path on the file system @type path: string
[ "Set", "data", "for", "an", "image", "mentioned", "in", "the", "template", "." ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L707-L720
49,648
faide/py3o.template
py3o/template/main.py
Template.__save_output
def __save_output(self): """Saves the output into a native OOo document format. """ out = zipfile.ZipFile(self.outputfilename, 'w') for info_zip in self.infile.infolist(): if info_zip.filename in self.templated_files: # Template file - we have edited these. ...
python
def __save_output(self): """Saves the output into a native OOo document format. """ out = zipfile.ZipFile(self.outputfilename, 'w') for info_zip in self.infile.infolist(): if info_zip.filename in self.templated_files: # Template file - we have edited these. ...
[ "def", "__save_output", "(", "self", ")", ":", "out", "=", "zipfile", ".", "ZipFile", "(", "self", ".", "outputfilename", ",", "'w'", ")", "for", "info_zip", "in", "self", ".", "infile", ".", "infolist", "(", ")", ":", "if", "info_zip", ".", "filename"...
Saves the output into a native OOo document format.
[ "Saves", "the", "output", "into", "a", "native", "OOo", "document", "format", "." ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L735-L779
49,649
dead-beef/markovchain
markovchain/cli/text.py
cmd_create
def cmd_create(args): """Create a generator. Parameters ---------- args : `argparse.Namespace` Command arguments. """ if args.type == SQLITE: if args.output is not None and path.exists(args.output): remove(args.output) storage = SqliteStorage(db=args.output, ...
python
def cmd_create(args): """Create a generator. Parameters ---------- args : `argparse.Namespace` Command arguments. """ if args.type == SQLITE: if args.output is not None and path.exists(args.output): remove(args.output) storage = SqliteStorage(db=args.output, ...
[ "def", "cmd_create", "(", "args", ")", ":", "if", "args", ".", "type", "==", "SQLITE", ":", "if", "args", ".", "output", "is", "not", "None", "and", "path", ".", "exists", "(", "args", ".", "output", ")", ":", "remove", "(", "args", ".", "output", ...
Create a generator. Parameters ---------- args : `argparse.Namespace` Command arguments.
[ "Create", "a", "generator", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/cli/text.py#L137-L153
49,650
dead-beef/markovchain
markovchain/cli/text.py
cmd_update
def cmd_update(args): """Update a generator. Parameters ---------- args : `argparse.Namespace` Command arguments. """ #args.output = None markov = load(MarkovText, args.state, args) read(args.input, markov, args.progress) if args.output is None: if args.type == SQLI...
python
def cmd_update(args): """Update a generator. Parameters ---------- args : `argparse.Namespace` Command arguments. """ #args.output = None markov = load(MarkovText, args.state, args) read(args.input, markov, args.progress) if args.output is None: if args.type == SQLI...
[ "def", "cmd_update", "(", "args", ")", ":", "#args.output = None", "markov", "=", "load", "(", "MarkovText", ",", "args", ".", "state", ",", "args", ")", "read", "(", "args", ".", "input", ",", "markov", ",", "args", ".", "progress", ")", "if", "args",...
Update a generator. Parameters ---------- args : `argparse.Namespace` Command arguments.
[ "Update", "a", "generator", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/cli/text.py#L155-L176
49,651
dead-beef/markovchain
markovchain/cli/text.py
cmd_generate
def cmd_generate(args): """Generate text. Parameters ---------- args : `argparse.Namespace` Command arguments. """ if args.start: if args.end or args.reply: raise ValueError('multiple input arguments') args.reply_to = args.start args.reply_mode = Rep...
python
def cmd_generate(args): """Generate text. Parameters ---------- args : `argparse.Namespace` Command arguments. """ if args.start: if args.end or args.reply: raise ValueError('multiple input arguments') args.reply_to = args.start args.reply_mode = Rep...
[ "def", "cmd_generate", "(", "args", ")", ":", "if", "args", ".", "start", ":", "if", "args", ".", "end", "or", "args", ".", "reply", ":", "raise", "ValueError", "(", "'multiple input arguments'", ")", "args", ".", "reply_to", "=", "args", ".", "start", ...
Generate text. Parameters ---------- args : `argparse.Namespace` Command arguments.
[ "Generate", "text", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/cli/text.py#L178-L223
49,652
dead-beef/markovchain
markovchain/cli/main.py
main
def main(args=None): """CLI main function. Parameters ---------- args : `list` of `str`, optional CLI arguments (default: `sys.argv`). """ parser = ArgumentParser() parser.add_argument('-v', '--version', action='version', version=CLI_VERSION) parsers = p...
python
def main(args=None): """CLI main function. Parameters ---------- args : `list` of `str`, optional CLI arguments (default: `sys.argv`). """ parser = ArgumentParser() parser.add_argument('-v', '--version', action='version', version=CLI_VERSION) parsers = p...
[ "def", "main", "(", "args", "=", "None", ")", ":", "parser", "=", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "CLI_VERSION", ")", "parsers", "=", "parse...
CLI main function. Parameters ---------- args : `list` of `str`, optional CLI arguments (default: `sys.argv`).
[ "CLI", "main", "function", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/cli/main.py#L13-L43
49,653
joshleeb/creditcard
creditcard/luhn.py
get_check_digit
def get_check_digit(unchecked): """returns the check digit of the card number.""" digits = digits_of(unchecked) checksum = sum(even_digits(unchecked)) + sum([ sum(digits_of(2 * d)) for d in odd_digits(unchecked)]) return 9 * checksum % 10
python
def get_check_digit(unchecked): """returns the check digit of the card number.""" digits = digits_of(unchecked) checksum = sum(even_digits(unchecked)) + sum([ sum(digits_of(2 * d)) for d in odd_digits(unchecked)]) return 9 * checksum % 10
[ "def", "get_check_digit", "(", "unchecked", ")", ":", "digits", "=", "digits_of", "(", "unchecked", ")", "checksum", "=", "sum", "(", "even_digits", "(", "unchecked", ")", ")", "+", "sum", "(", "[", "sum", "(", "digits_of", "(", "2", "*", "d", ")", "...
returns the check digit of the card number.
[ "returns", "the", "check", "digit", "of", "the", "card", "number", "." ]
8cff49ba80029026c7e221764eb2387eb2e04a4c
https://github.com/joshleeb/creditcard/blob/8cff49ba80029026c7e221764eb2387eb2e04a4c/creditcard/luhn.py#L4-L9
49,654
joshleeb/creditcard
creditcard/luhn.py
is_valid
def is_valid(number): """determines whether the card number is valid.""" n = str(number) if not n.isdigit(): return False return int(n[-1]) == get_check_digit(n[:-1])
python
def is_valid(number): """determines whether the card number is valid.""" n = str(number) if not n.isdigit(): return False return int(n[-1]) == get_check_digit(n[:-1])
[ "def", "is_valid", "(", "number", ")", ":", "n", "=", "str", "(", "number", ")", "if", "not", "n", ".", "isdigit", "(", ")", ":", "return", "False", "return", "int", "(", "n", "[", "-", "1", "]", ")", "==", "get_check_digit", "(", "n", "[", ":"...
determines whether the card number is valid.
[ "determines", "whether", "the", "card", "number", "is", "valid", "." ]
8cff49ba80029026c7e221764eb2387eb2e04a4c
https://github.com/joshleeb/creditcard/blob/8cff49ba80029026c7e221764eb2387eb2e04a4c/creditcard/luhn.py#L12-L17
49,655
joshleeb/creditcard
creditcard/luhn.py
generate
def generate(length): """Generates random and valid card number which is returned as a string.""" if not isinstance(length, int) or length < 2: raise TypeError('length must be a positive integer greater than 1.') # first digit cannot be 0 digits = [random.randint(1, 9)] for i in range(leng...
python
def generate(length): """Generates random and valid card number which is returned as a string.""" if not isinstance(length, int) or length < 2: raise TypeError('length must be a positive integer greater than 1.') # first digit cannot be 0 digits = [random.randint(1, 9)] for i in range(leng...
[ "def", "generate", "(", "length", ")", ":", "if", "not", "isinstance", "(", "length", ",", "int", ")", "or", "length", "<", "2", ":", "raise", "TypeError", "(", "'length must be a positive integer greater than 1.'", ")", "# first digit cannot be 0", "digits", "=",...
Generates random and valid card number which is returned as a string.
[ "Generates", "random", "and", "valid", "card", "number", "which", "is", "returned", "as", "a", "string", "." ]
8cff49ba80029026c7e221764eb2387eb2e04a4c
https://github.com/joshleeb/creditcard/blob/8cff49ba80029026c7e221764eb2387eb2e04a4c/creditcard/luhn.py#L37-L49
49,656
istommao/django-simditor
simditor/image_processing.py
get_backend
def get_backend(): """Get backend.""" backend = getattr(settings, 'SIMDITOR_IMAGE_BACKEND', None) if backend == 'pillow': from simditor.image import pillow_backend as backend else: from simditor.image import dummy_backend as backend return backend
python
def get_backend(): """Get backend.""" backend = getattr(settings, 'SIMDITOR_IMAGE_BACKEND', None) if backend == 'pillow': from simditor.image import pillow_backend as backend else: from simditor.image import dummy_backend as backend return backend
[ "def", "get_backend", "(", ")", ":", "backend", "=", "getattr", "(", "settings", ",", "'SIMDITOR_IMAGE_BACKEND'", ",", "None", ")", "if", "backend", "==", "'pillow'", ":", "from", "simditor", ".", "image", "import", "pillow_backend", "as", "backend", "else", ...
Get backend.
[ "Get", "backend", "." ]
1d9fe00481f463c67f88d73ec6593a721f5fb469
https://github.com/istommao/django-simditor/blob/1d9fe00481f463c67f88d73ec6593a721f5fb469/simditor/image_processing.py#L7-L15
49,657
dead-beef/markovchain
markovchain/image/traversal.py
Spiral._rspiral
def _rspiral(width, height): """Reversed spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points. """ x0 =...
python
def _rspiral(width, height): """Reversed spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points. """ x0 =...
[ "def", "_rspiral", "(", "width", ",", "height", ")", ":", "x0", "=", "0", "y0", "=", "0", "x1", "=", "width", "-", "1", "y1", "=", "height", "-", "1", "while", "x0", "<", "x1", "and", "y0", "<", "y1", ":", "for", "x", "in", "range", "(", "x...
Reversed spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points.
[ "Reversed", "spiral", "generator", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/image/traversal.py#L228-L269
49,658
dead-beef/markovchain
markovchain/image/traversal.py
Spiral._spiral
def _spiral(width, height): """Spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points. """ if width == 1:...
python
def _spiral(width, height): """Spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points. """ if width == 1:...
[ "def", "_spiral", "(", "width", ",", "height", ")", ":", "if", "width", "==", "1", ":", "for", "y", "in", "range", "(", "height", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "yield", "0", ",", "y", "return", "if", "height", "==", "1", ...
Spiral generator. Parameters ---------- width : `int` Spiral width. height : `int` Spiral height. Returns ------- `generator` of (`int`, `int`) Points.
[ "Spiral", "generator", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/image/traversal.py#L272-L326
49,659
dead-beef/markovchain
markovchain/image/traversal.py
Hilbert.get_point_in_block
def get_point_in_block(cls, x, y, block_idx, block_size): """Get point coordinates in next block. Parameters ---------- x : `int` X coordinate in current block. y : `int` Y coordinate in current block. block_index : `int` Current block...
python
def get_point_in_block(cls, x, y, block_idx, block_size): """Get point coordinates in next block. Parameters ---------- x : `int` X coordinate in current block. y : `int` Y coordinate in current block. block_index : `int` Current block...
[ "def", "get_point_in_block", "(", "cls", ",", "x", ",", "y", ",", "block_idx", ",", "block_size", ")", ":", "if", "block_idx", "==", "0", ":", "return", "y", ",", "x", "if", "block_idx", "==", "1", ":", "return", "x", ",", "y", "+", "block_size", "...
Get point coordinates in next block. Parameters ---------- x : `int` X coordinate in current block. y : `int` Y coordinate in current block. block_index : `int` Current block index in next block. block_size : `int` Current ...
[ "Get", "point", "coordinates", "in", "next", "block", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/image/traversal.py#L373-L406
49,660
dead-beef/markovchain
markovchain/image/traversal.py
Hilbert.get_point
def get_point(cls, idx, size): """Get curve point coordinates by index. Parameters ---------- idx : `int` Point index. size : `int` Curve size. Returns ------- (`int`, `int`) Point coordinates. """ x, y...
python
def get_point(cls, idx, size): """Get curve point coordinates by index. Parameters ---------- idx : `int` Point index. size : `int` Curve size. Returns ------- (`int`, `int`) Point coordinates. """ x, y...
[ "def", "get_point", "(", "cls", ",", "idx", ",", "size", ")", ":", "x", ",", "y", "=", "cls", ".", "POSITION", "[", "idx", "%", "4", "]", "idx", "//=", "4", "block_size", "=", "2", "while", "block_size", "<", "size", ":", "block_idx", "=", "idx",...
Get curve point coordinates by index. Parameters ---------- idx : `int` Point index. size : `int` Curve size. Returns ------- (`int`, `int`) Point coordinates.
[ "Get", "curve", "point", "coordinates", "by", "index", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/image/traversal.py#L409-L432
49,661
faide/py3o.template
py3o/template/decoder.py
ForList.__recur_to_dict
def __recur_to_dict(forlist, data_dict, res): """Recursive function that fills up the dictionary """ # First we go through all attrs from the ForList and add respective # keys on the dict. for a in forlist.attrs: a_list = a.split('.') if len(a_list) == 1:...
python
def __recur_to_dict(forlist, data_dict, res): """Recursive function that fills up the dictionary """ # First we go through all attrs from the ForList and add respective # keys on the dict. for a in forlist.attrs: a_list = a.split('.') if len(a_list) == 1:...
[ "def", "__recur_to_dict", "(", "forlist", ",", "data_dict", ",", "res", ")", ":", "# First we go through all attrs from the ForList and add respective", "# keys on the dict.", "for", "a", "in", "forlist", ".", "attrs", ":", "a_list", "=", "a", ".", "split", "(", "'...
Recursive function that fills up the dictionary
[ "Recursive", "function", "that", "fills", "up", "the", "dictionary" ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/decoder.py#L52-L92
49,662
faide/py3o.template
py3o/template/decoder.py
ForList.to_dict
def to_dict(for_lists, global_vars, data_dict): """ Construct a dict object from a list of ForList object :param for_lists: list of for_list :param global_vars: list of global vars to add :param data_dict: data from an orm-like object (with dot notation) :return: a dict represen...
python
def to_dict(for_lists, global_vars, data_dict): """ Construct a dict object from a list of ForList object :param for_lists: list of for_list :param global_vars: list of global vars to add :param data_dict: data from an orm-like object (with dot notation) :return: a dict represen...
[ "def", "to_dict", "(", "for_lists", ",", "global_vars", ",", "data_dict", ")", ":", "res", "=", "{", "}", "# The first level is a little bit special", "# Manage global variables", "for", "a", "in", "global_vars", ":", "a_list", "=", "a", ".", "split", "(", "'.'"...
Construct a dict object from a list of ForList object :param for_lists: list of for_list :param global_vars: list of global vars to add :param data_dict: data from an orm-like object (with dot notation) :return: a dict representation of the ForList objects
[ "Construct", "a", "dict", "object", "from", "a", "list", "of", "ForList", "object" ]
1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/decoder.py#L95-L142
49,663
ryanmcgrath/twython-django
twython_django_oauth/views.py
logout
def logout(request, redirect_url=settings.LOGOUT_REDIRECT_URL): """ Nothing hilariously hidden here, logs a user out. Strip this out if your application already has hooks to handle this. """ django_logout(request) return HttpResponseRedirect(request.build_absolute_uri(redirect_url))
python
def logout(request, redirect_url=settings.LOGOUT_REDIRECT_URL): """ Nothing hilariously hidden here, logs a user out. Strip this out if your application already has hooks to handle this. """ django_logout(request) return HttpResponseRedirect(request.build_absolute_uri(redirect_url))
[ "def", "logout", "(", "request", ",", "redirect_url", "=", "settings", ".", "LOGOUT_REDIRECT_URL", ")", ":", "django_logout", "(", "request", ")", "return", "HttpResponseRedirect", "(", "request", ".", "build_absolute_uri", "(", "redirect_url", ")", ")" ]
Nothing hilariously hidden here, logs a user out. Strip this out if your application already has hooks to handle this.
[ "Nothing", "hilariously", "hidden", "here", "logs", "a", "user", "out", ".", "Strip", "this", "out", "if", "your", "application", "already", "has", "hooks", "to", "handle", "this", "." ]
e49e3ccba94939187378993269eff19e198e5f64
https://github.com/ryanmcgrath/twython-django/blob/e49e3ccba94939187378993269eff19e198e5f64/twython_django_oauth/views.py#L18-L24
49,664
ryanmcgrath/twython-django
twython_django_oauth/views.py
begin_auth
def begin_auth(request): """The view function that initiates the entire handshake. For the most part, this is 100% drag and drop. """ # Instantiate Twython with the first leg of our trip. twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET) # Request an authorization url to send th...
python
def begin_auth(request): """The view function that initiates the entire handshake. For the most part, this is 100% drag and drop. """ # Instantiate Twython with the first leg of our trip. twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET) # Request an authorization url to send th...
[ "def", "begin_auth", "(", "request", ")", ":", "# Instantiate Twython with the first leg of our trip.", "twitter", "=", "Twython", "(", "settings", ".", "TWITTER_KEY", ",", "settings", ".", "TWITTER_SECRET", ")", "# Request an authorization url to send the user to...", "callb...
The view function that initiates the entire handshake. For the most part, this is 100% drag and drop.
[ "The", "view", "function", "that", "initiates", "the", "entire", "handshake", "." ]
e49e3ccba94939187378993269eff19e198e5f64
https://github.com/ryanmcgrath/twython-django/blob/e49e3ccba94939187378993269eff19e198e5f64/twython_django_oauth/views.py#L27-L44
49,665
ryanmcgrath/twython-django
twython_django_oauth/views.py
thanks
def thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL): """A user gets redirected here after hitting Twitter and authorizing your app to use their data. This is the view that stores the tokens you want for querying data. Pay attention to this. """ # Now that we've got the magic tokens back ...
python
def thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL): """A user gets redirected here after hitting Twitter and authorizing your app to use their data. This is the view that stores the tokens you want for querying data. Pay attention to this. """ # Now that we've got the magic tokens back ...
[ "def", "thanks", "(", "request", ",", "redirect_url", "=", "settings", ".", "LOGIN_REDIRECT_URL", ")", ":", "# Now that we've got the magic tokens back from Twitter, we need to exchange", "# for permanent ones and store them...", "oauth_token", "=", "request", ".", "session", "...
A user gets redirected here after hitting Twitter and authorizing your app to use their data. This is the view that stores the tokens you want for querying data. Pay attention to this.
[ "A", "user", "gets", "redirected", "here", "after", "hitting", "Twitter", "and", "authorizing", "your", "app", "to", "use", "their", "data", "." ]
e49e3ccba94939187378993269eff19e198e5f64
https://github.com/ryanmcgrath/twython-django/blob/e49e3ccba94939187378993269eff19e198e5f64/twython_django_oauth/views.py#L47-L83
49,666
dead-beef/markovchain
markovchain/image/markov.py
MarkovImage._imgdata
def _imgdata(self, width, height, state_size=None, start='', dataset=''): """Generate image pixels. Parameters ---------- width : `int` Image width. height : `int` Image height. state_size : `int` or `None`, optional S...
python
def _imgdata(self, width, height, state_size=None, start='', dataset=''): """Generate image pixels. Parameters ---------- width : `int` Image width. height : `int` Image height. state_size : `int` or `None`, optional S...
[ "def", "_imgdata", "(", "self", ",", "width", ",", "height", ",", "state_size", "=", "None", ",", "start", "=", "''", ",", "dataset", "=", "''", ")", ":", "size", "=", "width", "*", "height", "if", "size", ">", "0", "and", "start", ":", "yield", ...
Generate image pixels. Parameters ---------- width : `int` Image width. height : `int` Image height. state_size : `int` or `None`, optional State size to use for generation (default: `None`). start : `str`, optional Initial...
[ "Generate", "image", "pixels", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/image/markov.py#L159-L205
49,667
dead-beef/markovchain
markovchain/image/markov.py
MarkovImage._write_imgdata
def _write_imgdata(img, data, tr, x=0, y=0): """Write image data. Parameters ---------- img : `PIL.Image.Image` Image. data : `iterable` of `int` Image data. tr : `markovchain.image.traversal.Traversal` Image traversal. x : `in...
python
def _write_imgdata(img, data, tr, x=0, y=0): """Write image data. Parameters ---------- img : `PIL.Image.Image` Image. data : `iterable` of `int` Image data. tr : `markovchain.image.traversal.Traversal` Image traversal. x : `in...
[ "def", "_write_imgdata", "(", "img", ",", "data", ",", "tr", ",", "x", "=", "0", ",", "y", "=", "0", ")", ":", "for", "pixel", ",", "(", "x1", ",", "y1", ")", "in", "zip", "(", "data", ",", "tr", ")", ":", "img", ".", "putpixel", "(", "(", ...
Write image data. Parameters ---------- img : `PIL.Image.Image` Image. data : `iterable` of `int` Image data. tr : `markovchain.image.traversal.Traversal` Image traversal. x : `int` X offset. y : `int` Y...
[ "Write", "image", "data", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/image/markov.py#L208-L226
49,668
dead-beef/markovchain
markovchain/image/markov.py
MarkovImage._channel
def _channel(self, width, height, state_sizes, start_level, start_image, dataset): """Generate a channel. Parameters ---------- width : `int` Image width. height : `int` Image height. state_sizes : `list` of (`int` or `None`) ...
python
def _channel(self, width, height, state_sizes, start_level, start_image, dataset): """Generate a channel. Parameters ---------- width : `int` Image width. height : `int` Image height. state_sizes : `list` of (`int` or `None`) ...
[ "def", "_channel", "(", "self", ",", "width", ",", "height", ",", "state_sizes", ",", "start_level", ",", "start_image", ",", "dataset", ")", ":", "ret", "=", "start_image", "for", "level", ",", "state_size", "in", "enumerate", "(", "state_sizes", ",", "st...
Generate a channel. Parameters ---------- width : `int` Image width. height : `int` Image height. state_sizes : `list` of (`int` or `None`) Level state sizes. start_level : `int` Initial level. start_image : `PIL.Im...
[ "Generate", "a", "channel", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/image/markov.py#L228-L279
49,669
NICTA/revrand
revrand/btypes.py
ravel
def ravel(parameter, random_state=None): """ Flatten a ``Parameter``. Parameters ---------- parameter: Parameter A ``Parameter`` object Returns ------- flatvalue: ndarray a flattened array of shape ``(prod(parameter.shape),)`` flatbounds: list a list of boun...
python
def ravel(parameter, random_state=None): """ Flatten a ``Parameter``. Parameters ---------- parameter: Parameter A ``Parameter`` object Returns ------- flatvalue: ndarray a flattened array of shape ``(prod(parameter.shape),)`` flatbounds: list a list of boun...
[ "def", "ravel", "(", "parameter", ",", "random_state", "=", "None", ")", ":", "flatvalue", "=", "np", ".", "ravel", "(", "parameter", ".", "rvs", "(", "random_state", "=", "random_state", ")", ")", "flatbounds", "=", "[", "parameter", ".", "bounds", "for...
Flatten a ``Parameter``. Parameters ---------- parameter: Parameter A ``Parameter`` object Returns ------- flatvalue: ndarray a flattened array of shape ``(prod(parameter.shape),)`` flatbounds: list a list of bound tuples of length ``prod(parameter.shape)``
[ "Flatten", "a", "Parameter", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/btypes.py#L351-L371
49,670
NICTA/revrand
revrand/btypes.py
hstack
def hstack(tup): """ Horizontally stack a sequence of value bounds pairs. Parameters ---------- tup: sequence a sequence of value, ``Bound`` pairs Returns ------- value: ndarray a horizontally concatenated array1d bounds: a list of Bounds """ vals, b...
python
def hstack(tup): """ Horizontally stack a sequence of value bounds pairs. Parameters ---------- tup: sequence a sequence of value, ``Bound`` pairs Returns ------- value: ndarray a horizontally concatenated array1d bounds: a list of Bounds """ vals, b...
[ "def", "hstack", "(", "tup", ")", ":", "vals", ",", "bounds", "=", "zip", "(", "*", "tup", ")", "stackvalue", "=", "np", ".", "hstack", "(", "vals", ")", "stackbounds", "=", "list", "(", "chain", "(", "*", "bounds", ")", ")", "return", "stackvalue"...
Horizontally stack a sequence of value bounds pairs. Parameters ---------- tup: sequence a sequence of value, ``Bound`` pairs Returns ------- value: ndarray a horizontally concatenated array1d bounds: a list of Bounds
[ "Horizontally", "stack", "a", "sequence", "of", "value", "bounds", "pairs", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/btypes.py#L374-L394
49,671
NICTA/revrand
revrand/btypes.py
_BoundMixin.check
def check(self, value): """ Check a value falls within a bound. Parameters ---------- value : scalar or ndarray value to test Returns ------- bool: If all values fall within bounds Example ------- >>> bnd ...
python
def check(self, value): """ Check a value falls within a bound. Parameters ---------- value : scalar or ndarray value to test Returns ------- bool: If all values fall within bounds Example ------- >>> bnd ...
[ "def", "check", "(", "self", ",", "value", ")", ":", "if", "self", ".", "lower", ":", "if", "np", ".", "any", "(", "value", "<", "self", ".", "lower", ")", ":", "return", "False", "if", "self", ".", "upper", ":", "if", "np", ".", "any", "(", ...
Check a value falls within a bound. Parameters ---------- value : scalar or ndarray value to test Returns ------- bool: If all values fall within bounds Example ------- >>> bnd = Bound(1, 2) >>> bnd.check(1.5) ...
[ "Check", "a", "value", "falls", "within", "a", "bound", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/btypes.py#L13-L47
49,672
NICTA/revrand
revrand/btypes.py
_BoundMixin.clip
def clip(self, value): """ Clip a value to a bound. Parameters ---------- value : scalar or ndarray value to clip Returns ------- scalar or ndarray : of the same shape as value, bit with each element clipped to fall wi...
python
def clip(self, value): """ Clip a value to a bound. Parameters ---------- value : scalar or ndarray value to clip Returns ------- scalar or ndarray : of the same shape as value, bit with each element clipped to fall wi...
[ "def", "clip", "(", "self", ",", "value", ")", ":", "if", "not", "self", ".", "lower", "and", "not", "self", ".", "upper", ":", "return", "value", "return", "np", ".", "clip", "(", "value", ",", "self", ".", "lower", ",", "self", ".", "upper", ")...
Clip a value to a bound. Parameters ---------- value : scalar or ndarray value to clip Returns ------- scalar or ndarray : of the same shape as value, bit with each element clipped to fall within the specified bounds Example ...
[ "Clip", "a", "value", "to", "a", "bound", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/btypes.py#L49-L80
49,673
NICTA/revrand
revrand/btypes.py
Parameter.rvs
def rvs(self, random_state=None): r""" Draw a random value from this Parameter's distribution. If ``value`` was not initialised with a ``scipy.stats`` object, then the scalar/ndarray value is returned. Parameters ---------- random_state : None, int or RandomStat...
python
def rvs(self, random_state=None): r""" Draw a random value from this Parameter's distribution. If ``value`` was not initialised with a ``scipy.stats`` object, then the scalar/ndarray value is returned. Parameters ---------- random_state : None, int or RandomStat...
[ "def", "rvs", "(", "self", ",", "random_state", "=", "None", ")", ":", "# No sampling distibution", "if", "self", ".", "dist", "is", "None", ":", "return", "self", ".", "value", "# Unconstrained samples", "rs", "=", "check_random_state", "(", "random_state", "...
r""" Draw a random value from this Parameter's distribution. If ``value`` was not initialised with a ``scipy.stats`` object, then the scalar/ndarray value is returned. Parameters ---------- random_state : None, int or RandomState, optional random seed ...
[ "r", "Draw", "a", "random", "value", "from", "this", "Parameter", "s", "distribution", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/btypes.py#L290-L324
49,674
codeinn/vcs
vcs/backends/git/inmemory.py
GitInMemoryChangeset._get_missing_trees
def _get_missing_trees(self, path, root_tree): """ Creates missing ``Tree`` objects for the given path. :param path: path given as a string. It may be a path to a file node (i.e. ``foo/bar/baz.txt``) or directory path - in that case it must end with slash (i.e. ``foo/bar/``)...
python
def _get_missing_trees(self, path, root_tree): """ Creates missing ``Tree`` objects for the given path. :param path: path given as a string. It may be a path to a file node (i.e. ``foo/bar/baz.txt``) or directory path - in that case it must end with slash (i.e. ``foo/bar/``)...
[ "def", "_get_missing_trees", "(", "self", ",", "path", ",", "root_tree", ")", ":", "dirpath", "=", "posixpath", ".", "split", "(", "path", ")", "[", "0", "]", "dirs", "=", "dirpath", ".", "split", "(", "'/'", ")", "if", "not", "dirs", "or", "dirs", ...
Creates missing ``Tree`` objects for the given path. :param path: path given as a string. It may be a path to a file node (i.e. ``foo/bar/baz.txt``) or directory path - in that case it must end with slash (i.e. ``foo/bar/``). :param root_tree: ``dulwich.objects.Tree`` object from wh...
[ "Creates", "missing", "Tree", "objects", "for", "the", "given", "path", "." ]
e6cd94188e9c36d273411bf3adc0584ac6ab92a0
https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/backends/git/inmemory.py#L161-L199
49,675
dead-beef/markovchain
markovchain/util.py
to_list
def to_list(x): """Convert a value to a list. Parameters ---------- x Value. Returns ------- `list` Examples -------- >>> to_list(0) [0] >>> to_list({'x': 0}) [{'x': 0}] >>> to_list(x ** 2 for x in range(3)) [0, 1, 4] >>> x = [1, 2, 3] >>> t...
python
def to_list(x): """Convert a value to a list. Parameters ---------- x Value. Returns ------- `list` Examples -------- >>> to_list(0) [0] >>> to_list({'x': 0}) [{'x': 0}] >>> to_list(x ** 2 for x in range(3)) [0, 1, 4] >>> x = [1, 2, 3] >>> t...
[ "def", "to_list", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "list", ")", ":", "return", "x", "if", "not", "isinstance", "(", "x", ",", "dict", ")", ":", "try", ":", "return", "list", "(", "x", ")", "except", "TypeError", ":", "pass",...
Convert a value to a list. Parameters ---------- x Value. Returns ------- `list` Examples -------- >>> to_list(0) [0] >>> to_list({'x': 0}) [{'x': 0}] >>> to_list(x ** 2 for x in range(3)) [0, 1, 4] >>> x = [1, 2, 3] >>> to_list(x) [1, 2, 3]...
[ "Convert", "a", "value", "to", "a", "list", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/util.py#L164-L197
49,676
dead-beef/markovchain
markovchain/util.py
fill
def fill(xs, length, copy=False): """Convert a value to a list of specified length. If the input is too short, fill it with its last element. Parameters ---------- xs Input list or value. length : `int` Output list length. copy : `bool`, optional Deep copy the last ...
python
def fill(xs, length, copy=False): """Convert a value to a list of specified length. If the input is too short, fill it with its last element. Parameters ---------- xs Input list or value. length : `int` Output list length. copy : `bool`, optional Deep copy the last ...
[ "def", "fill", "(", "xs", ",", "length", ",", "copy", "=", "False", ")", ":", "if", "isinstance", "(", "xs", ",", "list", ")", "and", "len", "(", "xs", ")", "==", "length", ":", "return", "xs", "if", "length", "<=", "0", ":", "return", "[", "]"...
Convert a value to a list of specified length. If the input is too short, fill it with its last element. Parameters ---------- xs Input list or value. length : `int` Output list length. copy : `bool`, optional Deep copy the last element to fill the list (default: False)...
[ "Convert", "a", "value", "to", "a", "list", "of", "specified", "length", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/util.py#L199-L264
49,677
dead-beef/markovchain
markovchain/util.py
int_enum
def int_enum(cls, val): """Get int enum value. Parameters ---------- cls : `type` Int enum class. val : `int` or `str` Name or value. Returns ------- `IntEnum` Raises ------ ValueError """ if isinstance(val, str): val = val.upper() t...
python
def int_enum(cls, val): """Get int enum value. Parameters ---------- cls : `type` Int enum class. val : `int` or `str` Name or value. Returns ------- `IntEnum` Raises ------ ValueError """ if isinstance(val, str): val = val.upper() t...
[ "def", "int_enum", "(", "cls", ",", "val", ")", ":", "if", "isinstance", "(", "val", ",", "str", ")", ":", "val", "=", "val", ".", "upper", "(", ")", "try", ":", "return", "getattr", "(", "cls", ",", "val", ")", "except", "AttributeError", ":", "...
Get int enum value. Parameters ---------- cls : `type` Int enum class. val : `int` or `str` Name or value. Returns ------- `IntEnum` Raises ------ ValueError
[ "Get", "int", "enum", "value", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/util.py#L266-L290
49,678
dead-beef/markovchain
markovchain/util.py
load
def load(obj, cls, default_factory): """Create or load an object if necessary. Parameters ---------- obj : `object` or `dict` or `None` cls : `type` default_factory : `function` Returns ------- `object` """ if obj is None: return default_factory() if isinstance(...
python
def load(obj, cls, default_factory): """Create or load an object if necessary. Parameters ---------- obj : `object` or `dict` or `None` cls : `type` default_factory : `function` Returns ------- `object` """ if obj is None: return default_factory() if isinstance(...
[ "def", "load", "(", "obj", ",", "cls", ",", "default_factory", ")", ":", "if", "obj", "is", "None", ":", "return", "default_factory", "(", ")", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "cls", ".", "load", "(", "obj", ")", "r...
Create or load an object if necessary. Parameters ---------- obj : `object` or `dict` or `None` cls : `type` default_factory : `function` Returns ------- `object`
[ "Create", "or", "load", "an", "object", "if", "necessary", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/util.py#L292-L309
49,679
dead-beef/markovchain
markovchain/util.py
truncate
def truncate(string, maxlen, end=True): """Truncate a string. Parameters ---------- string : `str` String to truncate. maxlen : `int` Maximum string length. end : `boolean`, optional Remove characters from the end (default: `True`). Raises ------ ValueError ...
python
def truncate(string, maxlen, end=True): """Truncate a string. Parameters ---------- string : `str` String to truncate. maxlen : `int` Maximum string length. end : `boolean`, optional Remove characters from the end (default: `True`). Raises ------ ValueError ...
[ "def", "truncate", "(", "string", ",", "maxlen", ",", "end", "=", "True", ")", ":", "if", "maxlen", "<=", "3", ":", "raise", "ValueError", "(", "'maxlen <= 3'", ")", "if", "len", "(", "string", ")", "<=", "maxlen", ":", "return", "string", "if", "end...
Truncate a string. Parameters ---------- string : `str` String to truncate. maxlen : `int` Maximum string length. end : `boolean`, optional Remove characters from the end (default: `True`). Raises ------ ValueError If `maxlen` <= 3. Returns ----...
[ "Truncate", "a", "string", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/util.py#L348-L388
49,680
dead-beef/markovchain
markovchain/util.py
SaveLoad.add_class
def add_class(cls, *args): """Add classes to the group. Parameters ---------- *args : `type` Classes to add. """ for cls2 in args: cls.classes[cls2.__name__] = cls2
python
def add_class(cls, *args): """Add classes to the group. Parameters ---------- *args : `type` Classes to add. """ for cls2 in args: cls.classes[cls2.__name__] = cls2
[ "def", "add_class", "(", "cls", ",", "*", "args", ")", ":", "for", "cls2", "in", "args", ":", "cls", ".", "classes", "[", "cls2", ".", "__name__", "]", "=", "cls2" ]
Add classes to the group. Parameters ---------- *args : `type` Classes to add.
[ "Add", "classes", "to", "the", "group", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/util.py#L55-L64
49,681
dead-beef/markovchain
markovchain/util.py
SaveLoad.remove_class
def remove_class(cls, *args): """Remove classes from the group. Parameters ---------- *args : `type` Classes to remove. """ for cls2 in args: try: del cls.classes[cls2.__name__] except KeyError: pass
python
def remove_class(cls, *args): """Remove classes from the group. Parameters ---------- *args : `type` Classes to remove. """ for cls2 in args: try: del cls.classes[cls2.__name__] except KeyError: pass
[ "def", "remove_class", "(", "cls", ",", "*", "args", ")", ":", "for", "cls2", "in", "args", ":", "try", ":", "del", "cls", ".", "classes", "[", "cls2", ".", "__name__", "]", "except", "KeyError", ":", "pass" ]
Remove classes from the group. Parameters ---------- *args : `type` Classes to remove.
[ "Remove", "classes", "from", "the", "group", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/util.py#L67-L79
49,682
dead-beef/markovchain
markovchain/util.py
SaveLoad.load
def load(cls, data): """Create an object from JSON data. Parameters ---------- data : `dict` JSON data. Returns ---------- `object` Created object. Raises ------ KeyError If `data` does not have the '_...
python
def load(cls, data): """Create an object from JSON data. Parameters ---------- data : `dict` JSON data. Returns ---------- `object` Created object. Raises ------ KeyError If `data` does not have the '_...
[ "def", "load", "(", "cls", ",", "data", ")", ":", "ret", "=", "cls", ".", "classes", "[", "data", "[", "'__class__'", "]", "]", "data_cls", "=", "data", "[", "'__class__'", "]", "del", "data", "[", "'__class__'", "]", "try", ":", "ret", "=", "ret",...
Create an object from JSON data. Parameters ---------- data : `dict` JSON data. Returns ---------- `object` Created object. Raises ------ KeyError If `data` does not have the '__class__' key or the...
[ "Create", "an", "object", "from", "JSON", "data", "." ]
9bd10b2f01089341c4a875a0fa569d50caba22c7
https://github.com/dead-beef/markovchain/blob/9bd10b2f01089341c4a875a0fa569d50caba22c7/markovchain/util.py#L82-L108
49,683
mozilla/Marketplace.Python
marketplace/connection.py
Connection.set_oauth_client
def set_oauth_client(self, consumer_key, consumer_secret): """Sets the oauth_client attribute """ self.oauth_client = oauth1.Client(consumer_key, consumer_secret)
python
def set_oauth_client(self, consumer_key, consumer_secret): """Sets the oauth_client attribute """ self.oauth_client = oauth1.Client(consumer_key, consumer_secret)
[ "def", "set_oauth_client", "(", "self", ",", "consumer_key", ",", "consumer_secret", ")", ":", "self", ".", "oauth_client", "=", "oauth1", ".", "Client", "(", "consumer_key", ",", "consumer_secret", ")" ]
Sets the oauth_client attribute
[ "Sets", "the", "oauth_client", "attribute" ]
88176b12201f766b6b96bccc1e4c3e82f0676283
https://github.com/mozilla/Marketplace.Python/blob/88176b12201f766b6b96bccc1e4c3e82f0676283/marketplace/connection.py#L27-L30
49,684
mozilla/Marketplace.Python
marketplace/connection.py
Connection.prepare_request
def prepare_request(self, method, url, body=''): """Prepare the request body and headers :returns: headers of the signed request """ headers = { 'Content-type': 'application/json', } # Note: we don't pass body to sign() since it's only for bodies that ...
python
def prepare_request(self, method, url, body=''): """Prepare the request body and headers :returns: headers of the signed request """ headers = { 'Content-type': 'application/json', } # Note: we don't pass body to sign() since it's only for bodies that ...
[ "def", "prepare_request", "(", "self", ",", "method", ",", "url", ",", "body", "=", "''", ")", ":", "headers", "=", "{", "'Content-type'", ":", "'application/json'", ",", "}", "# Note: we don't pass body to sign() since it's only for bodies that", "# are form-urlencoded...
Prepare the request body and headers :returns: headers of the signed request
[ "Prepare", "the", "request", "body", "and", "headers" ]
88176b12201f766b6b96bccc1e4c3e82f0676283
https://github.com/mozilla/Marketplace.Python/blob/88176b12201f766b6b96bccc1e4c3e82f0676283/marketplace/connection.py#L32-L51
49,685
mozilla/Marketplace.Python
marketplace/connection.py
Connection._get_error_reason
def _get_error_reason(response): """Extract error reason from the response. It might be either the 'reason' or the entire response """ try: body = response.json() if body and 'reason' in body: return body['reason'] except ValueError: ...
python
def _get_error_reason(response): """Extract error reason from the response. It might be either the 'reason' or the entire response """ try: body = response.json() if body and 'reason' in body: return body['reason'] except ValueError: ...
[ "def", "_get_error_reason", "(", "response", ")", ":", "try", ":", "body", "=", "response", ".", "json", "(", ")", "if", "body", "and", "'reason'", "in", "body", ":", "return", "body", "[", "'reason'", "]", "except", "ValueError", ":", "pass", "return", ...
Extract error reason from the response. It might be either the 'reason' or the entire response
[ "Extract", "error", "reason", "from", "the", "response", ".", "It", "might", "be", "either", "the", "reason", "or", "the", "entire", "response" ]
88176b12201f766b6b96bccc1e4c3e82f0676283
https://github.com/mozilla/Marketplace.Python/blob/88176b12201f766b6b96bccc1e4c3e82f0676283/marketplace/connection.py#L54-L64
49,686
mozilla/Marketplace.Python
marketplace/connection.py
Connection.fetch
def fetch(self, method, url, data=None, expected_status_code=None): """Prepare the headers, encode data, call API and provide data it returns """ kwargs = self.prepare_request(method, url, data) log.debug(json.dumps(kwargs)) response = getattr(requests, method.lower())(ur...
python
def fetch(self, method, url, data=None, expected_status_code=None): """Prepare the headers, encode data, call API and provide data it returns """ kwargs = self.prepare_request(method, url, data) log.debug(json.dumps(kwargs)) response = getattr(requests, method.lower())(ur...
[ "def", "fetch", "(", "self", ",", "method", ",", "url", ",", "data", "=", "None", ",", "expected_status_code", "=", "None", ")", ":", "kwargs", "=", "self", ".", "prepare_request", "(", "method", ",", "url", ",", "data", ")", "log", ".", "debug", "("...
Prepare the headers, encode data, call API and provide data it returns
[ "Prepare", "the", "headers", "encode", "data", "call", "API", "and", "provide", "data", "it", "returns" ]
88176b12201f766b6b96bccc1e4c3e82f0676283
https://github.com/mozilla/Marketplace.Python/blob/88176b12201f766b6b96bccc1e4c3e82f0676283/marketplace/connection.py#L66-L79
49,687
mozilla/Marketplace.Python
marketplace/connection.py
Connection.fetch_json
def fetch_json(self, method, url, data=None, expected_status_code=None): """Return json decoded data from fetch """ return self.fetch(method, url, data, expected_status_code).json()
python
def fetch_json(self, method, url, data=None, expected_status_code=None): """Return json decoded data from fetch """ return self.fetch(method, url, data, expected_status_code).json()
[ "def", "fetch_json", "(", "self", ",", "method", ",", "url", ",", "data", "=", "None", ",", "expected_status_code", "=", "None", ")", ":", "return", "self", ".", "fetch", "(", "method", ",", "url", ",", "data", ",", "expected_status_code", ")", ".", "j...
Return json decoded data from fetch
[ "Return", "json", "decoded", "data", "from", "fetch" ]
88176b12201f766b6b96bccc1e4c3e82f0676283
https://github.com/mozilla/Marketplace.Python/blob/88176b12201f766b6b96bccc1e4c3e82f0676283/marketplace/connection.py#L81-L84
49,688
NICTA/revrand
revrand/optimize/decorators.py
structured_minimizer
def structured_minimizer(minimizer): r""" Allow an optimizer to accept nested sequences of Parameters to optimize. This decorator can intepret the :code:`Parameter` objects in `btypes.py`, and can accept nested sequences of *any* structure of these objects to optimise! It can also optionally e...
python
def structured_minimizer(minimizer): r""" Allow an optimizer to accept nested sequences of Parameters to optimize. This decorator can intepret the :code:`Parameter` objects in `btypes.py`, and can accept nested sequences of *any* structure of these objects to optimise! It can also optionally e...
[ "def", "structured_minimizer", "(", "minimizer", ")", ":", "@", "wraps", "(", "minimizer", ")", "def", "new_minimizer", "(", "fun", ",", "parameters", ",", "jac", "=", "True", ",", "args", "=", "(", ")", ",", "nstarts", "=", "0", ",", "random_state", "...
r""" Allow an optimizer to accept nested sequences of Parameters to optimize. This decorator can intepret the :code:`Parameter` objects in `btypes.py`, and can accept nested sequences of *any* structure of these objects to optimise! It can also optionally evaluate *random starts* (i.e. random star...
[ "r", "Allow", "an", "optimizer", "to", "accept", "nested", "sequences", "of", "Parameters", "to", "optimize", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/optimize/decorators.py#L24-L130
49,689
NICTA/revrand
revrand/optimize/decorators.py
structured_sgd
def structured_sgd(sgd): r""" Allow an SGD to accept nested sequences of Parameters to optimize. This decorator can intepret the :code:`Parameter` objects in `btypes.py`, and can accept nested sequences of *any* structure of these objects to optimise! It can also optionally evaluate *random st...
python
def structured_sgd(sgd): r""" Allow an SGD to accept nested sequences of Parameters to optimize. This decorator can intepret the :code:`Parameter` objects in `btypes.py`, and can accept nested sequences of *any* structure of these objects to optimise! It can also optionally evaluate *random st...
[ "def", "structured_sgd", "(", "sgd", ")", ":", "@", "wraps", "(", "sgd", ")", "def", "new_sgd", "(", "fun", ",", "parameters", ",", "data", ",", "eval_obj", "=", "False", ",", "batch_size", "=", "10", ",", "args", "=", "(", ")", ",", "random_state", ...
r""" Allow an SGD to accept nested sequences of Parameters to optimize. This decorator can intepret the :code:`Parameter` objects in `btypes.py`, and can accept nested sequences of *any* structure of these objects to optimise! It can also optionally evaluate *random starts* (i.e. random starting ...
[ "r", "Allow", "an", "SGD", "to", "accept", "nested", "sequences", "of", "Parameters", "to", "optimize", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/optimize/decorators.py#L133-L252
49,690
NICTA/revrand
revrand/optimize/decorators.py
logtrick_minimizer
def logtrick_minimizer(minimizer): r""" Log-Trick decorator for optimizers. This decorator implements the "log trick" for optimizing positive bounded variables. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- >>> from scipy.optimize i...
python
def logtrick_minimizer(minimizer): r""" Log-Trick decorator for optimizers. This decorator implements the "log trick" for optimizing positive bounded variables. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- >>> from scipy.optimize i...
[ "def", "logtrick_minimizer", "(", "minimizer", ")", ":", "@", "wraps", "(", "minimizer", ")", "def", "new_minimizer", "(", "fun", ",", "x0", ",", "jac", "=", "True", ",", "bounds", "=", "None", ",", "*", "*", "minimizer_kwargs", ")", ":", "if", "bounds...
r""" Log-Trick decorator for optimizers. This decorator implements the "log trick" for optimizing positive bounded variables. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- >>> from scipy.optimize import minimize as sp_min >>> from ....
[ "r", "Log", "-", "Trick", "decorator", "for", "optimizers", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/optimize/decorators.py#L255-L326
49,691
NICTA/revrand
revrand/optimize/decorators.py
logtrick_sgd
def logtrick_sgd(sgd): r""" Log-Trick decorator for stochastic gradients. This decorator implements the "log trick" for optimizing positive bounded variables using SGD. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- >>> from ..optimi...
python
def logtrick_sgd(sgd): r""" Log-Trick decorator for stochastic gradients. This decorator implements the "log trick" for optimizing positive bounded variables using SGD. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- >>> from ..optimi...
[ "def", "logtrick_sgd", "(", "sgd", ")", ":", "@", "wraps", "(", "sgd", ")", "def", "new_sgd", "(", "fun", ",", "x0", ",", "data", ",", "bounds", "=", "None", ",", "eval_obj", "=", "False", ",", "*", "*", "sgd_kwargs", ")", ":", "if", "bounds", "i...
r""" Log-Trick decorator for stochastic gradients. This decorator implements the "log trick" for optimizing positive bounded variables using SGD. It will apply this trick for any variables that correspond to a Positive() bound. Examples -------- >>> from ..optimize import sgd >>> from ...
[ "r", "Log", "-", "Trick", "decorator", "for", "stochastic", "gradients", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/optimize/decorators.py#L329-L403
49,692
NICTA/revrand
revrand/optimize/decorators.py
flatten_grad
def flatten_grad(func): r""" Decorator to flatten structured gradients. Examples -------- >>> def cost(w, lambda_): ... sq_norm = w.T.dot(w) ... return lambda_ * w, .5 * sq_norm >>> grad = cost(np.array([.5, .1, -.2]), .25) >>> len(grad) 2 >>> grad_w, grad_lambda = ...
python
def flatten_grad(func): r""" Decorator to flatten structured gradients. Examples -------- >>> def cost(w, lambda_): ... sq_norm = w.T.dot(w) ... return lambda_ * w, .5 * sq_norm >>> grad = cost(np.array([.5, .1, -.2]), .25) >>> len(grad) 2 >>> grad_w, grad_lambda = ...
[ "def", "flatten_grad", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "flatten", "(", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ",", "returns_...
r""" Decorator to flatten structured gradients. Examples -------- >>> def cost(w, lambda_): ... sq_norm = w.T.dot(w) ... return lambda_ * w, .5 * sq_norm >>> grad = cost(np.array([.5, .1, -.2]), .25) >>> len(grad) 2 >>> grad_w, grad_lambda = grad >>> np.shape(grad_w...
[ "r", "Decorator", "to", "flatten", "structured", "gradients", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/optimize/decorators.py#L411-L443
49,693
NICTA/revrand
revrand/optimize/decorators.py
flatten_func_grad
def flatten_func_grad(func): r""" Decorator to flatten structured gradients and return objective. Examples -------- >>> def cost(w, lambda_): ... sq_norm = w.T.dot(w) ... return .5 * lambda_ * sq_norm, [lambda_ * w, .5 * sq_norm] >>> val, grad = cost(np.array([.5, .1, -.2]), .25...
python
def flatten_func_grad(func): r""" Decorator to flatten structured gradients and return objective. Examples -------- >>> def cost(w, lambda_): ... sq_norm = w.T.dot(w) ... return .5 * lambda_ * sq_norm, [lambda_ * w, .5 * sq_norm] >>> val, grad = cost(np.array([.5, .1, -.2]), .25...
[ "def", "flatten_func_grad", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "val", ",", "grad", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", ...
r""" Decorator to flatten structured gradients and return objective. Examples -------- >>> def cost(w, lambda_): ... sq_norm = w.T.dot(w) ... return .5 * lambda_ * sq_norm, [lambda_ * w, .5 * sq_norm] >>> val, grad = cost(np.array([.5, .1, -.2]), .25) >>> np.isclose(val, 0.0375...
[ "r", "Decorator", "to", "flatten", "structured", "gradients", "and", "return", "objective", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/optimize/decorators.py#L446-L484
49,694
NICTA/revrand
revrand/optimize/decorators.py
flatten_args
def flatten_args(shapes): r""" Decorator to flatten structured arguments to a function. Examples -------- >>> @flatten_args([(5,), ()]) ... def f(w, lambda_): ... return .5 * lambda_ * w.T.dot(w) >>> np.isclose(f(np.array([2., .5, .6, -.2, .9, .2])), .546) True >>> w = np.ar...
python
def flatten_args(shapes): r""" Decorator to flatten structured arguments to a function. Examples -------- >>> @flatten_args([(5,), ()]) ... def f(w, lambda_): ... return .5 * lambda_ * w.T.dot(w) >>> np.isclose(f(np.array([2., .5, .6, -.2, .9, .2])), .546) True >>> w = np.ar...
[ "def", "flatten_args", "(", "shapes", ")", ":", "def", "flatten_args_dec", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "new_func", "(", "array1d", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "tuple", "(", "un...
r""" Decorator to flatten structured arguments to a function. Examples -------- >>> @flatten_args([(5,), ()]) ... def f(w, lambda_): ... return .5 * lambda_ * w.T.dot(w) >>> np.isclose(f(np.array([2., .5, .6, -.2, .9, .2])), .546) True >>> w = np.array([2., .5, .6, -.2, .9]) ...
[ "r", "Decorator", "to", "flatten", "structured", "arguments", "to", "a", "function", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/optimize/decorators.py#L487-L534
49,695
NICTA/revrand
revrand/optimize/decorators.py
_random_starts
def _random_starts(fun, parameters, jac, args, nstarts, random_state, data_gen=None): """Generate and evaluate random starts for Parameter objects.""" if nstarts < 1: raise ValueError("nstar...
python
def _random_starts(fun, parameters, jac, args, nstarts, random_state, data_gen=None): """Generate and evaluate random starts for Parameter objects.""" if nstarts < 1: raise ValueError("nstar...
[ "def", "_random_starts", "(", "fun", ",", "parameters", ",", "jac", ",", "args", ",", "nstarts", ",", "random_state", ",", "data_gen", "=", "None", ")", ":", "if", "nstarts", "<", "1", ":", "raise", "ValueError", "(", "\"nstarts has to be greater than or equal...
Generate and evaluate random starts for Parameter objects.
[ "Generate", "and", "evaluate", "random", "starts", "for", "Parameter", "objects", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/optimize/decorators.py#L541-L583
49,696
NICTA/revrand
revrand/optimize/decorators.py
_logtrick_gen
def _logtrick_gen(bounds): """Generate warping functions and new bounds for the log trick.""" # Test which parameters we can apply the log trick too ispos = np.array([isinstance(b, bt.Positive) for b in bounds], dtype=bool) nispos = ~ispos # Functions that implement the log trick def logx(x): ...
python
def _logtrick_gen(bounds): """Generate warping functions and new bounds for the log trick.""" # Test which parameters we can apply the log trick too ispos = np.array([isinstance(b, bt.Positive) for b in bounds], dtype=bool) nispos = ~ispos # Functions that implement the log trick def logx(x): ...
[ "def", "_logtrick_gen", "(", "bounds", ")", ":", "# Test which parameters we can apply the log trick too", "ispos", "=", "np", ".", "array", "(", "[", "isinstance", "(", "b", ",", "bt", ".", "Positive", ")", "for", "b", "in", "bounds", "]", ",", "dtype", "="...
Generate warping functions and new bounds for the log trick.
[ "Generate", "warping", "functions", "and", "new", "bounds", "for", "the", "log", "trick", "." ]
4c1881b6c1772d2b988518e49dde954f165acfb6
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/optimize/decorators.py#L586-L617
49,697
codeinn/vcs
vcs/backends/git/repository.py
GitRepository._check_url
def _check_url(cls, url): """ Functon will check given url and try to verify if it's a valid link. Sometimes it may happened that mercurial will issue basic auth request that can cause whole API to hang when used from python or other external calls. On failures it'll rai...
python
def _check_url(cls, url): """ Functon will check given url and try to verify if it's a valid link. Sometimes it may happened that mercurial will issue basic auth request that can cause whole API to hang when used from python or other external calls. On failures it'll rai...
[ "def", "_check_url", "(", "cls", ",", "url", ")", ":", "# check first if it's not an local url", "if", "os", ".", "path", ".", "isdir", "(", "url", ")", "or", "url", ".", "startswith", "(", "'file:'", ")", ":", "return", "True", "if", "(", "'+'", "in", ...
Functon will check given url and try to verify if it's a valid link. Sometimes it may happened that mercurial will issue basic auth request that can cause whole API to hang when used from python or other external calls. On failures it'll raise urllib2.HTTPError
[ "Functon", "will", "check", "given", "url", "and", "try", "to", "verify", "if", "it", "s", "a", "valid", "link", ".", "Sometimes", "it", "may", "happened", "that", "mercurial", "will", "issue", "basic", "auth", "request", "that", "can", "cause", "whole", ...
e6cd94188e9c36d273411bf3adc0584ac6ab92a0
https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/backends/git/repository.py#L139-L181
49,698
codeinn/vcs
vcs/backends/git/repository.py
GitRepository._get_revision
def _get_revision(self, revision): """ For git backend we always return integer here. This way we ensure that changset's revision attribute would become integer. """ is_null = lambda o: len(o) == revision.count('0') try: self.revisions[0] except (Key...
python
def _get_revision(self, revision): """ For git backend we always return integer here. This way we ensure that changset's revision attribute would become integer. """ is_null = lambda o: len(o) == revision.count('0') try: self.revisions[0] except (Key...
[ "def", "_get_revision", "(", "self", ",", "revision", ")", ":", "is_null", "=", "lambda", "o", ":", "len", "(", "o", ")", "==", "revision", ".", "count", "(", "'0'", ")", "try", ":", "self", ".", "revisions", "[", "0", "]", "except", "(", "KeyError...
For git backend we always return integer here. This way we ensure that changset's revision attribute would become integer.
[ "For", "git", "backend", "we", "always", "return", "integer", "here", ".", "This", "way", "we", "ensure", "that", "changset", "s", "revision", "attribute", "would", "become", "integer", "." ]
e6cd94188e9c36d273411bf3adc0584ac6ab92a0
https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/backends/git/repository.py#L230-L274
49,699
codeinn/vcs
vcs/backends/git/repository.py
GitRepository.get_hook_location
def get_hook_location(self): """ returns absolute path to location where hooks are stored """ loc = os.path.join(self.path, 'hooks') if not self.bare: loc = os.path.join(self.path, '.git', 'hooks') return loc
python
def get_hook_location(self): """ returns absolute path to location where hooks are stored """ loc = os.path.join(self.path, 'hooks') if not self.bare: loc = os.path.join(self.path, '.git', 'hooks') return loc
[ "def", "get_hook_location", "(", "self", ")", ":", "loc", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'hooks'", ")", "if", "not", "self", ".", "bare", ":", "loc", "=", "os", ".", "path", ".", "join", "(", "self", ".", "...
returns absolute path to location where hooks are stored
[ "returns", "absolute", "path", "to", "location", "where", "hooks", "are", "stored" ]
e6cd94188e9c36d273411bf3adc0584ac6ab92a0
https://github.com/codeinn/vcs/blob/e6cd94188e9c36d273411bf3adc0584ac6ab92a0/vcs/backends/git/repository.py#L291-L298