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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
hyperledger-archives/indy-ledger
ledger/stores/chunked_file_store.py
ChunkedFileStore._useChunk
def _useChunk(self, index) -> None: """ Switch to specific chunk :param index: """ if self.currentChunk is not None: if self.currentChunkIndex == index and \ not self.currentChunk.closed: return self.currentChunk.close() self.currentChunk = self._openChunk(index) self.currentChunkIndex = index self.itemNum = self.currentChunk.numKeys + 1
python
def _useChunk(self, index) -> None: """ Switch to specific chunk :param index: """ if self.currentChunk is not None: if self.currentChunkIndex == index and \ not self.currentChunk.closed: return self.currentChunk.close() self.currentChunk = self._openChunk(index) self.currentChunkIndex = index self.itemNum = self.currentChunk.numKeys + 1
[ "def", "_useChunk", "(", "self", ",", "index", ")", "->", "None", ":", "if", "self", ".", "currentChunk", "is", "not", "None", ":", "if", "self", ".", "currentChunkIndex", "==", "index", "and", "not", "self", ".", "currentChunk", ".", "closed", ":", "return", "self", ".", "currentChunk", ".", "close", "(", ")", "self", ".", "currentChunk", "=", "self", ".", "_openChunk", "(", "index", ")", "self", ".", "currentChunkIndex", "=", "index", "self", ".", "itemNum", "=", "self", ".", "currentChunk", ".", "numKeys", "+", "1" ]
Switch to specific chunk :param index:
[ "Switch", "to", "specific", "chunk" ]
7210c3b288e07f940eddad09b1dfc6a56be846df
https://github.com/hyperledger-archives/indy-ledger/blob/7210c3b288e07f940eddad09b1dfc6a56be846df/ledger/stores/chunked_file_store.py#L123-L138
train
hyperledger-archives/indy-ledger
ledger/stores/chunked_file_store.py
ChunkedFileStore.numKeys
def numKeys(self) -> int: """ This will iterate only over the last chunk since the name of the last chunk indicates how many lines in total exist in all other chunks """ chunks = self._listChunks() num_chunks = len(chunks) if num_chunks == 0: return 0 count = (num_chunks-1)*self.chunkSize last_chunk = self._openChunk(chunks[-1]) count += sum(1 for _ in last_chunk._lines()) last_chunk.close() return count
python
def numKeys(self) -> int: """ This will iterate only over the last chunk since the name of the last chunk indicates how many lines in total exist in all other chunks """ chunks = self._listChunks() num_chunks = len(chunks) if num_chunks == 0: return 0 count = (num_chunks-1)*self.chunkSize last_chunk = self._openChunk(chunks[-1]) count += sum(1 for _ in last_chunk._lines()) last_chunk.close() return count
[ "def", "numKeys", "(", "self", ")", "->", "int", ":", "chunks", "=", "self", ".", "_listChunks", "(", ")", "num_chunks", "=", "len", "(", "chunks", ")", "if", "num_chunks", "==", "0", ":", "return", "0", "count", "=", "(", "num_chunks", "-", "1", ")", "*", "self", ".", "chunkSize", "last_chunk", "=", "self", ".", "_openChunk", "(", "chunks", "[", "-", "1", "]", ")", "count", "+=", "sum", "(", "1", "for", "_", "in", "last_chunk", ".", "_lines", "(", ")", ")", "last_chunk", ".", "close", "(", ")", "return", "count" ]
This will iterate only over the last chunk since the name of the last chunk indicates how many lines in total exist in all other chunks
[ "This", "will", "iterate", "only", "over", "the", "last", "chunk", "since", "the", "name", "of", "the", "last", "chunk", "indicates", "how", "many", "lines", "in", "total", "exist", "in", "all", "other", "chunks" ]
7210c3b288e07f940eddad09b1dfc6a56be846df
https://github.com/hyperledger-archives/indy-ledger/blob/7210c3b288e07f940eddad09b1dfc6a56be846df/ledger/stores/chunked_file_store.py#L291-L304
train
mivade/tornadose
tornadose/stores.py
BaseStore.register
def register(self, subscriber): """Register a new subscriber. This method should be invoked by listeners to start receiving messages. """ assert isinstance(subscriber, RequestHandler) logger.debug('New subscriber') self.subscribers.add(subscriber)
python
def register(self, subscriber): """Register a new subscriber. This method should be invoked by listeners to start receiving messages. """ assert isinstance(subscriber, RequestHandler) logger.debug('New subscriber') self.subscribers.add(subscriber)
[ "def", "register", "(", "self", ",", "subscriber", ")", ":", "assert", "isinstance", "(", "subscriber", ",", "RequestHandler", ")", "logger", ".", "debug", "(", "'New subscriber'", ")", "self", ".", "subscribers", ".", "add", "(", "subscriber", ")" ]
Register a new subscriber. This method should be invoked by listeners to start receiving messages.
[ "Register", "a", "new", "subscriber", ".", "This", "method", "should", "be", "invoked", "by", "listeners", "to", "start", "receiving", "messages", "." ]
d220e0e3040d24c98997eee7a8a236602b4c5159
https://github.com/mivade/tornadose/blob/d220e0e3040d24c98997eee7a8a236602b4c5159/tornadose/stores.py#L35-L42
train
mivade/tornadose
tornadose/stores.py
BaseStore.deregister
def deregister(self, subscriber): """Stop publishing to a subscriber.""" try: logger.debug('Subscriber left') self.subscribers.remove(subscriber) except KeyError: logger.debug( 'Error removing subscriber: ' + str(subscriber))
python
def deregister(self, subscriber): """Stop publishing to a subscriber.""" try: logger.debug('Subscriber left') self.subscribers.remove(subscriber) except KeyError: logger.debug( 'Error removing subscriber: ' + str(subscriber))
[ "def", "deregister", "(", "self", ",", "subscriber", ")", ":", "try", ":", "logger", ".", "debug", "(", "'Subscriber left'", ")", "self", ".", "subscribers", ".", "remove", "(", "subscriber", ")", "except", "KeyError", ":", "logger", ".", "debug", "(", "'Error removing subscriber: '", "+", "str", "(", "subscriber", ")", ")" ]
Stop publishing to a subscriber.
[ "Stop", "publishing", "to", "a", "subscriber", "." ]
d220e0e3040d24c98997eee7a8a236602b4c5159
https://github.com/mivade/tornadose/blob/d220e0e3040d24c98997eee7a8a236602b4c5159/tornadose/stores.py#L44-L52
train
mivade/tornadose
tornadose/stores.py
RedisStore.shutdown
def shutdown(self): """Stop the publishing loop.""" self._done.set() self.executor.shutdown(wait=False)
python
def shutdown(self): """Stop the publishing loop.""" self._done.set() self.executor.shutdown(wait=False)
[ "def", "shutdown", "(", "self", ")", ":", "self", ".", "_done", ".", "set", "(", ")", "self", ".", "executor", ".", "shutdown", "(", "wait", "=", "False", ")" ]
Stop the publishing loop.
[ "Stop", "the", "publishing", "loop", "." ]
d220e0e3040d24c98997eee7a8a236602b4c5159
https://github.com/mivade/tornadose/blob/d220e0e3040d24c98997eee7a8a236602b4c5159/tornadose/stores.py#L152-L155
train
nmdp-bioinformatics/SeqAnn
seqann/sequence_annotation.py
BioSeqAnn.add_alignment
def add_alignment(self, ref_seq, annotation) -> Annotation: """ add_alignment - method for adding the alignment to an annotation :param ref_seq: List of reference sequences :type ref_seq: List :param annotation: The complete annotation :type annotation: Annotation :rtype: Annotation """ seq_features = get_seqs(ref_seq) annoated_align = {} allele = ref_seq.description.split(",")[0] locus = allele.split("*")[0].split("-")[1] for feat in seq_features: if feat in annotation.annotation: if isinstance(annotation.annotation[feat], DBSeq): seq_len = len(str(annotation.annotation[feat])) ref_len = len(seq_features[feat]) else: seq_len = len(str(annotation.annotation[feat].seq)) ref_len = len(seq_features[feat]) if seq_len == ref_len: seq = list(annotation.annotation[feat].seq) gaps = self.refdata.annoated_alignments[locus][allele][feat]['Gaps'] if self.verbose and self.verbosity > 0: self.logger.info(self.logname + " Lengths match for " + feat) self.logger.info(self.logname + " Gaps at " + feat) self.logger.info(self.logname + "-".join([",".join([str(s) for s in g]) for g in gaps])) for i in range(0, len(gaps)): for j in gaps[i]: loc = j seq.insert(loc, '-') nseq = ''.join(seq) annoated_align.update({feat: nseq}) else: in_seq = str(annotation.annotation[feat].seq) ref_seq = self.refdata.annoated_alignments[locus][allele][feat]['Seq'] alignment = pairwise2.align.globalxx(in_seq, ref_seq) if self.verbose and self.verbosity > 0: self.logger.info(self.logname + " Align2 -> in_seq != ref_len " + feat) self.logger.info(self.logname + " " + str(len(in_seq)) + " == " + str(ref_len)) annoated_align.update({feat: alignment[0][0]}) else: nseq = ''.join(list(repeat('-', len(seq_features[feat])))) annoated_align.update({feat: nseq}) annotation.aligned = annoated_align return annotation
python
def add_alignment(self, ref_seq, annotation) -> Annotation: """ add_alignment - method for adding the alignment to an annotation :param ref_seq: List of reference sequences :type ref_seq: List :param annotation: The complete annotation :type annotation: Annotation :rtype: Annotation """ seq_features = get_seqs(ref_seq) annoated_align = {} allele = ref_seq.description.split(",")[0] locus = allele.split("*")[0].split("-")[1] for feat in seq_features: if feat in annotation.annotation: if isinstance(annotation.annotation[feat], DBSeq): seq_len = len(str(annotation.annotation[feat])) ref_len = len(seq_features[feat]) else: seq_len = len(str(annotation.annotation[feat].seq)) ref_len = len(seq_features[feat]) if seq_len == ref_len: seq = list(annotation.annotation[feat].seq) gaps = self.refdata.annoated_alignments[locus][allele][feat]['Gaps'] if self.verbose and self.verbosity > 0: self.logger.info(self.logname + " Lengths match for " + feat) self.logger.info(self.logname + " Gaps at " + feat) self.logger.info(self.logname + "-".join([",".join([str(s) for s in g]) for g in gaps])) for i in range(0, len(gaps)): for j in gaps[i]: loc = j seq.insert(loc, '-') nseq = ''.join(seq) annoated_align.update({feat: nseq}) else: in_seq = str(annotation.annotation[feat].seq) ref_seq = self.refdata.annoated_alignments[locus][allele][feat]['Seq'] alignment = pairwise2.align.globalxx(in_seq, ref_seq) if self.verbose and self.verbosity > 0: self.logger.info(self.logname + " Align2 -> in_seq != ref_len " + feat) self.logger.info(self.logname + " " + str(len(in_seq)) + " == " + str(ref_len)) annoated_align.update({feat: alignment[0][0]}) else: nseq = ''.join(list(repeat('-', len(seq_features[feat])))) annoated_align.update({feat: nseq}) annotation.aligned = annoated_align return annotation
[ "def", "add_alignment", "(", "self", ",", "ref_seq", ",", "annotation", ")", "->", "Annotation", ":", "seq_features", "=", "get_seqs", "(", "ref_seq", ")", "annoated_align", "=", "{", "}", "allele", "=", "ref_seq", ".", "description", ".", "split", "(", "\",\"", ")", "[", "0", "]", "locus", "=", "allele", ".", "split", "(", "\"*\"", ")", "[", "0", "]", ".", "split", "(", "\"-\"", ")", "[", "1", "]", "for", "feat", "in", "seq_features", ":", "if", "feat", "in", "annotation", ".", "annotation", ":", "if", "isinstance", "(", "annotation", ".", "annotation", "[", "feat", "]", ",", "DBSeq", ")", ":", "seq_len", "=", "len", "(", "str", "(", "annotation", ".", "annotation", "[", "feat", "]", ")", ")", "ref_len", "=", "len", "(", "seq_features", "[", "feat", "]", ")", "else", ":", "seq_len", "=", "len", "(", "str", "(", "annotation", ".", "annotation", "[", "feat", "]", ".", "seq", ")", ")", "ref_len", "=", "len", "(", "seq_features", "[", "feat", "]", ")", "if", "seq_len", "==", "ref_len", ":", "seq", "=", "list", "(", "annotation", ".", "annotation", "[", "feat", "]", ".", "seq", ")", "gaps", "=", "self", ".", "refdata", ".", "annoated_alignments", "[", "locus", "]", "[", "allele", "]", "[", "feat", "]", "[", "'Gaps'", "]", "if", "self", ".", "verbose", "and", "self", ".", "verbosity", ">", "0", ":", "self", ".", "logger", ".", "info", "(", "self", ".", "logname", "+", "\" Lengths match for \"", "+", "feat", ")", "self", ".", "logger", ".", "info", "(", "self", ".", "logname", "+", "\" Gaps at \"", "+", "feat", ")", "self", ".", "logger", ".", "info", "(", "self", ".", "logname", "+", "\"-\"", ".", "join", "(", "[", "\",\"", ".", "join", "(", "[", "str", "(", "s", ")", "for", "s", "in", "g", "]", ")", "for", "g", "in", "gaps", "]", ")", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "gaps", ")", ")", ":", "for", "j", "in", "gaps", "[", "i", "]", ":", "loc", "=", "j", "seq", ".", "insert", "(", "loc", ",", "'-'", ")", "nseq", "=", "''", ".", "join", "(", "seq", ")", "annoated_align", ".", "update", "(", "{", "feat", ":", "nseq", "}", ")", "else", ":", "in_seq", "=", "str", "(", "annotation", ".", "annotation", "[", "feat", "]", ".", "seq", ")", "ref_seq", "=", "self", ".", "refdata", ".", "annoated_alignments", "[", "locus", "]", "[", "allele", "]", "[", "feat", "]", "[", "'Seq'", "]", "alignment", "=", "pairwise2", ".", "align", ".", "globalxx", "(", "in_seq", ",", "ref_seq", ")", "if", "self", ".", "verbose", "and", "self", ".", "verbosity", ">", "0", ":", "self", ".", "logger", ".", "info", "(", "self", ".", "logname", "+", "\" Align2 -> in_seq != ref_len \"", "+", "feat", ")", "self", ".", "logger", ".", "info", "(", "self", ".", "logname", "+", "\" \"", "+", "str", "(", "len", "(", "in_seq", ")", ")", "+", "\" == \"", "+", "str", "(", "ref_len", ")", ")", "annoated_align", ".", "update", "(", "{", "feat", ":", "alignment", "[", "0", "]", "[", "0", "]", "}", ")", "else", ":", "nseq", "=", "''", ".", "join", "(", "list", "(", "repeat", "(", "'-'", ",", "len", "(", "seq_features", "[", "feat", "]", ")", ")", ")", ")", "annoated_align", ".", "update", "(", "{", "feat", ":", "nseq", "}", ")", "annotation", ".", "aligned", "=", "annoated_align", "return", "annotation" ]
add_alignment - method for adding the alignment to an annotation :param ref_seq: List of reference sequences :type ref_seq: List :param annotation: The complete annotation :type annotation: Annotation :rtype: Annotation
[ "add_alignment", "-", "method", "for", "adding", "the", "alignment", "to", "an", "annotation" ]
5ce91559b0a4fbe4fb7758e034eb258202632463
https://github.com/nmdp-bioinformatics/SeqAnn/blob/5ce91559b0a4fbe4fb7758e034eb258202632463/seqann/sequence_annotation.py#L1129-L1180
train
heronotears/lazyxml
lazyxml/builder.py
Builder.object2xml
def object2xml(self, data): r"""Convert python object to xml string. :param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``. :rtype: str or unicode .. versionadded:: 1.2 """ if not self.__options['encoding']: self.set_options(encoding=self.__encoding) if self.__options['header_declare']: self.__tree.append(self.build_xml_header()) root = self.__options['root'] if not root: assert (isinstance(data, utils.DictTypes) and len(data) == 1), \ 'if root not specified, the data that dict object and length must be one required.' root, data = data.items()[0] self.build_tree(data, root) xml = unicode(''.join(self.__tree).strip()) if self.__options['encoding'] != self.__encoding: xml = xml.encode(self.__options['encoding'], errors=self.__options['errors']) return xml
python
def object2xml(self, data): r"""Convert python object to xml string. :param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``. :rtype: str or unicode .. versionadded:: 1.2 """ if not self.__options['encoding']: self.set_options(encoding=self.__encoding) if self.__options['header_declare']: self.__tree.append(self.build_xml_header()) root = self.__options['root'] if not root: assert (isinstance(data, utils.DictTypes) and len(data) == 1), \ 'if root not specified, the data that dict object and length must be one required.' root, data = data.items()[0] self.build_tree(data, root) xml = unicode(''.join(self.__tree).strip()) if self.__options['encoding'] != self.__encoding: xml = xml.encode(self.__options['encoding'], errors=self.__options['errors']) return xml
[ "def", "object2xml", "(", "self", ",", "data", ")", ":", "if", "not", "self", ".", "__options", "[", "'encoding'", "]", ":", "self", ".", "set_options", "(", "encoding", "=", "self", ".", "__encoding", ")", "if", "self", ".", "__options", "[", "'header_declare'", "]", ":", "self", ".", "__tree", ".", "append", "(", "self", ".", "build_xml_header", "(", ")", ")", "root", "=", "self", ".", "__options", "[", "'root'", "]", "if", "not", "root", ":", "assert", "(", "isinstance", "(", "data", ",", "utils", ".", "DictTypes", ")", "and", "len", "(", "data", ")", "==", "1", ")", ",", "'if root not specified, the data that dict object and length must be one required.'", "root", ",", "data", "=", "data", ".", "items", "(", ")", "[", "0", "]", "self", ".", "build_tree", "(", "data", ",", "root", ")", "xml", "=", "unicode", "(", "''", ".", "join", "(", "self", ".", "__tree", ")", ".", "strip", "(", ")", ")", "if", "self", ".", "__options", "[", "'encoding'", "]", "!=", "self", ".", "__encoding", ":", "xml", "=", "xml", ".", "encode", "(", "self", ".", "__options", "[", "'encoding'", "]", ",", "errors", "=", "self", ".", "__options", "[", "'errors'", "]", ")", "return", "xml" ]
r"""Convert python object to xml string. :param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``. :rtype: str or unicode .. versionadded:: 1.2
[ "r", "Convert", "python", "object", "to", "xml", "string", "." ]
e3f1ebd3f34cfa03d022ddec90e17d60c1c81953
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L60-L85
train
heronotears/lazyxml
lazyxml/builder.py
Builder.build_tree
def build_tree(self, data, tagname, attrs=None, depth=0): r"""Build xml tree. :param data: data for build xml. :param tagname: element tag name. :param attrs: element attributes. Default:``None``. :type attrs: dict or None :param depth: element depth of the hierarchy. Default:``0``. :type depth: int """ if data is None: data = '' indent = ('\n%s' % (self.__options['indent'] * depth)) if self.__options['indent'] else '' if isinstance(data, utils.DictTypes): if self.__options['hasattr'] and self.check_structure(data.keys()): attrs, values = self.pickdata(data) self.build_tree(values, tagname, attrs, depth) else: self.__tree.append('%s%s' % (indent, self.tag_start(tagname, attrs))) iter = data.iteritems() if self.__options['ksort']: iter = sorted(iter, key=lambda x:x[0], reverse=self.__options['reverse']) for k, v in iter: attrs = {} if self.__options['hasattr'] and isinstance(v, utils.DictTypes) and self.check_structure(v.keys()): attrs, v = self.pickdata(v) self.build_tree(v, k, attrs, depth+1) self.__tree.append('%s%s' % (indent, self.tag_end(tagname))) elif utils.is_iterable(data): for v in data: self.build_tree(v, tagname, attrs, depth) else: self.__tree.append(indent) data = self.safedata(data, self.__options['cdata']) self.__tree.append(self.build_tag(tagname, data, attrs))
python
def build_tree(self, data, tagname, attrs=None, depth=0): r"""Build xml tree. :param data: data for build xml. :param tagname: element tag name. :param attrs: element attributes. Default:``None``. :type attrs: dict or None :param depth: element depth of the hierarchy. Default:``0``. :type depth: int """ if data is None: data = '' indent = ('\n%s' % (self.__options['indent'] * depth)) if self.__options['indent'] else '' if isinstance(data, utils.DictTypes): if self.__options['hasattr'] and self.check_structure(data.keys()): attrs, values = self.pickdata(data) self.build_tree(values, tagname, attrs, depth) else: self.__tree.append('%s%s' % (indent, self.tag_start(tagname, attrs))) iter = data.iteritems() if self.__options['ksort']: iter = sorted(iter, key=lambda x:x[0], reverse=self.__options['reverse']) for k, v in iter: attrs = {} if self.__options['hasattr'] and isinstance(v, utils.DictTypes) and self.check_structure(v.keys()): attrs, v = self.pickdata(v) self.build_tree(v, k, attrs, depth+1) self.__tree.append('%s%s' % (indent, self.tag_end(tagname))) elif utils.is_iterable(data): for v in data: self.build_tree(v, tagname, attrs, depth) else: self.__tree.append(indent) data = self.safedata(data, self.__options['cdata']) self.__tree.append(self.build_tag(tagname, data, attrs))
[ "def", "build_tree", "(", "self", ",", "data", ",", "tagname", ",", "attrs", "=", "None", ",", "depth", "=", "0", ")", ":", "if", "data", "is", "None", ":", "data", "=", "''", "indent", "=", "(", "'\\n%s'", "%", "(", "self", ".", "__options", "[", "'indent'", "]", "*", "depth", ")", ")", "if", "self", ".", "__options", "[", "'indent'", "]", "else", "''", "if", "isinstance", "(", "data", ",", "utils", ".", "DictTypes", ")", ":", "if", "self", ".", "__options", "[", "'hasattr'", "]", "and", "self", ".", "check_structure", "(", "data", ".", "keys", "(", ")", ")", ":", "attrs", ",", "values", "=", "self", ".", "pickdata", "(", "data", ")", "self", ".", "build_tree", "(", "values", ",", "tagname", ",", "attrs", ",", "depth", ")", "else", ":", "self", ".", "__tree", ".", "append", "(", "'%s%s'", "%", "(", "indent", ",", "self", ".", "tag_start", "(", "tagname", ",", "attrs", ")", ")", ")", "iter", "=", "data", ".", "iteritems", "(", ")", "if", "self", ".", "__options", "[", "'ksort'", "]", ":", "iter", "=", "sorted", "(", "iter", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ",", "reverse", "=", "self", ".", "__options", "[", "'reverse'", "]", ")", "for", "k", ",", "v", "in", "iter", ":", "attrs", "=", "{", "}", "if", "self", ".", "__options", "[", "'hasattr'", "]", "and", "isinstance", "(", "v", ",", "utils", ".", "DictTypes", ")", "and", "self", ".", "check_structure", "(", "v", ".", "keys", "(", ")", ")", ":", "attrs", ",", "v", "=", "self", ".", "pickdata", "(", "v", ")", "self", ".", "build_tree", "(", "v", ",", "k", ",", "attrs", ",", "depth", "+", "1", ")", "self", ".", "__tree", ".", "append", "(", "'%s%s'", "%", "(", "indent", ",", "self", ".", "tag_end", "(", "tagname", ")", ")", ")", "elif", "utils", ".", "is_iterable", "(", "data", ")", ":", "for", "v", "in", "data", ":", "self", ".", "build_tree", "(", "v", ",", "tagname", ",", "attrs", ",", "depth", ")", "else", ":", "self", ".", "__tree", ".", "append", "(", "indent", ")", "data", "=", "self", ".", "safedata", "(", "data", ",", "self", ".", "__options", "[", "'cdata'", "]", ")", "self", ".", "__tree", ".", "append", "(", "self", ".", "build_tag", "(", "tagname", ",", "data", ",", "attrs", ")", ")" ]
r"""Build xml tree. :param data: data for build xml. :param tagname: element tag name. :param attrs: element attributes. Default:``None``. :type attrs: dict or None :param depth: element depth of the hierarchy. Default:``0``. :type depth: int
[ "r", "Build", "xml", "tree", "." ]
e3f1ebd3f34cfa03d022ddec90e17d60c1c81953
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L94-L128
train
heronotears/lazyxml
lazyxml/builder.py
Builder.check_structure
def check_structure(self, keys): r"""Check structure availability by ``attrkey`` and ``valuekey`` option. """ return set(keys) <= set([self.__options['attrkey'], self.__options['valuekey']])
python
def check_structure(self, keys): r"""Check structure availability by ``attrkey`` and ``valuekey`` option. """ return set(keys) <= set([self.__options['attrkey'], self.__options['valuekey']])
[ "def", "check_structure", "(", "self", ",", "keys", ")", ":", "return", "set", "(", "keys", ")", "<=", "set", "(", "[", "self", ".", "__options", "[", "'attrkey'", "]", ",", "self", ".", "__options", "[", "'valuekey'", "]", "]", ")" ]
r"""Check structure availability by ``attrkey`` and ``valuekey`` option.
[ "r", "Check", "structure", "availability", "by", "attrkey", "and", "valuekey", "option", "." ]
e3f1ebd3f34cfa03d022ddec90e17d60c1c81953
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L130-L133
train
heronotears/lazyxml
lazyxml/builder.py
Builder.pickdata
def pickdata(self, data): r"""Pick data from ``attrkey`` and ``valuekey`` option. :return: a pair of (attrs, values) :rtype: tuple """ attrs = data.get(self.__options['attrkey']) or {} values = data.get(self.__options['valuekey']) or '' return (attrs, values)
python
def pickdata(self, data): r"""Pick data from ``attrkey`` and ``valuekey`` option. :return: a pair of (attrs, values) :rtype: tuple """ attrs = data.get(self.__options['attrkey']) or {} values = data.get(self.__options['valuekey']) or '' return (attrs, values)
[ "def", "pickdata", "(", "self", ",", "data", ")", ":", "attrs", "=", "data", ".", "get", "(", "self", ".", "__options", "[", "'attrkey'", "]", ")", "or", "{", "}", "values", "=", "data", ".", "get", "(", "self", ".", "__options", "[", "'valuekey'", "]", ")", "or", "''", "return", "(", "attrs", ",", "values", ")" ]
r"""Pick data from ``attrkey`` and ``valuekey`` option. :return: a pair of (attrs, values) :rtype: tuple
[ "r", "Pick", "data", "from", "attrkey", "and", "valuekey", "option", "." ]
e3f1ebd3f34cfa03d022ddec90e17d60c1c81953
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L135-L143
train
heronotears/lazyxml
lazyxml/builder.py
Builder.safedata
def safedata(self, data, cdata=True): r"""Convert xml special chars to entities. :param data: the data will be converted safe. :param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data. :type cdata: bool :rtype: str """ safe = ('<![CDATA[%s]]>' % data) if cdata else cgi.escape(str(data), True) return safe
python
def safedata(self, data, cdata=True): r"""Convert xml special chars to entities. :param data: the data will be converted safe. :param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data. :type cdata: bool :rtype: str """ safe = ('<![CDATA[%s]]>' % data) if cdata else cgi.escape(str(data), True) return safe
[ "def", "safedata", "(", "self", ",", "data", ",", "cdata", "=", "True", ")", ":", "safe", "=", "(", "'<![CDATA[%s]]>'", "%", "data", ")", "if", "cdata", "else", "cgi", ".", "escape", "(", "str", "(", "data", ")", ",", "True", ")", "return", "safe" ]
r"""Convert xml special chars to entities. :param data: the data will be converted safe. :param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data. :type cdata: bool :rtype: str
[ "r", "Convert", "xml", "special", "chars", "to", "entities", "." ]
e3f1ebd3f34cfa03d022ddec90e17d60c1c81953
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L145-L154
train
heronotears/lazyxml
lazyxml/builder.py
Builder.build_tag
def build_tag(self, tag, text='', attrs=None): r"""Build tag full info include the attributes. :param tag: tag name. :param text: tag text. :param attrs: tag attributes. Default:``None``. :type attrs: dict or None :rtype: str """ return '%s%s%s' % (self.tag_start(tag, attrs), text, self.tag_end(tag))
python
def build_tag(self, tag, text='', attrs=None): r"""Build tag full info include the attributes. :param tag: tag name. :param text: tag text. :param attrs: tag attributes. Default:``None``. :type attrs: dict or None :rtype: str """ return '%s%s%s' % (self.tag_start(tag, attrs), text, self.tag_end(tag))
[ "def", "build_tag", "(", "self", ",", "tag", ",", "text", "=", "''", ",", "attrs", "=", "None", ")", ":", "return", "'%s%s%s'", "%", "(", "self", ".", "tag_start", "(", "tag", ",", "attrs", ")", ",", "text", ",", "self", ".", "tag_end", "(", "tag", ")", ")" ]
r"""Build tag full info include the attributes. :param tag: tag name. :param text: tag text. :param attrs: tag attributes. Default:``None``. :type attrs: dict or None :rtype: str
[ "r", "Build", "tag", "full", "info", "include", "the", "attributes", "." ]
e3f1ebd3f34cfa03d022ddec90e17d60c1c81953
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L156-L165
train
heronotears/lazyxml
lazyxml/builder.py
Builder.build_attr
def build_attr(self, attrs): r"""Build tag attributes. :param attrs: tag attributes :type attrs: dict :rtype: str """ attrs = sorted(attrs.iteritems(), key=lambda x: x[0]) return ' '.join(map(lambda x: '%s="%s"' % x, attrs))
python
def build_attr(self, attrs): r"""Build tag attributes. :param attrs: tag attributes :type attrs: dict :rtype: str """ attrs = sorted(attrs.iteritems(), key=lambda x: x[0]) return ' '.join(map(lambda x: '%s="%s"' % x, attrs))
[ "def", "build_attr", "(", "self", ",", "attrs", ")", ":", "attrs", "=", "sorted", "(", "attrs", ".", "iteritems", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "return", "' '", ".", "join", "(", "map", "(", "lambda", "x", ":", "'%s=\"%s\"'", "%", "x", ",", "attrs", ")", ")" ]
r"""Build tag attributes. :param attrs: tag attributes :type attrs: dict :rtype: str
[ "r", "Build", "tag", "attributes", "." ]
e3f1ebd3f34cfa03d022ddec90e17d60c1c81953
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L167-L175
train
heronotears/lazyxml
lazyxml/builder.py
Builder.tag_start
def tag_start(self, tag, attrs=None): r"""Build started tag info. :param tag: tag name :param attrs: tag attributes. Default:``None``. :type attrs: dict or None :rtype: str """ return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag
python
def tag_start(self, tag, attrs=None): r"""Build started tag info. :param tag: tag name :param attrs: tag attributes. Default:``None``. :type attrs: dict or None :rtype: str """ return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag
[ "def", "tag_start", "(", "self", ",", "tag", ",", "attrs", "=", "None", ")", ":", "return", "'<%s %s>'", "%", "(", "tag", ",", "self", ".", "build_attr", "(", "attrs", ")", ")", "if", "attrs", "else", "'<%s>'", "%", "tag" ]
r"""Build started tag info. :param tag: tag name :param attrs: tag attributes. Default:``None``. :type attrs: dict or None :rtype: str
[ "r", "Build", "started", "tag", "info", "." ]
e3f1ebd3f34cfa03d022ddec90e17d60c1c81953
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L177-L185
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/gui/windows_and_widgets/export_dialog.py
ExportDialog.open_file_dialog
def open_file_dialog(self): """ Opens a file dialog to get the path to a file and put tha tpath in the correct textbox """ dialog = QtWidgets.QFileDialog sender = self.sender() if sender == self.btn_open_source: textbox = self.source_path elif sender == self.btn_open_target: textbox = self.target_path folder = dialog.getExistingDirectory(self, 'Select a file:', textbox.text(), options = QtWidgets.QFileDialog.ShowDirsOnly) if str(folder) != '': textbox.setText(folder) # load elements from file and display in tree if sender == self.btn_open_source: self.reset_avaliable(folder)
python
def open_file_dialog(self): """ Opens a file dialog to get the path to a file and put tha tpath in the correct textbox """ dialog = QtWidgets.QFileDialog sender = self.sender() if sender == self.btn_open_source: textbox = self.source_path elif sender == self.btn_open_target: textbox = self.target_path folder = dialog.getExistingDirectory(self, 'Select a file:', textbox.text(), options = QtWidgets.QFileDialog.ShowDirsOnly) if str(folder) != '': textbox.setText(folder) # load elements from file and display in tree if sender == self.btn_open_source: self.reset_avaliable(folder)
[ "def", "open_file_dialog", "(", "self", ")", ":", "dialog", "=", "QtWidgets", ".", "QFileDialog", "sender", "=", "self", ".", "sender", "(", ")", "if", "sender", "==", "self", ".", "btn_open_source", ":", "textbox", "=", "self", ".", "source_path", "elif", "sender", "==", "self", ".", "btn_open_target", ":", "textbox", "=", "self", ".", "target_path", "folder", "=", "dialog", ".", "getExistingDirectory", "(", "self", ",", "'Select a file:'", ",", "textbox", ".", "text", "(", ")", ",", "options", "=", "QtWidgets", ".", "QFileDialog", ".", "ShowDirsOnly", ")", "if", "str", "(", "folder", ")", "!=", "''", ":", "textbox", ".", "setText", "(", "folder", ")", "# load elements from file and display in tree", "if", "sender", "==", "self", ".", "btn_open_source", ":", "self", ".", "reset_avaliable", "(", "folder", ")" ]
Opens a file dialog to get the path to a file and put tha tpath in the correct textbox
[ "Opens", "a", "file", "dialog", "to", "get", "the", "path", "to", "a", "file", "and", "put", "tha", "tpath", "in", "the", "correct", "textbox" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/gui/windows_and_widgets/export_dialog.py#L69-L84
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/gui/windows_and_widgets/export_dialog.py
ExportDialog.class_type_changed
def class_type_changed(self): """ Forces a reset if the class type is changed from instruments to scripts or vice versa """ if self.source_path.text(): self.reset_avaliable(self.source_path.text())
python
def class_type_changed(self): """ Forces a reset if the class type is changed from instruments to scripts or vice versa """ if self.source_path.text(): self.reset_avaliable(self.source_path.text())
[ "def", "class_type_changed", "(", "self", ")", ":", "if", "self", ".", "source_path", ".", "text", "(", ")", ":", "self", ".", "reset_avaliable", "(", "self", ".", "source_path", ".", "text", "(", ")", ")" ]
Forces a reset if the class type is changed from instruments to scripts or vice versa
[ "Forces", "a", "reset", "if", "the", "class", "type", "is", "changed", "from", "instruments", "to", "scripts", "or", "vice", "versa" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/gui/windows_and_widgets/export_dialog.py#L105-L110
train
PeerAssets/pypeerassets
pypeerassets/provider/rpcnode.py
RpcNode.select_inputs
def select_inputs(self, address: str, amount: int) -> dict: '''finds apropriate utxo's to include in rawtx, while being careful to never spend old transactions with a lot of coin age. Argument is intiger, returns list of apropriate UTXO's''' utxos = [] utxo_sum = Decimal(0) for tx in sorted(self.listunspent(address=address), key=itemgetter('confirmations')): if tx["address"] not in (self.pa_parameters.P2TH_addr, self.pa_parameters.test_P2TH_addr): utxos.append( MutableTxIn(txid=tx['txid'], txout=tx['vout'], sequence=Sequence.max(), script_sig=ScriptSig.empty()) ) utxo_sum += Decimal(tx["amount"]) if utxo_sum >= amount: return {'utxos': utxos, 'total': utxo_sum} if utxo_sum < amount: raise InsufficientFunds("Insufficient funds.") raise Exception("undefined behavior :.(")
python
def select_inputs(self, address: str, amount: int) -> dict: '''finds apropriate utxo's to include in rawtx, while being careful to never spend old transactions with a lot of coin age. Argument is intiger, returns list of apropriate UTXO's''' utxos = [] utxo_sum = Decimal(0) for tx in sorted(self.listunspent(address=address), key=itemgetter('confirmations')): if tx["address"] not in (self.pa_parameters.P2TH_addr, self.pa_parameters.test_P2TH_addr): utxos.append( MutableTxIn(txid=tx['txid'], txout=tx['vout'], sequence=Sequence.max(), script_sig=ScriptSig.empty()) ) utxo_sum += Decimal(tx["amount"]) if utxo_sum >= amount: return {'utxos': utxos, 'total': utxo_sum} if utxo_sum < amount: raise InsufficientFunds("Insufficient funds.") raise Exception("undefined behavior :.(")
[ "def", "select_inputs", "(", "self", ",", "address", ":", "str", ",", "amount", ":", "int", ")", "->", "dict", ":", "utxos", "=", "[", "]", "utxo_sum", "=", "Decimal", "(", "0", ")", "for", "tx", "in", "sorted", "(", "self", ".", "listunspent", "(", "address", "=", "address", ")", ",", "key", "=", "itemgetter", "(", "'confirmations'", ")", ")", ":", "if", "tx", "[", "\"address\"", "]", "not", "in", "(", "self", ".", "pa_parameters", ".", "P2TH_addr", ",", "self", ".", "pa_parameters", ".", "test_P2TH_addr", ")", ":", "utxos", ".", "append", "(", "MutableTxIn", "(", "txid", "=", "tx", "[", "'txid'", "]", ",", "txout", "=", "tx", "[", "'vout'", "]", ",", "sequence", "=", "Sequence", ".", "max", "(", ")", ",", "script_sig", "=", "ScriptSig", ".", "empty", "(", ")", ")", ")", "utxo_sum", "+=", "Decimal", "(", "tx", "[", "\"amount\"", "]", ")", "if", "utxo_sum", ">=", "amount", ":", "return", "{", "'utxos'", ":", "utxos", ",", "'total'", ":", "utxo_sum", "}", "if", "utxo_sum", "<", "amount", ":", "raise", "InsufficientFunds", "(", "\"Insufficient funds.\"", ")", "raise", "Exception", "(", "\"undefined behavior :.(\"", ")" ]
finds apropriate utxo's to include in rawtx, while being careful to never spend old transactions with a lot of coin age. Argument is intiger, returns list of apropriate UTXO's
[ "finds", "apropriate", "utxo", "s", "to", "include", "in", "rawtx", "while", "being", "careful", "to", "never", "spend", "old", "transactions", "with", "a", "lot", "of", "coin", "age", ".", "Argument", "is", "intiger", "returns", "list", "of", "apropriate", "UTXO", "s" ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/rpcnode.py#L21-L47
train
PeerAssets/pypeerassets
pypeerassets/provider/rpcnode.py
RpcNode.listunspent
def listunspent( self, address: str="", minconf: int=1, maxconf: int=999999, ) -> list: '''list UTXOs modified version to allow filtering by address. ''' if address: return self.req("listunspent", [minconf, maxconf, [address]]) return self.req("listunspent", [minconf, maxconf])
python
def listunspent( self, address: str="", minconf: int=1, maxconf: int=999999, ) -> list: '''list UTXOs modified version to allow filtering by address. ''' if address: return self.req("listunspent", [minconf, maxconf, [address]]) return self.req("listunspent", [minconf, maxconf])
[ "def", "listunspent", "(", "self", ",", "address", ":", "str", "=", "\"\"", ",", "minconf", ":", "int", "=", "1", ",", "maxconf", ":", "int", "=", "999999", ",", ")", "->", "list", ":", "if", "address", ":", "return", "self", ".", "req", "(", "\"listunspent\"", ",", "[", "minconf", ",", "maxconf", ",", "[", "address", "]", "]", ")", "return", "self", ".", "req", "(", "\"listunspent\"", ",", "[", "minconf", ",", "maxconf", "]", ")" ]
list UTXOs modified version to allow filtering by address.
[ "list", "UTXOs", "modified", "version", "to", "allow", "filtering", "by", "address", "." ]
8927b4a686887f44fe2cd9de777e2c827c948987
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/rpcnode.py#L67-L79
train
jspricke/python-remind
remind.py
rem2ics
def rem2ics(): """Command line tool to convert from Remind to iCalendar""" # pylint: disable=maybe-no-member from argparse import ArgumentParser, FileType from dateutil.parser import parse from sys import stdin, stdout parser = ArgumentParser(description='Converter from Remind to iCalendar syntax.') parser.add_argument('-s', '--startdate', type=lambda s: parse(s).date(), default=date.today() - timedelta(weeks=12), help='Start offset for remind call (default: -12 weeks)') parser.add_argument('-m', '--month', type=int, default=15, help='Number of month to generate calendar beginning wit startdate (default: 15)') parser.add_argument('-a', '--alarm', type=int, default=-10, help='Trigger time for the alarm before the event in minutes (default: -10)') parser.add_argument('-z', '--zone', help='Timezone of Remind file (default: local timezone)') parser.add_argument('infile', nargs='?', default=expanduser('~/.reminders'), help='The Remind file to process (default: ~/.reminders)') parser.add_argument('outfile', nargs='?', type=FileType('w'), default=stdout, help='Output iCalendar file (default: stdout)') args = parser.parse_args() zone = timezone(args.zone) if args.zone else None if args.infile == '-': remind = Remind(args.infile, zone, args.startdate, args.month, timedelta(minutes=args.alarm)) vobject = remind.stdin_to_vobject(stdin.read()) if vobject: args.outfile.write(vobject.serialize()) else: remind = Remind(args.infile, zone, args.startdate, args.month, timedelta(minutes=args.alarm)) args.outfile.write(remind.to_vobject().serialize())
python
def rem2ics(): """Command line tool to convert from Remind to iCalendar""" # pylint: disable=maybe-no-member from argparse import ArgumentParser, FileType from dateutil.parser import parse from sys import stdin, stdout parser = ArgumentParser(description='Converter from Remind to iCalendar syntax.') parser.add_argument('-s', '--startdate', type=lambda s: parse(s).date(), default=date.today() - timedelta(weeks=12), help='Start offset for remind call (default: -12 weeks)') parser.add_argument('-m', '--month', type=int, default=15, help='Number of month to generate calendar beginning wit startdate (default: 15)') parser.add_argument('-a', '--alarm', type=int, default=-10, help='Trigger time for the alarm before the event in minutes (default: -10)') parser.add_argument('-z', '--zone', help='Timezone of Remind file (default: local timezone)') parser.add_argument('infile', nargs='?', default=expanduser('~/.reminders'), help='The Remind file to process (default: ~/.reminders)') parser.add_argument('outfile', nargs='?', type=FileType('w'), default=stdout, help='Output iCalendar file (default: stdout)') args = parser.parse_args() zone = timezone(args.zone) if args.zone else None if args.infile == '-': remind = Remind(args.infile, zone, args.startdate, args.month, timedelta(minutes=args.alarm)) vobject = remind.stdin_to_vobject(stdin.read()) if vobject: args.outfile.write(vobject.serialize()) else: remind = Remind(args.infile, zone, args.startdate, args.month, timedelta(minutes=args.alarm)) args.outfile.write(remind.to_vobject().serialize())
[ "def", "rem2ics", "(", ")", ":", "# pylint: disable=maybe-no-member", "from", "argparse", "import", "ArgumentParser", ",", "FileType", "from", "dateutil", ".", "parser", "import", "parse", "from", "sys", "import", "stdin", ",", "stdout", "parser", "=", "ArgumentParser", "(", "description", "=", "'Converter from Remind to iCalendar syntax.'", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--startdate'", ",", "type", "=", "lambda", "s", ":", "parse", "(", "s", ")", ".", "date", "(", ")", ",", "default", "=", "date", ".", "today", "(", ")", "-", "timedelta", "(", "weeks", "=", "12", ")", ",", "help", "=", "'Start offset for remind call (default: -12 weeks)'", ")", "parser", ".", "add_argument", "(", "'-m'", ",", "'--month'", ",", "type", "=", "int", ",", "default", "=", "15", ",", "help", "=", "'Number of month to generate calendar beginning wit startdate (default: 15)'", ")", "parser", ".", "add_argument", "(", "'-a'", ",", "'--alarm'", ",", "type", "=", "int", ",", "default", "=", "-", "10", ",", "help", "=", "'Trigger time for the alarm before the event in minutes (default: -10)'", ")", "parser", ".", "add_argument", "(", "'-z'", ",", "'--zone'", ",", "help", "=", "'Timezone of Remind file (default: local timezone)'", ")", "parser", ".", "add_argument", "(", "'infile'", ",", "nargs", "=", "'?'", ",", "default", "=", "expanduser", "(", "'~/.reminders'", ")", ",", "help", "=", "'The Remind file to process (default: ~/.reminders)'", ")", "parser", ".", "add_argument", "(", "'outfile'", ",", "nargs", "=", "'?'", ",", "type", "=", "FileType", "(", "'w'", ")", ",", "default", "=", "stdout", ",", "help", "=", "'Output iCalendar file (default: stdout)'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "zone", "=", "timezone", "(", "args", ".", "zone", ")", "if", "args", ".", "zone", "else", "None", "if", "args", ".", "infile", "==", "'-'", ":", "remind", "=", "Remind", "(", "args", ".", "infile", ",", "zone", ",", "args", ".", "startdate", ",", "args", ".", "month", ",", "timedelta", "(", "minutes", "=", "args", ".", "alarm", ")", ")", "vobject", "=", "remind", ".", "stdin_to_vobject", "(", "stdin", ".", "read", "(", ")", ")", "if", "vobject", ":", "args", ".", "outfile", ".", "write", "(", "vobject", ".", "serialize", "(", ")", ")", "else", ":", "remind", "=", "Remind", "(", "args", ".", "infile", ",", "zone", ",", "args", ".", "startdate", ",", "args", ".", "month", ",", "timedelta", "(", "minutes", "=", "args", ".", "alarm", ")", ")", "args", ".", "outfile", ".", "write", "(", "remind", ".", "to_vobject", "(", ")", ".", "serialize", "(", ")", ")" ]
Command line tool to convert from Remind to iCalendar
[ "Command", "line", "tool", "to", "convert", "from", "Remind", "to", "iCalendar" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L594-L626
train
jspricke/python-remind
remind.py
ics2rem
def ics2rem(): """Command line tool to convert from iCalendar to Remind""" from argparse import ArgumentParser, FileType from sys import stdin, stdout parser = ArgumentParser(description='Converter from iCalendar to Remind syntax.') parser.add_argument('-l', '--label', help='Label for every Remind entry') parser.add_argument('-p', '--priority', type=int, help='Priority for every Remind entry (0..9999)') parser.add_argument('-t', '--tag', action='append', help='Tag(s) for every Remind entry') parser.add_argument('--tail', help='Text to append to every remind summary, following final %%"') parser.add_argument('--sep', default=" ", help='String to separate summary (and tail) from description') parser.add_argument('--postdate', help='String to follow the date in every Remind entry. ' 'Useful for entering "back" and "delta" fields (see man remind).') parser.add_argument('--posttime', help='String to follow the time in every timed Remind entry. ' 'Useful for entering "tdelta" and "trepeat" fields (see man remind).') parser.add_argument('-z', '--zone', help='Timezone of Remind file (default: local timezone)') parser.add_argument('infile', nargs='?', type=FileType('r'), default=stdin, help='Input iCalendar file (default: stdin)') parser.add_argument('outfile', nargs='?', type=FileType('w'), default=stdout, help='Output Remind file (default: stdout)') args = parser.parse_args() zone = timezone(args.zone) if args.zone else None vobject = readOne(args.infile.read()) rem = Remind(localtz=zone).to_reminders( vobject, args.label, args.priority, args.tag, args.tail, args.sep, args.postdate, args.posttime) args.outfile.write(rem)
python
def ics2rem(): """Command line tool to convert from iCalendar to Remind""" from argparse import ArgumentParser, FileType from sys import stdin, stdout parser = ArgumentParser(description='Converter from iCalendar to Remind syntax.') parser.add_argument('-l', '--label', help='Label for every Remind entry') parser.add_argument('-p', '--priority', type=int, help='Priority for every Remind entry (0..9999)') parser.add_argument('-t', '--tag', action='append', help='Tag(s) for every Remind entry') parser.add_argument('--tail', help='Text to append to every remind summary, following final %%"') parser.add_argument('--sep', default=" ", help='String to separate summary (and tail) from description') parser.add_argument('--postdate', help='String to follow the date in every Remind entry. ' 'Useful for entering "back" and "delta" fields (see man remind).') parser.add_argument('--posttime', help='String to follow the time in every timed Remind entry. ' 'Useful for entering "tdelta" and "trepeat" fields (see man remind).') parser.add_argument('-z', '--zone', help='Timezone of Remind file (default: local timezone)') parser.add_argument('infile', nargs='?', type=FileType('r'), default=stdin, help='Input iCalendar file (default: stdin)') parser.add_argument('outfile', nargs='?', type=FileType('w'), default=stdout, help='Output Remind file (default: stdout)') args = parser.parse_args() zone = timezone(args.zone) if args.zone else None vobject = readOne(args.infile.read()) rem = Remind(localtz=zone).to_reminders( vobject, args.label, args.priority, args.tag, args.tail, args.sep, args.postdate, args.posttime) args.outfile.write(rem)
[ "def", "ics2rem", "(", ")", ":", "from", "argparse", "import", "ArgumentParser", ",", "FileType", "from", "sys", "import", "stdin", ",", "stdout", "parser", "=", "ArgumentParser", "(", "description", "=", "'Converter from iCalendar to Remind syntax.'", ")", "parser", ".", "add_argument", "(", "'-l'", ",", "'--label'", ",", "help", "=", "'Label for every Remind entry'", ")", "parser", ".", "add_argument", "(", "'-p'", ",", "'--priority'", ",", "type", "=", "int", ",", "help", "=", "'Priority for every Remind entry (0..9999)'", ")", "parser", ".", "add_argument", "(", "'-t'", ",", "'--tag'", ",", "action", "=", "'append'", ",", "help", "=", "'Tag(s) for every Remind entry'", ")", "parser", ".", "add_argument", "(", "'--tail'", ",", "help", "=", "'Text to append to every remind summary, following final %%\"'", ")", "parser", ".", "add_argument", "(", "'--sep'", ",", "default", "=", "\" \"", ",", "help", "=", "'String to separate summary (and tail) from description'", ")", "parser", ".", "add_argument", "(", "'--postdate'", ",", "help", "=", "'String to follow the date in every Remind entry. '", "'Useful for entering \"back\" and \"delta\" fields (see man remind).'", ")", "parser", ".", "add_argument", "(", "'--posttime'", ",", "help", "=", "'String to follow the time in every timed Remind entry. '", "'Useful for entering \"tdelta\" and \"trepeat\" fields (see man remind).'", ")", "parser", ".", "add_argument", "(", "'-z'", ",", "'--zone'", ",", "help", "=", "'Timezone of Remind file (default: local timezone)'", ")", "parser", ".", "add_argument", "(", "'infile'", ",", "nargs", "=", "'?'", ",", "type", "=", "FileType", "(", "'r'", ")", ",", "default", "=", "stdin", ",", "help", "=", "'Input iCalendar file (default: stdin)'", ")", "parser", ".", "add_argument", "(", "'outfile'", ",", "nargs", "=", "'?'", ",", "type", "=", "FileType", "(", "'w'", ")", ",", "default", "=", "stdout", ",", "help", "=", "'Output Remind file (default: stdout)'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "zone", "=", "timezone", "(", "args", ".", "zone", ")", "if", "args", ".", "zone", "else", "None", "vobject", "=", "readOne", "(", "args", ".", "infile", ".", "read", "(", ")", ")", "rem", "=", "Remind", "(", "localtz", "=", "zone", ")", ".", "to_reminders", "(", "vobject", ",", "args", ".", "label", ",", "args", ".", "priority", ",", "args", ".", "tag", ",", "args", ".", "tail", ",", "args", ".", "sep", ",", "args", ".", "postdate", ",", "args", ".", "posttime", ")", "args", ".", "outfile", ".", "write", "(", "rem", ")" ]
Command line tool to convert from iCalendar to Remind
[ "Command", "line", "tool", "to", "convert", "from", "iCalendar", "to", "Remind" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L629-L664
train
jspricke/python-remind
remind.py
Remind._parse_remind
def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders
python
def _parse_remind(self, filename, lines=''): """Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ files = {} reminders = {} if lines: filename = '-' files[filename] = lines reminders[filename] = {} cmd = ['remind', '-l', '-s%d' % self._month, '-b1', '-y', '-r', filename, str(self._startdate)] try: rem = Popen(cmd, stdin=PIPE, stdout=PIPE).communicate(input=lines.encode('utf-8'))[0].decode('utf-8') except OSError: raise OSError('Error running: %s' % ' '.join(cmd)) rem = rem.splitlines() for (fileinfo, line) in zip(rem[::2], rem[1::2]): fileinfo = fileinfo.split() src_filename = fileinfo[3] if src_filename not in files: # There is a race condition with the remind call above here. # This could be solved by parsing the remind -de output, # but I don't see an easy way to do that. files[src_filename] = open(src_filename).readlines() reminders[src_filename] = {} mtime = getmtime(src_filename) if mtime > self._mtime: self._mtime = mtime text = files[src_filename][int(fileinfo[2]) - 1] event = self._parse_remind_line(line, text) if event['uid'] in reminders[src_filename]: reminders[src_filename][event['uid']]['dtstart'] += event['dtstart'] reminders[src_filename][event['uid']]['line'] += line else: reminders[src_filename][event['uid']] = event reminders[src_filename][event['uid']]['line'] = line # Find included files without reminders and add them to the file list for source in files.values(): for line in source: if line.startswith('include'): new_file = line.split(' ')[1].strip() if new_file not in reminders: reminders[new_file] = {} mtime = getmtime(new_file) if mtime > self._mtime: self._mtime = mtime return reminders
[ "def", "_parse_remind", "(", "self", ",", "filename", ",", "lines", "=", "''", ")", ":", "files", "=", "{", "}", "reminders", "=", "{", "}", "if", "lines", ":", "filename", "=", "'-'", "files", "[", "filename", "]", "=", "lines", "reminders", "[", "filename", "]", "=", "{", "}", "cmd", "=", "[", "'remind'", ",", "'-l'", ",", "'-s%d'", "%", "self", ".", "_month", ",", "'-b1'", ",", "'-y'", ",", "'-r'", ",", "filename", ",", "str", "(", "self", ".", "_startdate", ")", "]", "try", ":", "rem", "=", "Popen", "(", "cmd", ",", "stdin", "=", "PIPE", ",", "stdout", "=", "PIPE", ")", ".", "communicate", "(", "input", "=", "lines", ".", "encode", "(", "'utf-8'", ")", ")", "[", "0", "]", ".", "decode", "(", "'utf-8'", ")", "except", "OSError", ":", "raise", "OSError", "(", "'Error running: %s'", "%", "' '", ".", "join", "(", "cmd", ")", ")", "rem", "=", "rem", ".", "splitlines", "(", ")", "for", "(", "fileinfo", ",", "line", ")", "in", "zip", "(", "rem", "[", ":", ":", "2", "]", ",", "rem", "[", "1", ":", ":", "2", "]", ")", ":", "fileinfo", "=", "fileinfo", ".", "split", "(", ")", "src_filename", "=", "fileinfo", "[", "3", "]", "if", "src_filename", "not", "in", "files", ":", "# There is a race condition with the remind call above here.", "# This could be solved by parsing the remind -de output,", "# but I don't see an easy way to do that.", "files", "[", "src_filename", "]", "=", "open", "(", "src_filename", ")", ".", "readlines", "(", ")", "reminders", "[", "src_filename", "]", "=", "{", "}", "mtime", "=", "getmtime", "(", "src_filename", ")", "if", "mtime", ">", "self", ".", "_mtime", ":", "self", ".", "_mtime", "=", "mtime", "text", "=", "files", "[", "src_filename", "]", "[", "int", "(", "fileinfo", "[", "2", "]", ")", "-", "1", "]", "event", "=", "self", ".", "_parse_remind_line", "(", "line", ",", "text", ")", "if", "event", "[", "'uid'", "]", "in", "reminders", "[", "src_filename", "]", ":", "reminders", "[", "src_filename", "]", "[", "event", "[", "'uid'", "]", "]", "[", "'dtstart'", "]", "+=", "event", "[", "'dtstart'", "]", "reminders", "[", "src_filename", "]", "[", "event", "[", "'uid'", "]", "]", "[", "'line'", "]", "+=", "line", "else", ":", "reminders", "[", "src_filename", "]", "[", "event", "[", "'uid'", "]", "]", "=", "event", "reminders", "[", "src_filename", "]", "[", "event", "[", "'uid'", "]", "]", "[", "'line'", "]", "=", "line", "# Find included files without reminders and add them to the file list", "for", "source", "in", "files", ".", "values", "(", ")", ":", "for", "line", "in", "source", ":", "if", "line", ".", "startswith", "(", "'include'", ")", ":", "new_file", "=", "line", ".", "split", "(", "' '", ")", "[", "1", "]", ".", "strip", "(", ")", "if", "new_file", "not", "in", "reminders", ":", "reminders", "[", "new_file", "]", "=", "{", "}", "mtime", "=", "getmtime", "(", "new_file", ")", "if", "mtime", ">", "self", ".", "_mtime", ":", "self", ".", "_mtime", "=", "mtime", "return", "reminders" ]
Calls remind and parses the output into a dict filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -)
[ "Calls", "remind", "and", "parses", "the", "output", "into", "a", "dict" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L54-L109
train
jspricke/python-remind
remind.py
Remind._parse_remind_line
def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event
python
def _parse_remind_line(self, line, text): """Parse a line of remind output into a dict line -- the remind output text -- the original remind input """ event = {} line = line.split(None, 6) dat = [int(f) for f in line[0].split('/')] if line[4] != '*': start = divmod(int(line[4]), 60) event['dtstart'] = [datetime(dat[0], dat[1], dat[2], start[0], start[1], tzinfo=self._localtz)] if line[3] != '*': event['duration'] = timedelta(minutes=int(line[3])) else: event['dtstart'] = [date(dat[0], dat[1], dat[2])] msg = ' '.join(line[5:]) if line[4] == '*' else line[6] msg = msg.strip().replace('%_', '\n').replace('["["]', '[') if ' at ' in msg: (event['msg'], event['location']) = msg.rsplit(' at ', 1) else: event['msg'] = msg if '%"' in text: event['description'] = Remind._gen_description(text) tags = line[2].split(',') classes = ['PUBLIC', 'PRIVATE', 'CONFIDENTIAL'] for tag in tags[:-1]: if tag in classes: event['class'] = tag event['categories'] = [tag for tag in tags[:-1] if tag not in classes] event['uid'] = '%s@%s' % (tags[-1][7:], getfqdn()) return event
[ "def", "_parse_remind_line", "(", "self", ",", "line", ",", "text", ")", ":", "event", "=", "{", "}", "line", "=", "line", ".", "split", "(", "None", ",", "6", ")", "dat", "=", "[", "int", "(", "f", ")", "for", "f", "in", "line", "[", "0", "]", ".", "split", "(", "'/'", ")", "]", "if", "line", "[", "4", "]", "!=", "'*'", ":", "start", "=", "divmod", "(", "int", "(", "line", "[", "4", "]", ")", ",", "60", ")", "event", "[", "'dtstart'", "]", "=", "[", "datetime", "(", "dat", "[", "0", "]", ",", "dat", "[", "1", "]", ",", "dat", "[", "2", "]", ",", "start", "[", "0", "]", ",", "start", "[", "1", "]", ",", "tzinfo", "=", "self", ".", "_localtz", ")", "]", "if", "line", "[", "3", "]", "!=", "'*'", ":", "event", "[", "'duration'", "]", "=", "timedelta", "(", "minutes", "=", "int", "(", "line", "[", "3", "]", ")", ")", "else", ":", "event", "[", "'dtstart'", "]", "=", "[", "date", "(", "dat", "[", "0", "]", ",", "dat", "[", "1", "]", ",", "dat", "[", "2", "]", ")", "]", "msg", "=", "' '", ".", "join", "(", "line", "[", "5", ":", "]", ")", "if", "line", "[", "4", "]", "==", "'*'", "else", "line", "[", "6", "]", "msg", "=", "msg", ".", "strip", "(", ")", ".", "replace", "(", "'%_'", ",", "'\\n'", ")", ".", "replace", "(", "'[\"[\"]'", ",", "'['", ")", "if", "' at '", "in", "msg", ":", "(", "event", "[", "'msg'", "]", ",", "event", "[", "'location'", "]", ")", "=", "msg", ".", "rsplit", "(", "' at '", ",", "1", ")", "else", ":", "event", "[", "'msg'", "]", "=", "msg", "if", "'%\"'", "in", "text", ":", "event", "[", "'description'", "]", "=", "Remind", ".", "_gen_description", "(", "text", ")", "tags", "=", "line", "[", "2", "]", ".", "split", "(", "','", ")", "classes", "=", "[", "'PUBLIC'", ",", "'PRIVATE'", ",", "'CONFIDENTIAL'", "]", "for", "tag", "in", "tags", "[", ":", "-", "1", "]", ":", "if", "tag", "in", "classes", ":", "event", "[", "'class'", "]", "=", "tag", "event", "[", "'categories'", "]", "=", "[", "tag", "for", "tag", "in", "tags", "[", ":", "-", "1", "]", "if", "tag", "not", "in", "classes", "]", "event", "[", "'uid'", "]", "=", "'%s@%s'", "%", "(", "tags", "[", "-", "1", "]", "[", "7", ":", "]", ",", "getfqdn", "(", ")", ")", "return", "event" ]
Parse a line of remind output into a dict line -- the remind output text -- the original remind input
[ "Parse", "a", "line", "of", "remind", "output", "into", "a", "dict" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L118-L158
train
jspricke/python-remind
remind.py
Remind._interval
def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval
python
def _interval(dates): """Return the distance between all dates and 0 if they are different""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval
[ "def", "_interval", "(", "dates", ")", ":", "interval", "=", "(", "dates", "[", "1", "]", "-", "dates", "[", "0", "]", ")", ".", "days", "last", "=", "dates", "[", "0", "]", "for", "dat", "in", "dates", "[", "1", ":", "]", ":", "if", "(", "dat", "-", "last", ")", ".", "days", "!=", "interval", ":", "return", "0", "last", "=", "dat", "return", "interval" ]
Return the distance between all dates and 0 if they are different
[ "Return", "the", "distance", "between", "all", "dates", "and", "0", "if", "they", "are", "different" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L161-L169
train
jspricke/python-remind
remind.py
Remind._gen_dtend_rrule
def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1)
python
def _gen_dtend_rrule(dtstarts, vevent): """Generate an rdate or rrule from a list of dates and add it to the vevent""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts))) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts))) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add('dtend').value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add('dtend').value = dtstarts[0] + timedelta(days=1)
[ "def", "_gen_dtend_rrule", "(", "dtstarts", ",", "vevent", ")", ":", "interval", "=", "Remind", ".", "_interval", "(", "dtstarts", ")", "if", "interval", ">", "0", "and", "interval", "%", "7", "==", "0", ":", "rset", "=", "rrule", ".", "rruleset", "(", ")", "rset", ".", "rrule", "(", "rrule", ".", "rrule", "(", "freq", "=", "rrule", ".", "WEEKLY", ",", "interval", "=", "interval", "//", "7", ",", "count", "=", "len", "(", "dtstarts", ")", ")", ")", "vevent", ".", "rruleset", "=", "rset", "elif", "interval", ">", "1", ":", "rset", "=", "rrule", ".", "rruleset", "(", ")", "rset", ".", "rrule", "(", "rrule", ".", "rrule", "(", "freq", "=", "rrule", ".", "DAILY", ",", "interval", "=", "interval", ",", "count", "=", "len", "(", "dtstarts", ")", ")", ")", "vevent", ".", "rruleset", "=", "rset", "elif", "interval", ">", "0", ":", "if", "isinstance", "(", "dtstarts", "[", "0", "]", ",", "datetime", ")", ":", "rset", "=", "rrule", ".", "rruleset", "(", ")", "rset", ".", "rrule", "(", "rrule", ".", "rrule", "(", "freq", "=", "rrule", ".", "DAILY", ",", "count", "=", "len", "(", "dtstarts", ")", ")", ")", "vevent", ".", "rruleset", "=", "rset", "else", ":", "vevent", ".", "add", "(", "'dtend'", ")", ".", "value", "=", "dtstarts", "[", "-", "1", "]", "+", "timedelta", "(", "days", "=", "1", ")", "else", ":", "rset", "=", "rrule", ".", "rruleset", "(", ")", "if", "isinstance", "(", "dtstarts", "[", "0", "]", ",", "datetime", ")", ":", "for", "dat", "in", "dtstarts", ":", "rset", ".", "rdate", "(", "dat", ")", "else", ":", "for", "dat", "in", "dtstarts", ":", "rset", ".", "rdate", "(", "datetime", "(", "dat", ".", "year", ",", "dat", ".", "month", ",", "dat", ".", "day", ")", ")", "# temporary set dtstart to a different date, so it's not", "# removed from rset by python-vobject works around bug in", "# Android:", "# https://github.com/rfc2822/davdroid/issues/340", "vevent", ".", "dtstart", ".", "value", "=", "dtstarts", "[", "0", "]", "-", "timedelta", "(", "days", "=", "1", ")", "vevent", ".", "rruleset", "=", "rset", "vevent", ".", "dtstart", ".", "value", "=", "dtstarts", "[", "0", "]", "if", "not", "isinstance", "(", "dtstarts", "[", "0", "]", ",", "datetime", ")", ":", "vevent", ".", "add", "(", "'dtend'", ")", ".", "value", "=", "dtstarts", "[", "0", "]", "+", "timedelta", "(", "days", "=", "1", ")" ]
Generate an rdate or rrule from a list of dates and add it to the vevent
[ "Generate", "an", "rdate", "or", "rrule", "from", "a", "list", "of", "dates", "and", "add", "it", "to", "the", "vevent" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L172-L206
train
jspricke/python-remind
remind.py
Remind._gen_vevent
def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent)
python
def _gen_vevent(self, event, vevent): """Generate vevent from given event""" vevent.add('dtstart').value = event['dtstart'][0] vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime) vevent.add('summary').value = event['msg'] vevent.add('uid').value = event['uid'] if 'class' in event: vevent.add('class').value = event['class'] if 'categories' in event and len(event['categories']) > 0: vevent.add('categories').value = event['categories'] if 'location' in event: vevent.add('location').value = event['location'] if 'description' in event: vevent.add('description').value = event['description'] if isinstance(event['dtstart'][0], datetime): if self._alarm != timedelta(): valarm = vevent.add('valarm') valarm.add('trigger').value = self._alarm valarm.add('action').value = 'DISPLAY' valarm.add('description').value = event['msg'] if 'duration' in event: vevent.add('duration').value = event['duration'] else: vevent.add('dtend').value = event['dtstart'][0] elif len(event['dtstart']) == 1: vevent.add('dtend').value = event['dtstart'][0] + timedelta(days=1) if len(event['dtstart']) > 1: Remind._gen_dtend_rrule(event['dtstart'], vevent)
[ "def", "_gen_vevent", "(", "self", ",", "event", ",", "vevent", ")", ":", "vevent", ".", "add", "(", "'dtstart'", ")", ".", "value", "=", "event", "[", "'dtstart'", "]", "[", "0", "]", "vevent", ".", "add", "(", "'dtstamp'", ")", ".", "value", "=", "datetime", ".", "fromtimestamp", "(", "self", ".", "_mtime", ")", "vevent", ".", "add", "(", "'summary'", ")", ".", "value", "=", "event", "[", "'msg'", "]", "vevent", ".", "add", "(", "'uid'", ")", ".", "value", "=", "event", "[", "'uid'", "]", "if", "'class'", "in", "event", ":", "vevent", ".", "add", "(", "'class'", ")", ".", "value", "=", "event", "[", "'class'", "]", "if", "'categories'", "in", "event", "and", "len", "(", "event", "[", "'categories'", "]", ")", ">", "0", ":", "vevent", ".", "add", "(", "'categories'", ")", ".", "value", "=", "event", "[", "'categories'", "]", "if", "'location'", "in", "event", ":", "vevent", ".", "add", "(", "'location'", ")", ".", "value", "=", "event", "[", "'location'", "]", "if", "'description'", "in", "event", ":", "vevent", ".", "add", "(", "'description'", ")", ".", "value", "=", "event", "[", "'description'", "]", "if", "isinstance", "(", "event", "[", "'dtstart'", "]", "[", "0", "]", ",", "datetime", ")", ":", "if", "self", ".", "_alarm", "!=", "timedelta", "(", ")", ":", "valarm", "=", "vevent", ".", "add", "(", "'valarm'", ")", "valarm", ".", "add", "(", "'trigger'", ")", ".", "value", "=", "self", ".", "_alarm", "valarm", ".", "add", "(", "'action'", ")", ".", "value", "=", "'DISPLAY'", "valarm", ".", "add", "(", "'description'", ")", ".", "value", "=", "event", "[", "'msg'", "]", "if", "'duration'", "in", "event", ":", "vevent", ".", "add", "(", "'duration'", ")", ".", "value", "=", "event", "[", "'duration'", "]", "else", ":", "vevent", ".", "add", "(", "'dtend'", ")", ".", "value", "=", "event", "[", "'dtstart'", "]", "[", "0", "]", "elif", "len", "(", "event", "[", "'dtstart'", "]", ")", "==", "1", ":", "vevent", ".", "add", "(", "'dtend'", ")", ".", "value", "=", "event", "[", "'dtstart'", "]", "[", "0", "]", "+", "timedelta", "(", "days", "=", "1", ")", "if", "len", "(", "event", "[", "'dtstart'", "]", ")", ">", "1", ":", "Remind", ".", "_gen_dtend_rrule", "(", "event", "[", "'dtstart'", "]", ",", "vevent", ")" ]
Generate vevent from given event
[ "Generate", "vevent", "from", "given", "event" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L208-L243
train
jspricke/python-remind
remind.py
Remind._update
def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename)
python
def _update(self): """Reload Remind files if the mtime is newer""" update = not self._reminders with self._lock: for fname in self._reminders: if getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename)
[ "def", "_update", "(", "self", ")", ":", "update", "=", "not", "self", ".", "_reminders", "with", "self", ".", "_lock", ":", "for", "fname", "in", "self", ".", "_reminders", ":", "if", "getmtime", "(", "fname", ")", ">", "self", ".", "_mtime", ":", "update", "=", "True", "break", "if", "update", ":", "self", ".", "_reminders", "=", "self", ".", "_parse_remind", "(", "self", ".", "_filename", ")" ]
Reload Remind files if the mtime is newer
[ "Reload", "Remind", "files", "if", "the", "mtime", "is", "newer" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L245-L256
train
jspricke/python-remind
remind.py
Remind.get_uids
def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids]
python
def get_uids(self, filename=None): """UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return self._reminders[filename].keys() return [uid for uids in self._reminders.values() for uid in uids]
[ "def", "get_uids", "(", "self", ",", "filename", "=", "None", ")", ":", "self", ".", "_update", "(", ")", "if", "filename", ":", "if", "filename", "not", "in", "self", ".", "_reminders", ":", "return", "[", "]", "return", "self", ".", "_reminders", "[", "filename", "]", ".", "keys", "(", ")", "return", "[", "uid", "for", "uids", "in", "self", ".", "_reminders", ".", "values", "(", ")", "for", "uid", "in", "uids", "]" ]
UIDs of all reminders in the file excluding included files If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file
[ "UIDs", "of", "all", "reminders", "in", "the", "file", "excluding", "included", "files", "If", "a", "filename", "is", "specified", "only", "it", "s", "UIDs", "are", "return", "otherwise", "all", "." ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L268-L280
train
jspricke/python-remind
remind.py
Remind.to_vobjects
def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items
python
def to_vobjects(self, filename, uids=None): """Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = self._reminders[filename] items = [] for uid in uids: cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) etag = md5() etag.update(self._reminders[filename][uid]['line'].encode("utf-8")) items.append((uid, cal, '"%s"' % etag.hexdigest())) return items
[ "def", "to_vobjects", "(", "self", ",", "filename", ",", "uids", "=", "None", ")", ":", "self", ".", "_update", "(", ")", "if", "not", "uids", ":", "uids", "=", "self", ".", "_reminders", "[", "filename", "]", "items", "=", "[", "]", "for", "uid", "in", "uids", ":", "cal", "=", "iCalendar", "(", ")", "self", ".", "_gen_vevent", "(", "self", ".", "_reminders", "[", "filename", "]", "[", "uid", "]", ",", "cal", ".", "add", "(", "'vevent'", ")", ")", "etag", "=", "md5", "(", ")", "etag", ".", "update", "(", "self", ".", "_reminders", "[", "filename", "]", "[", "uid", "]", "[", "'line'", "]", ".", "encode", "(", "\"utf-8\"", ")", ")", "items", ".", "append", "(", "(", "uid", ",", "cal", ",", "'\"%s\"'", "%", "etag", ".", "hexdigest", "(", ")", ")", ")", "return", "items" ]
Return iCal objects and etags of all Remind entries in uids filename -- the remind file uids -- the UIDs of the Remind lines (all if None)
[ "Return", "iCal", "objects", "and", "etags", "of", "all", "Remind", "entries", "in", "uids" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L290-L309
train
jspricke/python-remind
remind.py
Remind.to_vobject
def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal
python
def to_vobject(self, filename=None, uid=None): """Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add('vevent')) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) else: for filename in self._reminders: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add('vevent')) return cal
[ "def", "to_vobject", "(", "self", ",", "filename", "=", "None", ",", "uid", "=", "None", ")", ":", "self", ".", "_update", "(", ")", "cal", "=", "iCalendar", "(", ")", "if", "uid", ":", "self", ".", "_gen_vevent", "(", "self", ".", "_reminders", "[", "filename", "]", "[", "uid", "]", ",", "cal", ".", "add", "(", "'vevent'", ")", ")", "elif", "filename", ":", "for", "event", "in", "self", ".", "_reminders", "[", "filename", "]", ".", "values", "(", ")", ":", "self", ".", "_gen_vevent", "(", "event", ",", "cal", ".", "add", "(", "'vevent'", ")", ")", "else", ":", "for", "filename", "in", "self", ".", "_reminders", ":", "for", "event", "in", "self", ".", "_reminders", "[", "filename", "]", ".", "values", "(", ")", ":", "self", ".", "_gen_vevent", "(", "event", ",", "cal", ".", "add", "(", "'vevent'", ")", ")", "return", "cal" ]
Return iCal object of Remind lines If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line
[ "Return", "iCal", "object", "of", "Remind", "lines", "If", "filename", "and", "UID", "are", "specified", "the", "vObject", "only", "contains", "that", "event", ".", "If", "only", "a", "filename", "is", "specified", "the", "vObject", "contains", "all", "events", "in", "the", "file", ".", "Otherwise", "the", "vObject", "contains", "all", "all", "objects", "of", "all", "files", "associated", "with", "the", "Remind", "object", "." ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L311-L332
train
jspricke/python-remind
remind.py
Remind.stdin_to_vobject
def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal
python
def stdin_to_vobject(self, lines): """Return iCal object of the Remind commands in lines""" cal = iCalendar() for event in self._parse_remind('-', lines)['-'].values(): self._gen_vevent(event, cal.add('vevent')) return cal
[ "def", "stdin_to_vobject", "(", "self", ",", "lines", ")", ":", "cal", "=", "iCalendar", "(", ")", "for", "event", "in", "self", ".", "_parse_remind", "(", "'-'", ",", "lines", ")", "[", "'-'", "]", ".", "values", "(", ")", ":", "self", ".", "_gen_vevent", "(", "event", ",", "cal", ".", "add", "(", "'vevent'", ")", ")", "return", "cal" ]
Return iCal object of the Remind commands in lines
[ "Return", "iCal", "object", "of", "the", "Remind", "commands", "in", "lines" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L334-L339
train
jspricke/python-remind
remind.py
Remind._parse_rruleset
def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep
python
def _parse_rruleset(rruleset): """Convert from iCal rrule to Remind recurrence syntax""" # pylint: disable=protected-access if rruleset._rrule[0]._freq == 0: return [] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append('*1') elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append('*%d' % rruleset._rrule[0]._interval) elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append('*%d' % (7 * rruleset._rrule[0]._interval)) else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] days = [weekdays[day] for day in daynums] rep.append('SKIP OMIT %s' % ' '.join(days)) if rruleset._rrule[0]._until: rep.append(rruleset._rrule[0]._until.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime('UNTIL %b %d %Y').replace(' 0', ' ')) return rep
[ "def", "_parse_rruleset", "(", "rruleset", ")", ":", "# pylint: disable=protected-access", "if", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_freq", "==", "0", ":", "return", "[", "]", "rep", "=", "[", "]", "if", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_byweekday", "and", "len", "(", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_byweekday", ")", ">", "1", ":", "rep", ".", "append", "(", "'*1'", ")", "elif", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_freq", "==", "rrule", ".", "DAILY", ":", "rep", ".", "append", "(", "'*%d'", "%", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_interval", ")", "elif", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_freq", "==", "rrule", ".", "WEEKLY", ":", "rep", ".", "append", "(", "'*%d'", "%", "(", "7", "*", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_interval", ")", ")", "else", ":", "return", "Remind", ".", "_parse_rdate", "(", "rruleset", ".", "_rrule", "[", "0", "]", ")", "if", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_byweekday", "and", "len", "(", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_byweekday", ")", ">", "1", ":", "daynums", "=", "set", "(", "range", "(", "7", ")", ")", "-", "set", "(", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_byweekday", ")", "weekdays", "=", "[", "'Mon'", ",", "'Tue'", ",", "'Wed'", ",", "'Thu'", ",", "'Fri'", ",", "'Sat'", ",", "'Sun'", "]", "days", "=", "[", "weekdays", "[", "day", "]", "for", "day", "in", "daynums", "]", "rep", ".", "append", "(", "'SKIP OMIT %s'", "%", "' '", ".", "join", "(", "days", ")", ")", "if", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_until", ":", "rep", ".", "append", "(", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_until", ".", "strftime", "(", "'UNTIL %b %d %Y'", ")", ".", "replace", "(", "' 0'", ",", "' '", ")", ")", "elif", "rruleset", ".", "_rrule", "[", "0", "]", ".", "_count", ":", "rep", ".", "append", "(", "rruleset", "[", "-", "1", "]", ".", "strftime", "(", "'UNTIL %b %d %Y'", ")", ".", "replace", "(", "' 0'", ",", "' '", ")", ")", "return", "rep" ]
Convert from iCal rrule to Remind recurrence syntax
[ "Convert", "from", "iCal", "rrule", "to", "Remind", "recurrence", "syntax" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L348-L376
train
jspricke/python-remind
remind.py
Remind._event_duration
def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0)
python
def _event_duration(vevent): """unify dtend and duration to the duration of the given vevent""" if hasattr(vevent, 'dtend'): return vevent.dtend.value - vevent.dtstart.value elif hasattr(vevent, 'duration') and vevent.duration.value: return vevent.duration.value return timedelta(0)
[ "def", "_event_duration", "(", "vevent", ")", ":", "if", "hasattr", "(", "vevent", ",", "'dtend'", ")", ":", "return", "vevent", ".", "dtend", ".", "value", "-", "vevent", ".", "dtstart", ".", "value", "elif", "hasattr", "(", "vevent", ",", "'duration'", ")", "and", "vevent", ".", "duration", ".", "value", ":", "return", "vevent", ".", "duration", ".", "value", "return", "timedelta", "(", "0", ")" ]
unify dtend and duration to the duration of the given vevent
[ "unify", "dtend", "and", "duration", "to", "the", "duration", "of", "the", "given", "vevent" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L379-L385
train
jspricke/python-remind
remind.py
Remind.to_remind
def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n'
python
def to_remind(self, vevent, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Generate a Remind command from the given vevent""" remind = ['REM'] trigdates = None if hasattr(vevent, 'rrule'): trigdates = Remind._parse_rruleset(vevent.rruleset) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, 'dtend'): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, 'rdate') and not isinstance(trigdates, str): remind.append(dtstart.strftime('%b %d %Y').replace(' 0', ' ')) if postdate: remind.append(postdate) if priority: remind.append('PRIORITY %s' % priority) if isinstance(trigdates, list): remind.extend(trigdates) duration = Remind._event_duration(vevent) if type(dtstart) is date and duration.days > 1: remind.append('*1') if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime('UNTIL %b %d %Y').replace(' 0', ' ')) if isinstance(dtstart, datetime): remind.append(dtstart.strftime('AT %H:%M').replace(' 0', ' ')) if posttime: remind.append(posttime) if duration.total_seconds() > 0: remind.append('DURATION %d:%02d' % divmod(duration.total_seconds() / 60, 60)) if hasattr(vevent, 'rdate'): remind.append(Remind._parse_rdate(vevent.rdate.value)) elif isinstance(trigdates, str): remind.append(trigdates) if hasattr(vevent, 'class'): remind.append('TAG %s' % Remind._abbr_tag(vevent.getChildValue('class'))) if tags: remind.extend(['TAG %s' % Remind._abbr_tag(tag) for tag in tags]) if hasattr(vevent, 'categories_list'): for categories in vevent.categories_list: for category in categories.value: remind.append('TAG %s' % Remind._abbr_tag(category)) remind.append(Remind._gen_msg(vevent, label, tail, sep)) return ' '.join(remind) + '\n'
[ "def", "to_remind", "(", "self", ",", "vevent", ",", "label", "=", "None", ",", "priority", "=", "None", ",", "tags", "=", "None", ",", "tail", "=", "None", ",", "sep", "=", "\" \"", ",", "postdate", "=", "None", ",", "posttime", "=", "None", ")", ":", "remind", "=", "[", "'REM'", "]", "trigdates", "=", "None", "if", "hasattr", "(", "vevent", ",", "'rrule'", ")", ":", "trigdates", "=", "Remind", ".", "_parse_rruleset", "(", "vevent", ".", "rruleset", ")", "dtstart", "=", "vevent", ".", "dtstart", ".", "value", "# If we don't get timezone information, handle it as a naive datetime.", "# See https://github.com/jspricke/python-remind/issues/2 for reference.", "if", "isinstance", "(", "dtstart", ",", "datetime", ")", "and", "dtstart", ".", "tzinfo", ":", "dtstart", "=", "dtstart", ".", "astimezone", "(", "self", ".", "_localtz", ")", "dtend", "=", "None", "if", "hasattr", "(", "vevent", ",", "'dtend'", ")", ":", "dtend", "=", "vevent", ".", "dtend", ".", "value", "if", "isinstance", "(", "dtend", ",", "datetime", ")", "and", "dtend", ".", "tzinfo", ":", "dtend", "=", "dtend", ".", "astimezone", "(", "self", ".", "_localtz", ")", "if", "not", "hasattr", "(", "vevent", ",", "'rdate'", ")", "and", "not", "isinstance", "(", "trigdates", ",", "str", ")", ":", "remind", ".", "append", "(", "dtstart", ".", "strftime", "(", "'%b %d %Y'", ")", ".", "replace", "(", "' 0'", ",", "' '", ")", ")", "if", "postdate", ":", "remind", ".", "append", "(", "postdate", ")", "if", "priority", ":", "remind", ".", "append", "(", "'PRIORITY %s'", "%", "priority", ")", "if", "isinstance", "(", "trigdates", ",", "list", ")", ":", "remind", ".", "extend", "(", "trigdates", ")", "duration", "=", "Remind", ".", "_event_duration", "(", "vevent", ")", "if", "type", "(", "dtstart", ")", "is", "date", "and", "duration", ".", "days", ">", "1", ":", "remind", ".", "append", "(", "'*1'", ")", "if", "dtend", "is", "not", "None", ":", "dtend", "-=", "timedelta", "(", "days", "=", "1", ")", "remind", ".", "append", "(", "dtend", ".", "strftime", "(", "'UNTIL %b %d %Y'", ")", ".", "replace", "(", "' 0'", ",", "' '", ")", ")", "if", "isinstance", "(", "dtstart", ",", "datetime", ")", ":", "remind", ".", "append", "(", "dtstart", ".", "strftime", "(", "'AT %H:%M'", ")", ".", "replace", "(", "' 0'", ",", "' '", ")", ")", "if", "posttime", ":", "remind", ".", "append", "(", "posttime", ")", "if", "duration", ".", "total_seconds", "(", ")", ">", "0", ":", "remind", ".", "append", "(", "'DURATION %d:%02d'", "%", "divmod", "(", "duration", ".", "total_seconds", "(", ")", "/", "60", ",", "60", ")", ")", "if", "hasattr", "(", "vevent", ",", "'rdate'", ")", ":", "remind", ".", "append", "(", "Remind", ".", "_parse_rdate", "(", "vevent", ".", "rdate", ".", "value", ")", ")", "elif", "isinstance", "(", "trigdates", ",", "str", ")", ":", "remind", ".", "append", "(", "trigdates", ")", "if", "hasattr", "(", "vevent", ",", "'class'", ")", ":", "remind", ".", "append", "(", "'TAG %s'", "%", "Remind", ".", "_abbr_tag", "(", "vevent", ".", "getChildValue", "(", "'class'", ")", ")", ")", "if", "tags", ":", "remind", ".", "extend", "(", "[", "'TAG %s'", "%", "Remind", ".", "_abbr_tag", "(", "tag", ")", "for", "tag", "in", "tags", "]", ")", "if", "hasattr", "(", "vevent", ",", "'categories_list'", ")", ":", "for", "categories", "in", "vevent", ".", "categories_list", ":", "for", "category", "in", "categories", ".", "value", ":", "remind", ".", "append", "(", "'TAG %s'", "%", "Remind", ".", "_abbr_tag", "(", "category", ")", ")", "remind", ".", "append", "(", "Remind", ".", "_gen_msg", "(", "vevent", ",", "label", ",", "tail", ",", "sep", ")", ")", "return", "' '", ".", "join", "(", "remind", ")", "+", "'\\n'" ]
Generate a Remind command from the given vevent
[ "Generate", "a", "Remind", "command", "from", "the", "given", "vevent" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L431-L499
train
jspricke/python-remind
remind.py
Remind.to_reminders
def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders)
python
def to_reminders(self, ical, label=None, priority=None, tags=None, tail=None, sep=" ", postdate=None, posttime=None): """Return Remind commands for all events of a iCalendar""" if not hasattr(ical, 'vevent_list'): return '' reminders = [self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list] return ''.join(reminders)
[ "def", "to_reminders", "(", "self", ",", "ical", ",", "label", "=", "None", ",", "priority", "=", "None", ",", "tags", "=", "None", ",", "tail", "=", "None", ",", "sep", "=", "\" \"", ",", "postdate", "=", "None", ",", "posttime", "=", "None", ")", ":", "if", "not", "hasattr", "(", "ical", ",", "'vevent_list'", ")", ":", "return", "''", "reminders", "=", "[", "self", ".", "to_remind", "(", "vevent", ",", "label", ",", "priority", ",", "tags", ",", "tail", ",", "sep", ",", "postdate", ",", "posttime", ")", "for", "vevent", "in", "ical", ".", "vevent_list", "]", "return", "''", ".", "join", "(", "reminders", ")" ]
Return Remind commands for all events of a iCalendar
[ "Return", "Remind", "commands", "for", "all", "events", "of", "a", "iCalendar" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L501-L510
train
jspricke/python-remind
remind.py
Remind.append_vobject
def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat)
python
def append_vobject(self, ical, filename=None): """Append a Remind command generated from the iCalendar to the file""" if not filename: filename = self._filename elif filename not in self._reminders: return with self._lock: outdat = self.to_reminders(ical) open(filename, 'a').write(outdat) return Remind._get_uid(outdat)
[ "def", "append_vobject", "(", "self", ",", "ical", ",", "filename", "=", "None", ")", ":", "if", "not", "filename", ":", "filename", "=", "self", ".", "_filename", "elif", "filename", "not", "in", "self", ".", "_reminders", ":", "return", "with", "self", ".", "_lock", ":", "outdat", "=", "self", ".", "to_reminders", "(", "ical", ")", "open", "(", "filename", ",", "'a'", ")", ".", "write", "(", "outdat", ")", "return", "Remind", ".", "_get_uid", "(", "outdat", ")" ]
Append a Remind command generated from the iCalendar to the file
[ "Append", "a", "Remind", "command", "generated", "from", "the", "iCalendar", "to", "the", "file" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L516-L527
train
jspricke/python-remind
remind.py
Remind.remove
def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break
python
def remove(self, uid, filename=None): """Remove the Remind command with the uid from the file""" if not filename: filename = self._filename elif filename not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(filename).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(filename, 'w').writelines(rem) break
[ "def", "remove", "(", "self", ",", "uid", ",", "filename", "=", "None", ")", ":", "if", "not", "filename", ":", "filename", "=", "self", ".", "_filename", "elif", "filename", "not", "in", "self", ".", "_reminders", ":", "return", "uid", "=", "uid", ".", "split", "(", "'@'", ")", "[", "0", "]", "with", "self", ".", "_lock", ":", "rem", "=", "open", "(", "filename", ")", ".", "readlines", "(", ")", "for", "(", "index", ",", "line", ")", "in", "enumerate", "(", "rem", ")", ":", "if", "uid", "==", "md5", "(", "line", "[", ":", "-", "1", "]", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", ":", "del", "rem", "[", "index", "]", "open", "(", "filename", ",", "'w'", ")", ".", "writelines", "(", "rem", ")", "break" ]
Remove the Remind command with the uid from the file
[ "Remove", "the", "Remind", "command", "with", "the", "uid", "from", "the", "file" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L529-L544
train
jspricke/python-remind
remind.py
Remind.move_vobject
def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break
python
def move_vobject(self, uid, from_file, to_file): """Move the Remind command with the uid from from_file to to_file""" if from_file not in self._reminders or to_file not in self._reminders: return uid = uid.split('@')[0] with self._lock: rem = open(from_file).readlines() for (index, line) in enumerate(rem): if uid == md5(line[:-1].encode('utf-8')).hexdigest(): del rem[index] open(from_file, 'w').writelines(rem) open(to_file, 'a').write(line) break
[ "def", "move_vobject", "(", "self", ",", "uid", ",", "from_file", ",", "to_file", ")", ":", "if", "from_file", "not", "in", "self", ".", "_reminders", "or", "to_file", "not", "in", "self", ".", "_reminders", ":", "return", "uid", "=", "uid", ".", "split", "(", "'@'", ")", "[", "0", "]", "with", "self", ".", "_lock", ":", "rem", "=", "open", "(", "from_file", ")", ".", "readlines", "(", ")", "for", "(", "index", ",", "line", ")", "in", "enumerate", "(", "rem", ")", ":", "if", "uid", "==", "md5", "(", "line", "[", ":", "-", "1", "]", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", ":", "del", "rem", "[", "index", "]", "open", "(", "from_file", ",", "'w'", ")", ".", "writelines", "(", "rem", ")", "open", "(", "to_file", ",", "'a'", ")", ".", "write", "(", "line", ")", "break" ]
Move the Remind command with the uid from from_file to to_file
[ "Move", "the", "Remind", "command", "with", "the", "uid", "from", "from_file", "to", "to_file" ]
dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1
https://github.com/jspricke/python-remind/blob/dda2aa8fc20b87b9c9fcbca2b67bce73911d05d1/remind.py#L568-L582
train
heinzK1X/pylibconfig2
pylibconfig2/conf_types.py
Config.expand_include
def expand_include(filename): """ Expand the content of a file into a string. If @include directives are found in the config, they are expanded by this function. In case recursion is detected or a RunTimeError is thrown, ``None`` is returned. """ open_files = set() def _expand_include_rec(filename): if filename in open_files: raise RuntimeError('Recursive include statement detected for ' 'file: ' + filename) else: open_files.add(filename) with open(filename) as open_file: for line in open_file: line_stripped = line.strip().replace("//", "#") if line_stripped.startswith('@include '): inc_to_clean = line_stripped.split(None, 1)[1] inc_filename = inc_to_clean.replace('"'," ").strip() for included_line in _expand_include_rec(inc_filename): yield included_line else: yield line open_files.remove(filename) try: lines = [] for line in _expand_include_rec(filename): lines.append(line) return ''.join(lines) except RuntimeError: return None
python
def expand_include(filename): """ Expand the content of a file into a string. If @include directives are found in the config, they are expanded by this function. In case recursion is detected or a RunTimeError is thrown, ``None`` is returned. """ open_files = set() def _expand_include_rec(filename): if filename in open_files: raise RuntimeError('Recursive include statement detected for ' 'file: ' + filename) else: open_files.add(filename) with open(filename) as open_file: for line in open_file: line_stripped = line.strip().replace("//", "#") if line_stripped.startswith('@include '): inc_to_clean = line_stripped.split(None, 1)[1] inc_filename = inc_to_clean.replace('"'," ").strip() for included_line in _expand_include_rec(inc_filename): yield included_line else: yield line open_files.remove(filename) try: lines = [] for line in _expand_include_rec(filename): lines.append(line) return ''.join(lines) except RuntimeError: return None
[ "def", "expand_include", "(", "filename", ")", ":", "open_files", "=", "set", "(", ")", "def", "_expand_include_rec", "(", "filename", ")", ":", "if", "filename", "in", "open_files", ":", "raise", "RuntimeError", "(", "'Recursive include statement detected for '", "'file: '", "+", "filename", ")", "else", ":", "open_files", ".", "add", "(", "filename", ")", "with", "open", "(", "filename", ")", "as", "open_file", ":", "for", "line", "in", "open_file", ":", "line_stripped", "=", "line", ".", "strip", "(", ")", ".", "replace", "(", "\"//\"", ",", "\"#\"", ")", "if", "line_stripped", ".", "startswith", "(", "'@include '", ")", ":", "inc_to_clean", "=", "line_stripped", ".", "split", "(", "None", ",", "1", ")", "[", "1", "]", "inc_filename", "=", "inc_to_clean", ".", "replace", "(", "'\"'", ",", "\" \"", ")", ".", "strip", "(", ")", "for", "included_line", "in", "_expand_include_rec", "(", "inc_filename", ")", ":", "yield", "included_line", "else", ":", "yield", "line", "open_files", ".", "remove", "(", "filename", ")", "try", ":", "lines", "=", "[", "]", "for", "line", "in", "_expand_include_rec", "(", "filename", ")", ":", "lines", ".", "append", "(", "line", ")", "return", "''", ".", "join", "(", "lines", ")", "except", "RuntimeError", ":", "return", "None" ]
Expand the content of a file into a string. If @include directives are found in the config, they are expanded by this function. In case recursion is detected or a RunTimeError is thrown, ``None`` is returned.
[ "Expand", "the", "content", "of", "a", "file", "into", "a", "string", "." ]
f3a851ac780da28a42264c24aac51b54fbd63f81
https://github.com/heinzK1X/pylibconfig2/blob/f3a851ac780da28a42264c24aac51b54fbd63f81/pylibconfig2/conf_types.py#L290-L326
train
moonso/ped_parser
ped_parser/individual.py
Individual.to_json
def to_json(self): """ Return the individual info in a dictionary for json. """ self.logger.debug("Returning json info") individual_info = { 'family_id': self.family, 'id':self.individual_id, 'sex':str(self.sex), 'phenotype': str(self.phenotype), 'mother': self.mother, 'father': self.father, 'extra_info': self.extra_info } return individual_info
python
def to_json(self): """ Return the individual info in a dictionary for json. """ self.logger.debug("Returning json info") individual_info = { 'family_id': self.family, 'id':self.individual_id, 'sex':str(self.sex), 'phenotype': str(self.phenotype), 'mother': self.mother, 'father': self.father, 'extra_info': self.extra_info } return individual_info
[ "def", "to_json", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Returning json info\"", ")", "individual_info", "=", "{", "'family_id'", ":", "self", ".", "family", ",", "'id'", ":", "self", ".", "individual_id", ",", "'sex'", ":", "str", "(", "self", ".", "sex", ")", ",", "'phenotype'", ":", "str", "(", "self", ".", "phenotype", ")", ",", "'mother'", ":", "self", ".", "mother", ",", "'father'", ":", "self", ".", "father", ",", "'extra_info'", ":", "self", ".", "extra_info", "}", "return", "individual_info" ]
Return the individual info in a dictionary for json.
[ "Return", "the", "individual", "info", "in", "a", "dictionary", "for", "json", "." ]
a7393e47139532782ea3c821aabea33d46f94323
https://github.com/moonso/ped_parser/blob/a7393e47139532782ea3c821aabea33d46f94323/ped_parser/individual.py#L122-L136
train
moonso/ped_parser
ped_parser/individual.py
Individual.to_madeline
def to_madeline(self): """ Return the individual info in a madeline formated string """ #Convert sex to madeleine type self.logger.debug("Returning madeline info") if self.sex == 1: madeline_gender = 'M' elif self.sex == 2: madeline_gender = 'F' else: madeline_gender = '.' #Convert father to madeleine type if self.father == '0': madeline_father = '.' else: madeline_father = self.father #Convert mother to madeleine type if self.mother == '0': madeline_mother = '.' else: madeline_mother = self.mother #Convert phenotype to madeleine type if self.phenotype == 1: madeline_phenotype = 'U' elif self.phenotype == 2: madeline_phenotype = 'A' else: madeline_phenotype = '.' return "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}".format( self.family, self.individual_id, madeline_gender, madeline_father, madeline_mother, madeline_phenotype, self.proband, self.consultand, self.alive )
python
def to_madeline(self): """ Return the individual info in a madeline formated string """ #Convert sex to madeleine type self.logger.debug("Returning madeline info") if self.sex == 1: madeline_gender = 'M' elif self.sex == 2: madeline_gender = 'F' else: madeline_gender = '.' #Convert father to madeleine type if self.father == '0': madeline_father = '.' else: madeline_father = self.father #Convert mother to madeleine type if self.mother == '0': madeline_mother = '.' else: madeline_mother = self.mother #Convert phenotype to madeleine type if self.phenotype == 1: madeline_phenotype = 'U' elif self.phenotype == 2: madeline_phenotype = 'A' else: madeline_phenotype = '.' return "{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}".format( self.family, self.individual_id, madeline_gender, madeline_father, madeline_mother, madeline_phenotype, self.proband, self.consultand, self.alive )
[ "def", "to_madeline", "(", "self", ")", ":", "#Convert sex to madeleine type", "self", ".", "logger", ".", "debug", "(", "\"Returning madeline info\"", ")", "if", "self", ".", "sex", "==", "1", ":", "madeline_gender", "=", "'M'", "elif", "self", ".", "sex", "==", "2", ":", "madeline_gender", "=", "'F'", "else", ":", "madeline_gender", "=", "'.'", "#Convert father to madeleine type", "if", "self", ".", "father", "==", "'0'", ":", "madeline_father", "=", "'.'", "else", ":", "madeline_father", "=", "self", ".", "father", "#Convert mother to madeleine type", "if", "self", ".", "mother", "==", "'0'", ":", "madeline_mother", "=", "'.'", "else", ":", "madeline_mother", "=", "self", ".", "mother", "#Convert phenotype to madeleine type", "if", "self", ".", "phenotype", "==", "1", ":", "madeline_phenotype", "=", "'U'", "elif", "self", ".", "phenotype", "==", "2", ":", "madeline_phenotype", "=", "'A'", "else", ":", "madeline_phenotype", "=", "'.'", "return", "\"{0}\\t{1}\\t{2}\\t{3}\\t{4}\\t{5}\\t{6}\\t{7}\\t{8}\"", ".", "format", "(", "self", ".", "family", ",", "self", ".", "individual_id", ",", "madeline_gender", ",", "madeline_father", ",", "madeline_mother", ",", "madeline_phenotype", ",", "self", ".", "proband", ",", "self", ".", "consultand", ",", "self", ".", "alive", ")" ]
Return the individual info in a madeline formated string
[ "Return", "the", "individual", "info", "in", "a", "madeline", "formated", "string" ]
a7393e47139532782ea3c821aabea33d46f94323
https://github.com/moonso/ped_parser/blob/a7393e47139532782ea3c821aabea33d46f94323/ped_parser/individual.py#L138-L172
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/helper_functions.py
module_name_from_path
def module_name_from_path(folder_name, verbose=False): """ takes in a path to a folder or file and return the module path and the path to the module the module is idenitified by the path being in os.path, e.g. if /Users/Projects/Python/ is in os.path, then folder_name = '/Users/PycharmProjects/pylabcontrol/pylabcontrol/scripts/script_dummy.pyc' returns '/Users/PycharmProjects/' as the path and pylabcontrol.scripts.script_dummy as the module Args: folder_name: path to a file of the form '/Users/PycharmProjects/pylabcontrol/pylabcontrol/scripts/script_dummy.pyc' Returns: module: a string of the form, e.g. pylabcontrol.scripts.script_dummy ... path: a string with the path to the module, e.g. /Users/PycharmProjects/ """ # strip off endings folder_name = folder_name.split('.pyc')[0] folder_name = folder_name.split('.py')[0] folder_name = os.path.normpath(folder_name) path = folder_name + '/' package = get_python_package(path) # path = folder_name module = [] if verbose: print(('folder_name', folder_name)) # os_sys_path = os.sys.path # # if os.path.normpath(path) in os_sys_path: # if verbose: # print('warning: path in sys.path!') # os_sys_path.remove(os.path.normpath(path)) # # # if verbose: # for elem in os_sys_path: # # print('os.sys.path', elem) while True: path = os.path.dirname(path) module.append(os.path.basename(path)) if os.path.basename(path) == package: path = os.path.dirname(path) break # failed to identify the module if os.path.dirname(path) == path: path, module = None, None break if verbose: print(('path', path, os.path.dirname(path))) # if path == os.path.dirname(path): # if verbose: # print('break -- os.path.dirname(path)', os.path.dirname(path)) # # path, module = None, None # break # if verbose: print(('module', module)) # OLD START # while path not in os_sys_path: # path = os.path.dirname(path) # # if verbose: # print('path', path, os.path.dirname(path)) # # if path == os.path.dirname(path): # if verbose: # print('break -- os.path.dirname(path)', os.path.dirname(path)) # # path, module = None, None # break # module.append(os.path.basename(path)) # # if verbose: # print('module', module) # OLD END if verbose: print(('module', module)) # module = module[:-1] # print('mod', module) # from the list construct the path like b26_toolkit.pylabcontrol.scripts and load it module.reverse() module = '.'.join(module) return module, path
python
def module_name_from_path(folder_name, verbose=False): """ takes in a path to a folder or file and return the module path and the path to the module the module is idenitified by the path being in os.path, e.g. if /Users/Projects/Python/ is in os.path, then folder_name = '/Users/PycharmProjects/pylabcontrol/pylabcontrol/scripts/script_dummy.pyc' returns '/Users/PycharmProjects/' as the path and pylabcontrol.scripts.script_dummy as the module Args: folder_name: path to a file of the form '/Users/PycharmProjects/pylabcontrol/pylabcontrol/scripts/script_dummy.pyc' Returns: module: a string of the form, e.g. pylabcontrol.scripts.script_dummy ... path: a string with the path to the module, e.g. /Users/PycharmProjects/ """ # strip off endings folder_name = folder_name.split('.pyc')[0] folder_name = folder_name.split('.py')[0] folder_name = os.path.normpath(folder_name) path = folder_name + '/' package = get_python_package(path) # path = folder_name module = [] if verbose: print(('folder_name', folder_name)) # os_sys_path = os.sys.path # # if os.path.normpath(path) in os_sys_path: # if verbose: # print('warning: path in sys.path!') # os_sys_path.remove(os.path.normpath(path)) # # # if verbose: # for elem in os_sys_path: # # print('os.sys.path', elem) while True: path = os.path.dirname(path) module.append(os.path.basename(path)) if os.path.basename(path) == package: path = os.path.dirname(path) break # failed to identify the module if os.path.dirname(path) == path: path, module = None, None break if verbose: print(('path', path, os.path.dirname(path))) # if path == os.path.dirname(path): # if verbose: # print('break -- os.path.dirname(path)', os.path.dirname(path)) # # path, module = None, None # break # if verbose: print(('module', module)) # OLD START # while path not in os_sys_path: # path = os.path.dirname(path) # # if verbose: # print('path', path, os.path.dirname(path)) # # if path == os.path.dirname(path): # if verbose: # print('break -- os.path.dirname(path)', os.path.dirname(path)) # # path, module = None, None # break # module.append(os.path.basename(path)) # # if verbose: # print('module', module) # OLD END if verbose: print(('module', module)) # module = module[:-1] # print('mod', module) # from the list construct the path like b26_toolkit.pylabcontrol.scripts and load it module.reverse() module = '.'.join(module) return module, path
[ "def", "module_name_from_path", "(", "folder_name", ",", "verbose", "=", "False", ")", ":", "# strip off endings", "folder_name", "=", "folder_name", ".", "split", "(", "'.pyc'", ")", "[", "0", "]", "folder_name", "=", "folder_name", ".", "split", "(", "'.py'", ")", "[", "0", "]", "folder_name", "=", "os", ".", "path", ".", "normpath", "(", "folder_name", ")", "path", "=", "folder_name", "+", "'/'", "package", "=", "get_python_package", "(", "path", ")", "# path = folder_name", "module", "=", "[", "]", "if", "verbose", ":", "print", "(", "(", "'folder_name'", ",", "folder_name", ")", ")", "# os_sys_path = os.sys.path", "#", "# if os.path.normpath(path) in os_sys_path:", "# if verbose:", "# print('warning: path in sys.path!')", "# os_sys_path.remove(os.path.normpath(path))", "#", "#", "# if verbose:", "# for elem in os_sys_path:", "#", "# print('os.sys.path', elem)", "while", "True", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "module", ".", "append", "(", "os", ".", "path", ".", "basename", "(", "path", ")", ")", "if", "os", ".", "path", ".", "basename", "(", "path", ")", "==", "package", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "break", "# failed to identify the module", "if", "os", ".", "path", ".", "dirname", "(", "path", ")", "==", "path", ":", "path", ",", "module", "=", "None", ",", "None", "break", "if", "verbose", ":", "print", "(", "(", "'path'", ",", "path", ",", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", ")", "# if path == os.path.dirname(path):", "# if verbose:", "# print('break -- os.path.dirname(path)', os.path.dirname(path))", "# # path, module = None, None", "# break", "#", "if", "verbose", ":", "print", "(", "(", "'module'", ",", "module", ")", ")", "# OLD START", "# while path not in os_sys_path:", "# path = os.path.dirname(path)", "#", "# if verbose:", "# print('path', path, os.path.dirname(path))", "#", "# if path == os.path.dirname(path):", "# if verbose:", "# print('break -- os.path.dirname(path)', os.path.dirname(path))", "# # path, module = None, None", "# break", "# module.append(os.path.basename(path))", "#", "# if verbose:", "# print('module', module)", "# OLD END", "if", "verbose", ":", "print", "(", "(", "'module'", ",", "module", ")", ")", "# module = module[:-1]", "# print('mod', module)", "# from the list construct the path like b26_toolkit.pylabcontrol.scripts and load it", "module", ".", "reverse", "(", ")", "module", "=", "'.'", ".", "join", "(", "module", ")", "return", "module", ",", "path" ]
takes in a path to a folder or file and return the module path and the path to the module the module is idenitified by the path being in os.path, e.g. if /Users/Projects/Python/ is in os.path, then folder_name = '/Users/PycharmProjects/pylabcontrol/pylabcontrol/scripts/script_dummy.pyc' returns '/Users/PycharmProjects/' as the path and pylabcontrol.scripts.script_dummy as the module Args: folder_name: path to a file of the form '/Users/PycharmProjects/pylabcontrol/pylabcontrol/scripts/script_dummy.pyc' Returns: module: a string of the form, e.g. pylabcontrol.scripts.script_dummy ... path: a string with the path to the module, e.g. /Users/PycharmProjects/
[ "takes", "in", "a", "path", "to", "a", "folder", "or", "file", "and", "return", "the", "module", "path", "and", "the", "path", "to", "the", "module" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/helper_functions.py#L23-L127
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/helper_functions.py
explore_package
def explore_package(module_name): """ returns all the packages in the module Args: module_name: name of module Returns: """ packages = [] loader = pkgutil.get_loader(module_name) for sub_module in pkgutil.walk_packages([os.path.dirname(loader.get_filename())], prefix=module_name + '.'): _, sub_module_name, _ = sub_module packages.append(sub_module_name) return packages
python
def explore_package(module_name): """ returns all the packages in the module Args: module_name: name of module Returns: """ packages = [] loader = pkgutil.get_loader(module_name) for sub_module in pkgutil.walk_packages([os.path.dirname(loader.get_filename())], prefix=module_name + '.'): _, sub_module_name, _ = sub_module packages.append(sub_module_name) return packages
[ "def", "explore_package", "(", "module_name", ")", ":", "packages", "=", "[", "]", "loader", "=", "pkgutil", ".", "get_loader", "(", "module_name", ")", "for", "sub_module", "in", "pkgutil", ".", "walk_packages", "(", "[", "os", ".", "path", ".", "dirname", "(", "loader", ".", "get_filename", "(", ")", ")", "]", ",", "prefix", "=", "module_name", "+", "'.'", ")", ":", "_", ",", "sub_module_name", ",", "_", "=", "sub_module", "packages", ".", "append", "(", "sub_module_name", ")", "return", "packages" ]
returns all the packages in the module Args: module_name: name of module Returns:
[ "returns", "all", "the", "packages", "in", "the", "module" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/helper_functions.py#L201-L219
train
CitrineInformatics/pif-dft
dfttopif/parsers/base.py
DFTParser.generate_from_directory
def generate_from_directory(cls, directory): """Create a parser by defining which input files it will read from. Input: directory - str, directory to read from files - str, list of files from which to search. """ files = [os.path.join(directory, f) for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))] return cls(files)
python
def generate_from_directory(cls, directory): """Create a parser by defining which input files it will read from. Input: directory - str, directory to read from files - str, list of files from which to search. """ files = [os.path.join(directory, f) for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))] return cls(files)
[ "def", "generate_from_directory", "(", "cls", ",", "directory", ")", ":", "files", "=", "[", "os", ".", "path", ".", "join", "(", "directory", ",", "f", ")", "for", "f", "in", "os", ".", "listdir", "(", "directory", ")", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "f", ")", ")", "]", "return", "cls", "(", "files", ")" ]
Create a parser by defining which input files it will read from. Input: directory - str, directory to read from files - str, list of files from which to search.
[ "Create", "a", "parser", "by", "defining", "which", "input", "files", "it", "will", "read", "from", "." ]
d5411dc1f6c6e8d454b132977ca7ab3bb8131a80
https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/parsers/base.py#L57-L66
train
CitrineInformatics/pif-dft
dfttopif/parsers/base.py
DFTParser.get_density
def get_density(self): """Compute the density from the output structure""" strc = self.get_output_structure() density = sum(strc.get_masses()) / strc.get_volume() * 1.660539040 return Property(scalars=[Scalar(value=density)], units="g/(cm^3)")
python
def get_density(self): """Compute the density from the output structure""" strc = self.get_output_structure() density = sum(strc.get_masses()) / strc.get_volume() * 1.660539040 return Property(scalars=[Scalar(value=density)], units="g/(cm^3)")
[ "def", "get_density", "(", "self", ")", ":", "strc", "=", "self", ".", "get_output_structure", "(", ")", "density", "=", "sum", "(", "strc", ".", "get_masses", "(", ")", ")", "/", "strc", ".", "get_volume", "(", ")", "*", "1.660539040", "return", "Property", "(", "scalars", "=", "[", "Scalar", "(", "value", "=", "density", ")", "]", ",", "units", "=", "\"g/(cm^3)\"", ")" ]
Compute the density from the output structure
[ "Compute", "the", "density", "from", "the", "output", "structure" ]
d5411dc1f6c6e8d454b132977ca7ab3bb8131a80
https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/parsers/base.py#L148-L152
train
CitrineInformatics/pif-dft
dfttopif/parsers/base.py
DFTParser.get_number_of_atoms
def get_number_of_atoms(self): """Get the number of atoms in the calculated structure. Returns: Property, where number of atoms is a scalar. """ strc = self.get_output_structure() if not strc: return None return Property(scalars=[Scalar(value=len(strc))], units="/unit cell")
python
def get_number_of_atoms(self): """Get the number of atoms in the calculated structure. Returns: Property, where number of atoms is a scalar. """ strc = self.get_output_structure() if not strc: return None return Property(scalars=[Scalar(value=len(strc))], units="/unit cell")
[ "def", "get_number_of_atoms", "(", "self", ")", ":", "strc", "=", "self", ".", "get_output_structure", "(", ")", "if", "not", "strc", ":", "return", "None", "return", "Property", "(", "scalars", "=", "[", "Scalar", "(", "value", "=", "len", "(", "strc", ")", ")", "]", ",", "units", "=", "\"/unit cell\"", ")" ]
Get the number of atoms in the calculated structure. Returns: Property, where number of atoms is a scalar.
[ "Get", "the", "number", "of", "atoms", "in", "the", "calculated", "structure", "." ]
d5411dc1f6c6e8d454b132977ca7ab3bb8131a80
https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/parsers/base.py#L296-L304
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/read_write_functions.py
load_b26_file
def load_b26_file(file_name): """ loads a .b26 file into a dictionary Args: file_name: Returns: dictionary with keys instrument, scripts, probes """ # file_name = "Z:\Lab\Cantilever\Measurements\\tmp_\\a" assert os.path.exists(file_name) with open(file_name, 'r') as infile: data = yaml.safe_load(infile) return data
python
def load_b26_file(file_name): """ loads a .b26 file into a dictionary Args: file_name: Returns: dictionary with keys instrument, scripts, probes """ # file_name = "Z:\Lab\Cantilever\Measurements\\tmp_\\a" assert os.path.exists(file_name) with open(file_name, 'r') as infile: data = yaml.safe_load(infile) return data
[ "def", "load_b26_file", "(", "file_name", ")", ":", "# file_name = \"Z:\\Lab\\Cantilever\\Measurements\\\\tmp_\\\\a\"", "assert", "os", ".", "path", ".", "exists", "(", "file_name", ")", "with", "open", "(", "file_name", ",", "'r'", ")", "as", "infile", ":", "data", "=", "yaml", ".", "safe_load", "(", "infile", ")", "return", "data" ]
loads a .b26 file into a dictionary Args: file_name: Returns: dictionary with keys instrument, scripts, probes
[ "loads", "a", ".", "b26", "file", "into", "a", "dictionary" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/read_write_functions.py#L76-L92
train
datamachine/twx
twx/mtproto/mtproto.py
Datacenter.recv_message
def recv_message(self, debug=False): """ Reading socket and receiving message from server. Check the CRC32. """ if debug: packet = self.sock.recv(1024) # reads how many bytes to read hexdump(packet) packet_length_data = self.sock.recv(4) # reads how many bytes to read if len(packet_length_data) < 4: raise Exception("Nothing in the socket!") packet_length = struct.unpack("<I", packet_length_data)[0] packet = self.sock.recv(packet_length - 4) # read the rest of bytes from socket # check the CRC32 if not crc32(packet_length_data + packet[0:-4]) == struct.unpack('<I', packet[-4:])[0]: raise Exception("CRC32 was not correct!") x = struct.unpack("<I", packet[:4]) auth_key_id = packet[4:12] if auth_key_id == b'\x00\x00\x00\x00\x00\x00\x00\x00': # No encryption - Plain text (message_id, message_length) = struct.unpack("<QI", packet[12:24]) data = packet[24:24+message_length] elif auth_key_id == self.auth_key_id: pass message_key = packet[12:28] encrypted_data = packet[28:-4] aes_key, aes_iv = self.aes_calculate(message_key, direction="from server") decrypted_data = crypt.ige_decrypt(encrypted_data, aes_key, aes_iv) assert decrypted_data[0:8] == self.server_salt assert decrypted_data[8:16] == self.session_id message_id = decrypted_data[16:24] seq_no = struct.unpack("<I", decrypted_data[24:28])[0] message_data_length = struct.unpack("<I", decrypted_data[28:32])[0] data = decrypted_data[32:32+message_data_length] else: raise Exception("Got unknown auth_key id") return data
python
def recv_message(self, debug=False): """ Reading socket and receiving message from server. Check the CRC32. """ if debug: packet = self.sock.recv(1024) # reads how many bytes to read hexdump(packet) packet_length_data = self.sock.recv(4) # reads how many bytes to read if len(packet_length_data) < 4: raise Exception("Nothing in the socket!") packet_length = struct.unpack("<I", packet_length_data)[0] packet = self.sock.recv(packet_length - 4) # read the rest of bytes from socket # check the CRC32 if not crc32(packet_length_data + packet[0:-4]) == struct.unpack('<I', packet[-4:])[0]: raise Exception("CRC32 was not correct!") x = struct.unpack("<I", packet[:4]) auth_key_id = packet[4:12] if auth_key_id == b'\x00\x00\x00\x00\x00\x00\x00\x00': # No encryption - Plain text (message_id, message_length) = struct.unpack("<QI", packet[12:24]) data = packet[24:24+message_length] elif auth_key_id == self.auth_key_id: pass message_key = packet[12:28] encrypted_data = packet[28:-4] aes_key, aes_iv = self.aes_calculate(message_key, direction="from server") decrypted_data = crypt.ige_decrypt(encrypted_data, aes_key, aes_iv) assert decrypted_data[0:8] == self.server_salt assert decrypted_data[8:16] == self.session_id message_id = decrypted_data[16:24] seq_no = struct.unpack("<I", decrypted_data[24:28])[0] message_data_length = struct.unpack("<I", decrypted_data[28:32])[0] data = decrypted_data[32:32+message_data_length] else: raise Exception("Got unknown auth_key id") return data
[ "def", "recv_message", "(", "self", ",", "debug", "=", "False", ")", ":", "if", "debug", ":", "packet", "=", "self", ".", "sock", ".", "recv", "(", "1024", ")", "# reads how many bytes to read", "hexdump", "(", "packet", ")", "packet_length_data", "=", "self", ".", "sock", ".", "recv", "(", "4", ")", "# reads how many bytes to read", "if", "len", "(", "packet_length_data", ")", "<", "4", ":", "raise", "Exception", "(", "\"Nothing in the socket!\"", ")", "packet_length", "=", "struct", ".", "unpack", "(", "\"<I\"", ",", "packet_length_data", ")", "[", "0", "]", "packet", "=", "self", ".", "sock", ".", "recv", "(", "packet_length", "-", "4", ")", "# read the rest of bytes from socket", "# check the CRC32", "if", "not", "crc32", "(", "packet_length_data", "+", "packet", "[", "0", ":", "-", "4", "]", ")", "==", "struct", ".", "unpack", "(", "'<I'", ",", "packet", "[", "-", "4", ":", "]", ")", "[", "0", "]", ":", "raise", "Exception", "(", "\"CRC32 was not correct!\"", ")", "x", "=", "struct", ".", "unpack", "(", "\"<I\"", ",", "packet", "[", ":", "4", "]", ")", "auth_key_id", "=", "packet", "[", "4", ":", "12", "]", "if", "auth_key_id", "==", "b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'", ":", "# No encryption - Plain text", "(", "message_id", ",", "message_length", ")", "=", "struct", ".", "unpack", "(", "\"<QI\"", ",", "packet", "[", "12", ":", "24", "]", ")", "data", "=", "packet", "[", "24", ":", "24", "+", "message_length", "]", "elif", "auth_key_id", "==", "self", ".", "auth_key_id", ":", "pass", "message_key", "=", "packet", "[", "12", ":", "28", "]", "encrypted_data", "=", "packet", "[", "28", ":", "-", "4", "]", "aes_key", ",", "aes_iv", "=", "self", ".", "aes_calculate", "(", "message_key", ",", "direction", "=", "\"from server\"", ")", "decrypted_data", "=", "crypt", ".", "ige_decrypt", "(", "encrypted_data", ",", "aes_key", ",", "aes_iv", ")", "assert", "decrypted_data", "[", "0", ":", "8", "]", "==", "self", ".", "server_salt", "assert", "decrypted_data", "[", "8", ":", "16", "]", "==", "self", ".", "session_id", "message_id", "=", "decrypted_data", "[", "16", ":", "24", "]", "seq_no", "=", "struct", ".", "unpack", "(", "\"<I\"", ",", "decrypted_data", "[", "24", ":", "28", "]", ")", "[", "0", "]", "message_data_length", "=", "struct", ".", "unpack", "(", "\"<I\"", ",", "decrypted_data", "[", "28", ":", "32", "]", ")", "[", "0", "]", "data", "=", "decrypted_data", "[", "32", ":", "32", "+", "message_data_length", "]", "else", ":", "raise", "Exception", "(", "\"Got unknown auth_key id\"", ")", "return", "data" ]
Reading socket and receiving message from server. Check the CRC32.
[ "Reading", "socket", "and", "receiving", "message", "from", "server", ".", "Check", "the", "CRC32", "." ]
d9633f12f3647b1e54ba87b70b39df3b7e02b4eb
https://github.com/datamachine/twx/blob/d9633f12f3647b1e54ba87b70b39df3b7e02b4eb/twx/mtproto/mtproto.py#L248-L286
train
idlesign/django-sitecats
sitecats/models.py
ModelWithCategory.get_category_lists
def get_category_lists(self, init_kwargs=None, additional_parents_aliases=None): """Returns a list of CategoryList objects, associated with this model instance. :param dict|None init_kwargs: :param list|None additional_parents_aliases: :rtype: list|CategoryRequestHandler :return: """ if self._category_editor is not None: # Return editor lists instead of plain lists if it's enabled. return self._category_editor.get_lists() from .toolbox import get_category_lists init_kwargs = init_kwargs or {} catlist_kwargs = {} if self._category_lists_init_kwargs is not None: catlist_kwargs.update(self._category_lists_init_kwargs) catlist_kwargs.update(init_kwargs) lists = get_category_lists(catlist_kwargs, additional_parents_aliases, obj=self) return lists
python
def get_category_lists(self, init_kwargs=None, additional_parents_aliases=None): """Returns a list of CategoryList objects, associated with this model instance. :param dict|None init_kwargs: :param list|None additional_parents_aliases: :rtype: list|CategoryRequestHandler :return: """ if self._category_editor is not None: # Return editor lists instead of plain lists if it's enabled. return self._category_editor.get_lists() from .toolbox import get_category_lists init_kwargs = init_kwargs or {} catlist_kwargs = {} if self._category_lists_init_kwargs is not None: catlist_kwargs.update(self._category_lists_init_kwargs) catlist_kwargs.update(init_kwargs) lists = get_category_lists(catlist_kwargs, additional_parents_aliases, obj=self) return lists
[ "def", "get_category_lists", "(", "self", ",", "init_kwargs", "=", "None", ",", "additional_parents_aliases", "=", "None", ")", ":", "if", "self", ".", "_category_editor", "is", "not", "None", ":", "# Return editor lists instead of plain lists if it's enabled.", "return", "self", ".", "_category_editor", ".", "get_lists", "(", ")", "from", ".", "toolbox", "import", "get_category_lists", "init_kwargs", "=", "init_kwargs", "or", "{", "}", "catlist_kwargs", "=", "{", "}", "if", "self", ".", "_category_lists_init_kwargs", "is", "not", "None", ":", "catlist_kwargs", ".", "update", "(", "self", ".", "_category_lists_init_kwargs", ")", "catlist_kwargs", ".", "update", "(", "init_kwargs", ")", "lists", "=", "get_category_lists", "(", "catlist_kwargs", ",", "additional_parents_aliases", ",", "obj", "=", "self", ")", "return", "lists" ]
Returns a list of CategoryList objects, associated with this model instance. :param dict|None init_kwargs: :param list|None additional_parents_aliases: :rtype: list|CategoryRequestHandler :return:
[ "Returns", "a", "list", "of", "CategoryList", "objects", "associated", "with", "this", "model", "instance", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/models.py#L229-L252
train
idlesign/django-sitecats
sitecats/models.py
ModelWithCategory.enable_category_lists_editor
def enable_category_lists_editor(self, request, editor_init_kwargs=None, additional_parents_aliases=None, lists_init_kwargs=None, handler_init_kwargs=None): """Enables editor functionality for categories of this object. :param Request request: Django request object :param dict editor_init_kwargs: Keyword args to initialize category lists editor with. See CategoryList.enable_editor() :param list additional_parents_aliases: Aliases of categories for editor to render even if this object has no tie to them. :param dict lists_init_kwargs: Keyword args to initialize CategoryList objects with :param dict handler_init_kwargs: Keyword args to initialize CategoryRequestHandler object with :return: """ from .toolbox import CategoryRequestHandler additional_parents_aliases = additional_parents_aliases or [] lists_init_kwargs = lists_init_kwargs or {} editor_init_kwargs = editor_init_kwargs or {} handler_init_kwargs = handler_init_kwargs or {} handler = CategoryRequestHandler(request, self, **handler_init_kwargs) lists = self.get_category_lists( init_kwargs=lists_init_kwargs, additional_parents_aliases=additional_parents_aliases) handler.register_lists(lists, lists_init_kwargs=lists_init_kwargs, editor_init_kwargs=editor_init_kwargs) self._category_editor = handler # Set link to handler to mutate get_category_lists() behaviour. return handler.listen()
python
def enable_category_lists_editor(self, request, editor_init_kwargs=None, additional_parents_aliases=None, lists_init_kwargs=None, handler_init_kwargs=None): """Enables editor functionality for categories of this object. :param Request request: Django request object :param dict editor_init_kwargs: Keyword args to initialize category lists editor with. See CategoryList.enable_editor() :param list additional_parents_aliases: Aliases of categories for editor to render even if this object has no tie to them. :param dict lists_init_kwargs: Keyword args to initialize CategoryList objects with :param dict handler_init_kwargs: Keyword args to initialize CategoryRequestHandler object with :return: """ from .toolbox import CategoryRequestHandler additional_parents_aliases = additional_parents_aliases or [] lists_init_kwargs = lists_init_kwargs or {} editor_init_kwargs = editor_init_kwargs or {} handler_init_kwargs = handler_init_kwargs or {} handler = CategoryRequestHandler(request, self, **handler_init_kwargs) lists = self.get_category_lists( init_kwargs=lists_init_kwargs, additional_parents_aliases=additional_parents_aliases) handler.register_lists(lists, lists_init_kwargs=lists_init_kwargs, editor_init_kwargs=editor_init_kwargs) self._category_editor = handler # Set link to handler to mutate get_category_lists() behaviour. return handler.listen()
[ "def", "enable_category_lists_editor", "(", "self", ",", "request", ",", "editor_init_kwargs", "=", "None", ",", "additional_parents_aliases", "=", "None", ",", "lists_init_kwargs", "=", "None", ",", "handler_init_kwargs", "=", "None", ")", ":", "from", ".", "toolbox", "import", "CategoryRequestHandler", "additional_parents_aliases", "=", "additional_parents_aliases", "or", "[", "]", "lists_init_kwargs", "=", "lists_init_kwargs", "or", "{", "}", "editor_init_kwargs", "=", "editor_init_kwargs", "or", "{", "}", "handler_init_kwargs", "=", "handler_init_kwargs", "or", "{", "}", "handler", "=", "CategoryRequestHandler", "(", "request", ",", "self", ",", "*", "*", "handler_init_kwargs", ")", "lists", "=", "self", ".", "get_category_lists", "(", "init_kwargs", "=", "lists_init_kwargs", ",", "additional_parents_aliases", "=", "additional_parents_aliases", ")", "handler", ".", "register_lists", "(", "lists", ",", "lists_init_kwargs", "=", "lists_init_kwargs", ",", "editor_init_kwargs", "=", "editor_init_kwargs", ")", "self", ".", "_category_editor", "=", "handler", "# Set link to handler to mutate get_category_lists() behaviour.", "return", "handler", ".", "listen", "(", ")" ]
Enables editor functionality for categories of this object. :param Request request: Django request object :param dict editor_init_kwargs: Keyword args to initialize category lists editor with. See CategoryList.enable_editor() :param list additional_parents_aliases: Aliases of categories for editor to render even if this object has no tie to them. :param dict lists_init_kwargs: Keyword args to initialize CategoryList objects with :param dict handler_init_kwargs: Keyword args to initialize CategoryRequestHandler object with :return:
[ "Enables", "editor", "functionality", "for", "categories", "of", "this", "object", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/models.py#L254-L277
train
idlesign/django-sitecats
sitecats/models.py
ModelWithCategory.add_to_category
def add_to_category(self, category, user): """Add this model instance to a category. :param Category category: Category to add this object to :param User user: User heir who adds :return: """ init_kwargs = { 'category': category, 'creator': user, 'linked_object': self } tie = self.categories.model(**init_kwargs) # That's a model of Tie. tie.save() return tie
python
def add_to_category(self, category, user): """Add this model instance to a category. :param Category category: Category to add this object to :param User user: User heir who adds :return: """ init_kwargs = { 'category': category, 'creator': user, 'linked_object': self } tie = self.categories.model(**init_kwargs) # That's a model of Tie. tie.save() return tie
[ "def", "add_to_category", "(", "self", ",", "category", ",", "user", ")", ":", "init_kwargs", "=", "{", "'category'", ":", "category", ",", "'creator'", ":", "user", ",", "'linked_object'", ":", "self", "}", "tie", "=", "self", ".", "categories", ".", "model", "(", "*", "*", "init_kwargs", ")", "# That's a model of Tie.", "tie", ".", "save", "(", ")", "return", "tie" ]
Add this model instance to a category. :param Category category: Category to add this object to :param User user: User heir who adds :return:
[ "Add", "this", "model", "instance", "to", "a", "category", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/models.py#L279-L293
train
idlesign/django-sitecats
sitecats/models.py
ModelWithCategory.remove_from_category
def remove_from_category(self, category): """Removes this object from a given category. :param Category category: :return: """ ctype = ContentType.objects.get_for_model(self) self.categories.model.objects.filter(category=category, content_type=ctype, object_id=self.id).delete()
python
def remove_from_category(self, category): """Removes this object from a given category. :param Category category: :return: """ ctype = ContentType.objects.get_for_model(self) self.categories.model.objects.filter(category=category, content_type=ctype, object_id=self.id).delete()
[ "def", "remove_from_category", "(", "self", ",", "category", ")", ":", "ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "self", ")", "self", ".", "categories", ".", "model", ".", "objects", ".", "filter", "(", "category", "=", "category", ",", "content_type", "=", "ctype", ",", "object_id", "=", "self", ".", "id", ")", ".", "delete", "(", ")" ]
Removes this object from a given category. :param Category category: :return:
[ "Removes", "this", "object", "from", "a", "given", "category", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/models.py#L295-L302
train
idlesign/django-sitecats
sitecats/models.py
ModelWithCategory.get_ties_for_categories_qs
def get_ties_for_categories_qs(cls, categories, user=None, status=None): """Returns a QuerySet of Ties for the given categories. :param list|Category categories: :param User|None user: :param int|None status: :return: """ if not isinstance(categories, list): categories = [categories] category_ids = [] for category in categories: if isinstance(category, models.Model): category_ids.append(category.id) else: category_ids.append(category) filter_kwargs = { 'content_type': ContentType.objects.get_for_model(cls, for_concrete_model=False), 'category_id__in': category_ids } if user is not None: filter_kwargs['creator'] = user if status is not None: filter_kwargs['status'] = status ties = get_tie_model().objects.filter(**filter_kwargs) return ties
python
def get_ties_for_categories_qs(cls, categories, user=None, status=None): """Returns a QuerySet of Ties for the given categories. :param list|Category categories: :param User|None user: :param int|None status: :return: """ if not isinstance(categories, list): categories = [categories] category_ids = [] for category in categories: if isinstance(category, models.Model): category_ids.append(category.id) else: category_ids.append(category) filter_kwargs = { 'content_type': ContentType.objects.get_for_model(cls, for_concrete_model=False), 'category_id__in': category_ids } if user is not None: filter_kwargs['creator'] = user if status is not None: filter_kwargs['status'] = status ties = get_tie_model().objects.filter(**filter_kwargs) return ties
[ "def", "get_ties_for_categories_qs", "(", "cls", ",", "categories", ",", "user", "=", "None", ",", "status", "=", "None", ")", ":", "if", "not", "isinstance", "(", "categories", ",", "list", ")", ":", "categories", "=", "[", "categories", "]", "category_ids", "=", "[", "]", "for", "category", "in", "categories", ":", "if", "isinstance", "(", "category", ",", "models", ".", "Model", ")", ":", "category_ids", ".", "append", "(", "category", ".", "id", ")", "else", ":", "category_ids", ".", "append", "(", "category", ")", "filter_kwargs", "=", "{", "'content_type'", ":", "ContentType", ".", "objects", ".", "get_for_model", "(", "cls", ",", "for_concrete_model", "=", "False", ")", ",", "'category_id__in'", ":", "category_ids", "}", "if", "user", "is", "not", "None", ":", "filter_kwargs", "[", "'creator'", "]", "=", "user", "if", "status", "is", "not", "None", ":", "filter_kwargs", "[", "'status'", "]", "=", "status", "ties", "=", "get_tie_model", "(", ")", ".", "objects", ".", "filter", "(", "*", "*", "filter_kwargs", ")", "return", "ties" ]
Returns a QuerySet of Ties for the given categories. :param list|Category categories: :param User|None user: :param int|None status: :return:
[ "Returns", "a", "QuerySet", "of", "Ties", "for", "the", "given", "categories", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/models.py#L305-L331
train
idlesign/django-sitecats
sitecats/models.py
ModelWithCategory.get_from_category_qs
def get_from_category_qs(cls, category): """Returns a QuerySet of objects of this type associated with the given category. :param Category category: :rtype: list :return: """ ids = cls.get_ties_for_categories_qs(category).values_list('object_id').distinct() filter_kwargs = {'id__in': [i[0] for i in ids]} return cls.objects.filter(**filter_kwargs)
python
def get_from_category_qs(cls, category): """Returns a QuerySet of objects of this type associated with the given category. :param Category category: :rtype: list :return: """ ids = cls.get_ties_for_categories_qs(category).values_list('object_id').distinct() filter_kwargs = {'id__in': [i[0] for i in ids]} return cls.objects.filter(**filter_kwargs)
[ "def", "get_from_category_qs", "(", "cls", ",", "category", ")", ":", "ids", "=", "cls", ".", "get_ties_for_categories_qs", "(", "category", ")", ".", "values_list", "(", "'object_id'", ")", ".", "distinct", "(", ")", "filter_kwargs", "=", "{", "'id__in'", ":", "[", "i", "[", "0", "]", "for", "i", "in", "ids", "]", "}", "return", "cls", ".", "objects", ".", "filter", "(", "*", "*", "filter_kwargs", ")" ]
Returns a QuerySet of objects of this type associated with the given category. :param Category category: :rtype: list :return:
[ "Returns", "a", "QuerySet", "of", "objects", "of", "this", "type", "associated", "with", "the", "given", "category", "." ]
9b45e91fc0dcb63a0011780437fe28145e3ecce9
https://github.com/idlesign/django-sitecats/blob/9b45e91fc0dcb63a0011780437fe28145e3ecce9/sitecats/models.py#L334-L343
train
nmdp-bioinformatics/SeqAnn
scripts/annotate_fasta.py
main
def main(): """This is run if file is directly executed, but not if imported as module. Having this in a separate function allows importing the file into interactive python, and still able to execute the function for testing""" parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", required=True, help="input file", type=str) parser.add_argument("-l", "--locus", required=True, help="Locus", type=str) parser.add_argument("-k", "--kir", help="Option for running with KIR", action='store_true') parser.add_argument("-s", "--server", help="Option for running with a server", action='store_true') parser.add_argument("-v", "--verbose", help="Option for running in verbose", action='store_true') args = parser.parse_args() fastafile = args.file locus = args.locus verbose = False if args.verbose: verbose = True verbose = False if args.verbose: verbose = True kir = False if args.kir: kir = True serv = False if args.server: serv = True if verbose: logging.basicConfig(format='%(asctime)s - %(name)-35s - %(levelname)-5s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO) server = None if serv: server = BioSeqDatabase.open_database(driver="pymysql", user="root", passwd="", host="localhost", db="bioseqdb") seqann = BioSeqAnn(verbose=True, kir=kir) for seq in SeqIO.parse(fastafile, "fasta"): ann = seqann.annotate(seq, locus=locus) print('{:*^20} {:^20} {:*^20}'.format("", str(seq.description), "")) l = 0 for f in ann.annotation: if isinstance(ann.annotation[f], DBSeq): print(f, ann.method, str(ann.annotation[f]), sep="\t") l += len(ann.annotation[f]) else: print(f, ann.method, str(ann.annotation[f].seq), sep="\t") l += len(ann.annotation[f].seq) print("") if serv: server.close()
python
def main(): """This is run if file is directly executed, but not if imported as module. Having this in a separate function allows importing the file into interactive python, and still able to execute the function for testing""" parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", required=True, help="input file", type=str) parser.add_argument("-l", "--locus", required=True, help="Locus", type=str) parser.add_argument("-k", "--kir", help="Option for running with KIR", action='store_true') parser.add_argument("-s", "--server", help="Option for running with a server", action='store_true') parser.add_argument("-v", "--verbose", help="Option for running in verbose", action='store_true') args = parser.parse_args() fastafile = args.file locus = args.locus verbose = False if args.verbose: verbose = True verbose = False if args.verbose: verbose = True kir = False if args.kir: kir = True serv = False if args.server: serv = True if verbose: logging.basicConfig(format='%(asctime)s - %(name)-35s - %(levelname)-5s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO) server = None if serv: server = BioSeqDatabase.open_database(driver="pymysql", user="root", passwd="", host="localhost", db="bioseqdb") seqann = BioSeqAnn(verbose=True, kir=kir) for seq in SeqIO.parse(fastafile, "fasta"): ann = seqann.annotate(seq, locus=locus) print('{:*^20} {:^20} {:*^20}'.format("", str(seq.description), "")) l = 0 for f in ann.annotation: if isinstance(ann.annotation[f], DBSeq): print(f, ann.method, str(ann.annotation[f]), sep="\t") l += len(ann.annotation[f]) else: print(f, ann.method, str(ann.annotation[f].seq), sep="\t") l += len(ann.annotation[f].seq) print("") if serv: server.close()
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"-f\"", ",", "\"--file\"", ",", "required", "=", "True", ",", "help", "=", "\"input file\"", ",", "type", "=", "str", ")", "parser", ".", "add_argument", "(", "\"-l\"", ",", "\"--locus\"", ",", "required", "=", "True", ",", "help", "=", "\"Locus\"", ",", "type", "=", "str", ")", "parser", ".", "add_argument", "(", "\"-k\"", ",", "\"--kir\"", ",", "help", "=", "\"Option for running with KIR\"", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "\"-s\"", ",", "\"--server\"", ",", "help", "=", "\"Option for running with a server\"", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "\"-v\"", ",", "\"--verbose\"", ",", "help", "=", "\"Option for running in verbose\"", ",", "action", "=", "'store_true'", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "fastafile", "=", "args", ".", "file", "locus", "=", "args", ".", "locus", "verbose", "=", "False", "if", "args", ".", "verbose", ":", "verbose", "=", "True", "verbose", "=", "False", "if", "args", ".", "verbose", ":", "verbose", "=", "True", "kir", "=", "False", "if", "args", ".", "kir", ":", "kir", "=", "True", "serv", "=", "False", "if", "args", ".", "server", ":", "serv", "=", "True", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "format", "=", "'%(asctime)s - %(name)-35s - %(levelname)-5s - %(message)s'", ",", "datefmt", "=", "'%m/%d/%Y %I:%M:%S %p'", ",", "level", "=", "logging", ".", "INFO", ")", "server", "=", "None", "if", "serv", ":", "server", "=", "BioSeqDatabase", ".", "open_database", "(", "driver", "=", "\"pymysql\"", ",", "user", "=", "\"root\"", ",", "passwd", "=", "\"\"", ",", "host", "=", "\"localhost\"", ",", "db", "=", "\"bioseqdb\"", ")", "seqann", "=", "BioSeqAnn", "(", "verbose", "=", "True", ",", "kir", "=", "kir", ")", "for", "seq", "in", "SeqIO", ".", "parse", "(", "fastafile", ",", "\"fasta\"", ")", ":", "ann", "=", "seqann", ".", "annotate", "(", "seq", ",", "locus", "=", "locus", ")", "print", "(", "'{:*^20} {:^20} {:*^20}'", ".", "format", "(", "\"\"", ",", "str", "(", "seq", ".", "description", ")", ",", "\"\"", ")", ")", "l", "=", "0", "for", "f", "in", "ann", ".", "annotation", ":", "if", "isinstance", "(", "ann", ".", "annotation", "[", "f", "]", ",", "DBSeq", ")", ":", "print", "(", "f", ",", "ann", ".", "method", ",", "str", "(", "ann", ".", "annotation", "[", "f", "]", ")", ",", "sep", "=", "\"\\t\"", ")", "l", "+=", "len", "(", "ann", ".", "annotation", "[", "f", "]", ")", "else", ":", "print", "(", "f", ",", "ann", ".", "method", ",", "str", "(", "ann", ".", "annotation", "[", "f", "]", ".", "seq", ")", ",", "sep", "=", "\"\\t\"", ")", "l", "+=", "len", "(", "ann", ".", "annotation", "[", "f", "]", ".", "seq", ")", "print", "(", "\"\"", ")", "if", "serv", ":", "server", ".", "close", "(", ")" ]
This is run if file is directly executed, but not if imported as module. Having this in a separate function allows importing the file into interactive python, and still able to execute the function for testing
[ "This", "is", "run", "if", "file", "is", "directly", "executed", "but", "not", "if", "imported", "as", "module", ".", "Having", "this", "in", "a", "separate", "function", "allows", "importing", "the", "file", "into", "interactive", "python", "and", "still", "able", "to", "execute", "the", "function", "for", "testing" ]
5ce91559b0a4fbe4fb7758e034eb258202632463
https://github.com/nmdp-bioinformatics/SeqAnn/blob/5ce91559b0a4fbe4fb7758e034eb258202632463/scripts/annotate_fasta.py#L17-L91
train
hyperledger-archives/indy-ledger
ledger/compact_merkle_tree.py
CompactMerkleTree._push_subtree
def _push_subtree(self, leaves: List[bytes]): """Extend with a full subtree <= the current minimum subtree. The leaves must form a full subtree, i.e. of size 2^k for some k. If there is a minimum subtree (i.e. __mintree_height > 0), then the input subtree must be smaller or of equal size to the minimum subtree. If the subtree is smaller (or no such minimum exists, in an empty tree), we can simply append its hash to self.hashes, since this maintains the invariant property of being sorted in descending size order. If the subtree is of equal size, we are in a similar situation to an addition carry. We handle it by combining the two subtrees into a larger subtree (of size 2^(k+1)), then recursively trying to add this new subtree back into the tree. Any collection of leaves larger than the minimum subtree must undergo additional partition to conform with the structure of a merkle tree, which is a more complex operation, performed by extend(). """ size = len(leaves) if count_bits_set(size) != 1: raise ValueError("invalid subtree with size != 2^k: %s" % size) # in general we want the highest bit, but here it's also the lowest bit # so just reuse that code instead of writing a new highest_bit_set() subtree_h, mintree_h = lowest_bit_set(size), self.__mintree_height if mintree_h > 0 and subtree_h > mintree_h: raise ValueError("subtree %s > current smallest subtree %s" % ( subtree_h, mintree_h)) root_hash, hashes = self.__hasher._hash_full(leaves, 0, size) assert hashes == (root_hash,) if self.hashStore: for h in hashes: self.hashStore.writeLeaf(h) new_node_hashes = self.__push_subtree_hash(subtree_h, root_hash) nodes = [(self.tree_size, height, h) for h, height in new_node_hashes] if self.hashStore: for node in nodes: self.hashStore.writeNode(node)
python
def _push_subtree(self, leaves: List[bytes]): """Extend with a full subtree <= the current minimum subtree. The leaves must form a full subtree, i.e. of size 2^k for some k. If there is a minimum subtree (i.e. __mintree_height > 0), then the input subtree must be smaller or of equal size to the minimum subtree. If the subtree is smaller (or no such minimum exists, in an empty tree), we can simply append its hash to self.hashes, since this maintains the invariant property of being sorted in descending size order. If the subtree is of equal size, we are in a similar situation to an addition carry. We handle it by combining the two subtrees into a larger subtree (of size 2^(k+1)), then recursively trying to add this new subtree back into the tree. Any collection of leaves larger than the minimum subtree must undergo additional partition to conform with the structure of a merkle tree, which is a more complex operation, performed by extend(). """ size = len(leaves) if count_bits_set(size) != 1: raise ValueError("invalid subtree with size != 2^k: %s" % size) # in general we want the highest bit, but here it's also the lowest bit # so just reuse that code instead of writing a new highest_bit_set() subtree_h, mintree_h = lowest_bit_set(size), self.__mintree_height if mintree_h > 0 and subtree_h > mintree_h: raise ValueError("subtree %s > current smallest subtree %s" % ( subtree_h, mintree_h)) root_hash, hashes = self.__hasher._hash_full(leaves, 0, size) assert hashes == (root_hash,) if self.hashStore: for h in hashes: self.hashStore.writeLeaf(h) new_node_hashes = self.__push_subtree_hash(subtree_h, root_hash) nodes = [(self.tree_size, height, h) for h, height in new_node_hashes] if self.hashStore: for node in nodes: self.hashStore.writeNode(node)
[ "def", "_push_subtree", "(", "self", ",", "leaves", ":", "List", "[", "bytes", "]", ")", ":", "size", "=", "len", "(", "leaves", ")", "if", "count_bits_set", "(", "size", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"invalid subtree with size != 2^k: %s\"", "%", "size", ")", "# in general we want the highest bit, but here it's also the lowest bit", "# so just reuse that code instead of writing a new highest_bit_set()", "subtree_h", ",", "mintree_h", "=", "lowest_bit_set", "(", "size", ")", ",", "self", ".", "__mintree_height", "if", "mintree_h", ">", "0", "and", "subtree_h", ">", "mintree_h", ":", "raise", "ValueError", "(", "\"subtree %s > current smallest subtree %s\"", "%", "(", "subtree_h", ",", "mintree_h", ")", ")", "root_hash", ",", "hashes", "=", "self", ".", "__hasher", ".", "_hash_full", "(", "leaves", ",", "0", ",", "size", ")", "assert", "hashes", "==", "(", "root_hash", ",", ")", "if", "self", ".", "hashStore", ":", "for", "h", "in", "hashes", ":", "self", ".", "hashStore", ".", "writeLeaf", "(", "h", ")", "new_node_hashes", "=", "self", ".", "__push_subtree_hash", "(", "subtree_h", ",", "root_hash", ")", "nodes", "=", "[", "(", "self", ".", "tree_size", ",", "height", ",", "h", ")", "for", "h", ",", "height", "in", "new_node_hashes", "]", "if", "self", ".", "hashStore", ":", "for", "node", "in", "nodes", ":", "self", ".", "hashStore", ".", "writeNode", "(", "node", ")" ]
Extend with a full subtree <= the current minimum subtree. The leaves must form a full subtree, i.e. of size 2^k for some k. If there is a minimum subtree (i.e. __mintree_height > 0), then the input subtree must be smaller or of equal size to the minimum subtree. If the subtree is smaller (or no such minimum exists, in an empty tree), we can simply append its hash to self.hashes, since this maintains the invariant property of being sorted in descending size order. If the subtree is of equal size, we are in a similar situation to an addition carry. We handle it by combining the two subtrees into a larger subtree (of size 2^(k+1)), then recursively trying to add this new subtree back into the tree. Any collection of leaves larger than the minimum subtree must undergo additional partition to conform with the structure of a merkle tree, which is a more complex operation, performed by extend().
[ "Extend", "with", "a", "full", "subtree", "<", "=", "the", "current", "minimum", "subtree", "." ]
7210c3b288e07f940eddad09b1dfc6a56be846df
https://github.com/hyperledger-archives/indy-ledger/blob/7210c3b288e07f940eddad09b1dfc6a56be846df/ledger/compact_merkle_tree.py#L91-L132
train
johnnoone/json-spec
src/jsonspec/reference/__init__.py
resolve
def resolve(obj, pointer, registry=None): """resolve a local object :param obj: the local object. :param pointer: the pointer :type pointer: DocumentPointer, str :param registry: the registry. It mays be omited if inner json references document don't refer to other documents. :type registry: Provider, dict .. warning:: Once pointer is extracted, it won't follow sub mapping /element! For example, the value of:: value = resolve({ 'foo': {'$ref': '#/bar'}, 'bar': [{'$ref': '#/baz'}], 'baz': 'quux', }, '#/foo') is:: assert value == [{'$ref': '#/baz'}] and not:: assert value == ['quux'] """ registry = LocalRegistry(obj, registry or {}) local = DocumentPointer(pointer) if local.document: registry[local.document] = obj local.document = '<local>' return registry.resolve(local)
python
def resolve(obj, pointer, registry=None): """resolve a local object :param obj: the local object. :param pointer: the pointer :type pointer: DocumentPointer, str :param registry: the registry. It mays be omited if inner json references document don't refer to other documents. :type registry: Provider, dict .. warning:: Once pointer is extracted, it won't follow sub mapping /element! For example, the value of:: value = resolve({ 'foo': {'$ref': '#/bar'}, 'bar': [{'$ref': '#/baz'}], 'baz': 'quux', }, '#/foo') is:: assert value == [{'$ref': '#/baz'}] and not:: assert value == ['quux'] """ registry = LocalRegistry(obj, registry or {}) local = DocumentPointer(pointer) if local.document: registry[local.document] = obj local.document = '<local>' return registry.resolve(local)
[ "def", "resolve", "(", "obj", ",", "pointer", ",", "registry", "=", "None", ")", ":", "registry", "=", "LocalRegistry", "(", "obj", ",", "registry", "or", "{", "}", ")", "local", "=", "DocumentPointer", "(", "pointer", ")", "if", "local", ".", "document", ":", "registry", "[", "local", ".", "document", "]", "=", "obj", "local", ".", "document", "=", "'<local>'", "return", "registry", ".", "resolve", "(", "local", ")" ]
resolve a local object :param obj: the local object. :param pointer: the pointer :type pointer: DocumentPointer, str :param registry: the registry. It mays be omited if inner json references document don't refer to other documents. :type registry: Provider, dict .. warning:: Once pointer is extracted, it won't follow sub mapping /element! For example, the value of:: value = resolve({ 'foo': {'$ref': '#/bar'}, 'bar': [{'$ref': '#/baz'}], 'baz': 'quux', }, '#/foo') is:: assert value == [{'$ref': '#/baz'}] and not:: assert value == ['quux']
[ "resolve", "a", "local", "object" ]
f91981724cea0c366bd42a6670eb07bbe31c0e0c
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/reference/__init__.py#L24-L62
train
abarmat/python-oembed
oembed/__init__.py
OEmbedEndpoint.addUrlScheme
def addUrlScheme(self, url): ''' Add a url scheme to this endpoint. It takes a url string and create the OEmbedUrlScheme object internally. Args: url: The url string that represents a url scheme to add. ''' #@TODO: validate invalid url format according to http://oembed.com/ if not isinstance(url, str): raise TypeError('url must be a string value') if not url in self._urlSchemes: self._urlSchemes[url] = OEmbedUrlScheme(url)
python
def addUrlScheme(self, url): ''' Add a url scheme to this endpoint. It takes a url string and create the OEmbedUrlScheme object internally. Args: url: The url string that represents a url scheme to add. ''' #@TODO: validate invalid url format according to http://oembed.com/ if not isinstance(url, str): raise TypeError('url must be a string value') if not url in self._urlSchemes: self._urlSchemes[url] = OEmbedUrlScheme(url)
[ "def", "addUrlScheme", "(", "self", ",", "url", ")", ":", "#@TODO: validate invalid url format according to http://oembed.com/", "if", "not", "isinstance", "(", "url", ",", "str", ")", ":", "raise", "TypeError", "(", "'url must be a string value'", ")", "if", "not", "url", "in", "self", ".", "_urlSchemes", ":", "self", ".", "_urlSchemes", "[", "url", "]", "=", "OEmbedUrlScheme", "(", "url", ")" ]
Add a url scheme to this endpoint. It takes a url string and create the OEmbedUrlScheme object internally. Args: url: The url string that represents a url scheme to add.
[ "Add", "a", "url", "scheme", "to", "this", "endpoint", ".", "It", "takes", "a", "url", "string", "and", "create", "the", "OEmbedUrlScheme", "object", "internally", "." ]
bb3d14213e0ac91aa998af67182826b6f1529fe6
https://github.com/abarmat/python-oembed/blob/bb3d14213e0ac91aa998af67182826b6f1529fe6/oembed/__init__.py#L240-L254
train
abarmat/python-oembed
oembed/__init__.py
OEmbedEndpoint.match
def match(self, url): ''' Try to find if url matches against any of the schemes within this endpoint. Args: url: The url to match against each scheme Returns: True if a matching scheme was found for the url, False otherwise ''' try: urlSchemes = self._urlSchemes.itervalues() # Python 2 except AttributeError: urlSchemes = self._urlSchemes.values() # Python 3 for urlScheme in urlSchemes: if urlScheme.match(url): return True return False
python
def match(self, url): ''' Try to find if url matches against any of the schemes within this endpoint. Args: url: The url to match against each scheme Returns: True if a matching scheme was found for the url, False otherwise ''' try: urlSchemes = self._urlSchemes.itervalues() # Python 2 except AttributeError: urlSchemes = self._urlSchemes.values() # Python 3 for urlScheme in urlSchemes: if urlScheme.match(url): return True return False
[ "def", "match", "(", "self", ",", "url", ")", ":", "try", ":", "urlSchemes", "=", "self", ".", "_urlSchemes", ".", "itervalues", "(", ")", "# Python 2", "except", "AttributeError", ":", "urlSchemes", "=", "self", ".", "_urlSchemes", ".", "values", "(", ")", "# Python 3", "for", "urlScheme", "in", "urlSchemes", ":", "if", "urlScheme", ".", "match", "(", "url", ")", ":", "return", "True", "return", "False" ]
Try to find if url matches against any of the schemes within this endpoint. Args: url: The url to match against each scheme Returns: True if a matching scheme was found for the url, False otherwise
[ "Try", "to", "find", "if", "url", "matches", "against", "any", "of", "the", "schemes", "within", "this", "endpoint", "." ]
bb3d14213e0ac91aa998af67182826b6f1529fe6
https://github.com/abarmat/python-oembed/blob/bb3d14213e0ac91aa998af67182826b6f1529fe6/oembed/__init__.py#L279-L298
train
abarmat/python-oembed
oembed/__init__.py
OEmbedEndpoint.request
def request(self, url, **opt): ''' Format the input url and optional parameters, and provides the final url where to get the given resource. Args: url: The url of an OEmbed resource. **opt: Parameters passed to the url. Returns: The complete url of the endpoint and resource. ''' params = opt params['url'] = url urlApi = self._urlApi if 'format' in params and self._implicitFormat: urlApi = self._urlApi.replace('{format}', params['format']) del params['format'] if '?' in urlApi: return "%s&%s" % (urlApi, urllib.urlencode(params)) else: return "%s?%s" % (urlApi, urllib.urlencode(params))
python
def request(self, url, **opt): ''' Format the input url and optional parameters, and provides the final url where to get the given resource. Args: url: The url of an OEmbed resource. **opt: Parameters passed to the url. Returns: The complete url of the endpoint and resource. ''' params = opt params['url'] = url urlApi = self._urlApi if 'format' in params and self._implicitFormat: urlApi = self._urlApi.replace('{format}', params['format']) del params['format'] if '?' in urlApi: return "%s&%s" % (urlApi, urllib.urlencode(params)) else: return "%s?%s" % (urlApi, urllib.urlencode(params))
[ "def", "request", "(", "self", ",", "url", ",", "*", "*", "opt", ")", ":", "params", "=", "opt", "params", "[", "'url'", "]", "=", "url", "urlApi", "=", "self", ".", "_urlApi", "if", "'format'", "in", "params", "and", "self", ".", "_implicitFormat", ":", "urlApi", "=", "self", ".", "_urlApi", ".", "replace", "(", "'{format}'", ",", "params", "[", "'format'", "]", ")", "del", "params", "[", "'format'", "]", "if", "'?'", "in", "urlApi", ":", "return", "\"%s&%s\"", "%", "(", "urlApi", ",", "urllib", ".", "urlencode", "(", "params", ")", ")", "else", ":", "return", "\"%s?%s\"", "%", "(", "urlApi", ",", "urllib", ".", "urlencode", "(", "params", ")", ")" ]
Format the input url and optional parameters, and provides the final url where to get the given resource. Args: url: The url of an OEmbed resource. **opt: Parameters passed to the url. Returns: The complete url of the endpoint and resource.
[ "Format", "the", "input", "url", "and", "optional", "parameters", "and", "provides", "the", "final", "url", "where", "to", "get", "the", "given", "resource", "." ]
bb3d14213e0ac91aa998af67182826b6f1529fe6
https://github.com/abarmat/python-oembed/blob/bb3d14213e0ac91aa998af67182826b6f1529fe6/oembed/__init__.py#L300-L323
train
abarmat/python-oembed
oembed/__init__.py
OEmbedEndpoint.get
def get(self, url, **opt): ''' Convert the resource url to a complete url and then fetch the data from it. Args: url: The url of an OEmbed resource. **opt: Parameters passed to the url. Returns: OEmbedResponse object according to data fetched ''' return self.fetch(self.request(url, **opt))
python
def get(self, url, **opt): ''' Convert the resource url to a complete url and then fetch the data from it. Args: url: The url of an OEmbed resource. **opt: Parameters passed to the url. Returns: OEmbedResponse object according to data fetched ''' return self.fetch(self.request(url, **opt))
[ "def", "get", "(", "self", ",", "url", ",", "*", "*", "opt", ")", ":", "return", "self", ".", "fetch", "(", "self", ".", "request", "(", "url", ",", "*", "*", "opt", ")", ")" ]
Convert the resource url to a complete url and then fetch the data from it. Args: url: The url of an OEmbed resource. **opt: Parameters passed to the url. Returns: OEmbedResponse object according to data fetched
[ "Convert", "the", "resource", "url", "to", "a", "complete", "url", "and", "then", "fetch", "the", "data", "from", "it", "." ]
bb3d14213e0ac91aa998af67182826b6f1529fe6
https://github.com/abarmat/python-oembed/blob/bb3d14213e0ac91aa998af67182826b6f1529fe6/oembed/__init__.py#L325-L337
train
abarmat/python-oembed
oembed/__init__.py
OEmbedEndpoint.fetch
def fetch(self, url): ''' Fetch url and create a response object according to the mime-type. Args: url: The url to fetch data from Returns: OEmbedResponse object according to data fetched ''' opener = self._urllib.build_opener() opener.addheaders = self._requestHeaders.items() response = opener.open(url) headers = response.info() raw = response.read() raw = raw.decode('utf8') if not 'Content-Type' in headers: raise OEmbedError('Missing mime-type in response') if headers['Content-Type'].find('application/xml') != -1 or \ headers['Content-Type'].find('text/xml') != -1: response = OEmbedResponse.newFromXML(raw) elif headers['Content-Type'].find('application/json') != -1 or \ headers['Content-Type'].find('text/javascript') != -1 or \ headers['Content-Type'].find('text/json') != -1: response = OEmbedResponse.newFromJSON(raw) else: raise OEmbedError('Invalid mime-type in response - %s' % headers['Content-Type']) return response
python
def fetch(self, url): ''' Fetch url and create a response object according to the mime-type. Args: url: The url to fetch data from Returns: OEmbedResponse object according to data fetched ''' opener = self._urllib.build_opener() opener.addheaders = self._requestHeaders.items() response = opener.open(url) headers = response.info() raw = response.read() raw = raw.decode('utf8') if not 'Content-Type' in headers: raise OEmbedError('Missing mime-type in response') if headers['Content-Type'].find('application/xml') != -1 or \ headers['Content-Type'].find('text/xml') != -1: response = OEmbedResponse.newFromXML(raw) elif headers['Content-Type'].find('application/json') != -1 or \ headers['Content-Type'].find('text/javascript') != -1 or \ headers['Content-Type'].find('text/json') != -1: response = OEmbedResponse.newFromJSON(raw) else: raise OEmbedError('Invalid mime-type in response - %s' % headers['Content-Type']) return response
[ "def", "fetch", "(", "self", ",", "url", ")", ":", "opener", "=", "self", ".", "_urllib", ".", "build_opener", "(", ")", "opener", ".", "addheaders", "=", "self", ".", "_requestHeaders", ".", "items", "(", ")", "response", "=", "opener", ".", "open", "(", "url", ")", "headers", "=", "response", ".", "info", "(", ")", "raw", "=", "response", ".", "read", "(", ")", "raw", "=", "raw", ".", "decode", "(", "'utf8'", ")", "if", "not", "'Content-Type'", "in", "headers", ":", "raise", "OEmbedError", "(", "'Missing mime-type in response'", ")", "if", "headers", "[", "'Content-Type'", "]", ".", "find", "(", "'application/xml'", ")", "!=", "-", "1", "or", "headers", "[", "'Content-Type'", "]", ".", "find", "(", "'text/xml'", ")", "!=", "-", "1", ":", "response", "=", "OEmbedResponse", ".", "newFromXML", "(", "raw", ")", "elif", "headers", "[", "'Content-Type'", "]", ".", "find", "(", "'application/json'", ")", "!=", "-", "1", "or", "headers", "[", "'Content-Type'", "]", ".", "find", "(", "'text/javascript'", ")", "!=", "-", "1", "or", "headers", "[", "'Content-Type'", "]", ".", "find", "(", "'text/json'", ")", "!=", "-", "1", ":", "response", "=", "OEmbedResponse", ".", "newFromJSON", "(", "raw", ")", "else", ":", "raise", "OEmbedError", "(", "'Invalid mime-type in response - %s'", "%", "headers", "[", "'Content-Type'", "]", ")", "return", "response" ]
Fetch url and create a response object according to the mime-type. Args: url: The url to fetch data from Returns: OEmbedResponse object according to data fetched
[ "Fetch", "url", "and", "create", "a", "response", "object", "according", "to", "the", "mime", "-", "type", "." ]
bb3d14213e0ac91aa998af67182826b6f1529fe6
https://github.com/abarmat/python-oembed/blob/bb3d14213e0ac91aa998af67182826b6f1529fe6/oembed/__init__.py#L339-L369
train
abarmat/python-oembed
oembed/__init__.py
OEmbedConsumer.embed
def embed(self, url, format='json', **opt): ''' Get an OEmbedResponse from one of the providers configured in this consumer according to the resource url. Args: url: The url of the resource to get. format: Desired response format. **opt: Optional parameters to pass in the url to the provider. Returns: OEmbedResponse object. ''' if format not in ['json', 'xml']: raise OEmbedInvalidRequest('Format must be json or xml') opt['format'] = format return self._request(url, **opt)
python
def embed(self, url, format='json', **opt): ''' Get an OEmbedResponse from one of the providers configured in this consumer according to the resource url. Args: url: The url of the resource to get. format: Desired response format. **opt: Optional parameters to pass in the url to the provider. Returns: OEmbedResponse object. ''' if format not in ['json', 'xml']: raise OEmbedInvalidRequest('Format must be json or xml') opt['format'] = format return self._request(url, **opt)
[ "def", "embed", "(", "self", ",", "url", ",", "format", "=", "'json'", ",", "*", "*", "opt", ")", ":", "if", "format", "not", "in", "[", "'json'", ",", "'xml'", "]", ":", "raise", "OEmbedInvalidRequest", "(", "'Format must be json or xml'", ")", "opt", "[", "'format'", "]", "=", "format", "return", "self", ".", "_request", "(", "url", ",", "*", "*", "opt", ")" ]
Get an OEmbedResponse from one of the providers configured in this consumer according to the resource url. Args: url: The url of the resource to get. format: Desired response format. **opt: Optional parameters to pass in the url to the provider. Returns: OEmbedResponse object.
[ "Get", "an", "OEmbedResponse", "from", "one", "of", "the", "providers", "configured", "in", "this", "consumer", "according", "to", "the", "resource", "url", "." ]
bb3d14213e0ac91aa998af67182826b6f1529fe6
https://github.com/abarmat/python-oembed/blob/bb3d14213e0ac91aa998af67182826b6f1529fe6/oembed/__init__.py#L488-L504
train
sastrarobotics/pyHerkulex
herkulex.py
connect
def connect(portname, baudrate): """ Connect to the Herkulex bus Connect to serial port to which Herkulex Servos are attatched Args: portname (str): The serial port name baudrate (int): The serial port baudrate Raises: SerialException: Error occured while opening serial port """ global SERPORT try: SERPORT = serial.Serial(portname, baudrate, timeout = 0.1) except: raise HerkulexError("could not open the serial port")
python
def connect(portname, baudrate): """ Connect to the Herkulex bus Connect to serial port to which Herkulex Servos are attatched Args: portname (str): The serial port name baudrate (int): The serial port baudrate Raises: SerialException: Error occured while opening serial port """ global SERPORT try: SERPORT = serial.Serial(portname, baudrate, timeout = 0.1) except: raise HerkulexError("could not open the serial port")
[ "def", "connect", "(", "portname", ",", "baudrate", ")", ":", "global", "SERPORT", "try", ":", "SERPORT", "=", "serial", ".", "Serial", "(", "portname", ",", "baudrate", ",", "timeout", "=", "0.1", ")", "except", ":", "raise", "HerkulexError", "(", "\"could not open the serial port\"", ")" ]
Connect to the Herkulex bus Connect to serial port to which Herkulex Servos are attatched Args: portname (str): The serial port name baudrate (int): The serial port baudrate Raises: SerialException: Error occured while opening serial port
[ "Connect", "to", "the", "Herkulex", "bus" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L152-L168
train
sastrarobotics/pyHerkulex
herkulex.py
checksum1
def checksum1(data, stringlength): """ Calculate Checksum 1 Calculate the ckecksum 1 required for the herkulex data packet Args: data (list): the data of which checksum is to be calculated stringlength (int): the length of the data Returns: int: The calculated checksum 1 """ value_buffer = 0 for count in range(0, stringlength): value_buffer = value_buffer ^ data[count] return value_buffer&0xFE
python
def checksum1(data, stringlength): """ Calculate Checksum 1 Calculate the ckecksum 1 required for the herkulex data packet Args: data (list): the data of which checksum is to be calculated stringlength (int): the length of the data Returns: int: The calculated checksum 1 """ value_buffer = 0 for count in range(0, stringlength): value_buffer = value_buffer ^ data[count] return value_buffer&0xFE
[ "def", "checksum1", "(", "data", ",", "stringlength", ")", ":", "value_buffer", "=", "0", "for", "count", "in", "range", "(", "0", ",", "stringlength", ")", ":", "value_buffer", "=", "value_buffer", "^", "data", "[", "count", "]", "return", "value_buffer", "&", "0xFE" ]
Calculate Checksum 1 Calculate the ckecksum 1 required for the herkulex data packet Args: data (list): the data of which checksum is to be calculated stringlength (int): the length of the data Returns: int: The calculated checksum 1
[ "Calculate", "Checksum", "1" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L184-L199
train
sastrarobotics/pyHerkulex
herkulex.py
send_data
def send_data(data): """ Send data to herkulex Paketize & write the packet to serial port Args: data (list): the data to be sent Raises: SerialException: Error occured while opening serial port """ datalength = len(data) csm1 = checksum1(data, datalength) csm2 = checksum2(csm1) data.insert(0, 0xFF) data.insert(1, 0xFF) data.insert(5, csm1) data.insert(6, csm2) stringtosend = "" for i in range(len(data)): byteformat = '%02X' % data[i] stringtosend = stringtosend + "\\x" + byteformat try: SERPORT.write(stringtosend.decode('string-escape')) #print stringtosend except: raise HerkulexError("could not communicate with motors")
python
def send_data(data): """ Send data to herkulex Paketize & write the packet to serial port Args: data (list): the data to be sent Raises: SerialException: Error occured while opening serial port """ datalength = len(data) csm1 = checksum1(data, datalength) csm2 = checksum2(csm1) data.insert(0, 0xFF) data.insert(1, 0xFF) data.insert(5, csm1) data.insert(6, csm2) stringtosend = "" for i in range(len(data)): byteformat = '%02X' % data[i] stringtosend = stringtosend + "\\x" + byteformat try: SERPORT.write(stringtosend.decode('string-escape')) #print stringtosend except: raise HerkulexError("could not communicate with motors")
[ "def", "send_data", "(", "data", ")", ":", "datalength", "=", "len", "(", "data", ")", "csm1", "=", "checksum1", "(", "data", ",", "datalength", ")", "csm2", "=", "checksum2", "(", "csm1", ")", "data", ".", "insert", "(", "0", ",", "0xFF", ")", "data", ".", "insert", "(", "1", ",", "0xFF", ")", "data", ".", "insert", "(", "5", ",", "csm1", ")", "data", ".", "insert", "(", "6", ",", "csm2", ")", "stringtosend", "=", "\"\"", "for", "i", "in", "range", "(", "len", "(", "data", ")", ")", ":", "byteformat", "=", "'%02X'", "%", "data", "[", "i", "]", "stringtosend", "=", "stringtosend", "+", "\"\\\\x\"", "+", "byteformat", "try", ":", "SERPORT", ".", "write", "(", "stringtosend", ".", "decode", "(", "'string-escape'", ")", ")", "#print stringtosend", "except", ":", "raise", "HerkulexError", "(", "\"could not communicate with motors\"", ")" ]
Send data to herkulex Paketize & write the packet to serial port Args: data (list): the data to be sent Raises: SerialException: Error occured while opening serial port
[ "Send", "data", "to", "herkulex" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L216-L245
train
sastrarobotics/pyHerkulex
herkulex.py
clear_errors
def clear_errors(): """ Clears the errors register of all Herkulex servos Args: none """ data = [] data.append(0x0B) data.append(BROADCAST_ID) data.append(RAM_WRITE_REQ) data.append(STATUS_ERROR_RAM) data.append(BYTE2) data.append(0x00) data.append(0x00) send_data(data)
python
def clear_errors(): """ Clears the errors register of all Herkulex servos Args: none """ data = [] data.append(0x0B) data.append(BROADCAST_ID) data.append(RAM_WRITE_REQ) data.append(STATUS_ERROR_RAM) data.append(BYTE2) data.append(0x00) data.append(0x00) send_data(data)
[ "def", "clear_errors", "(", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x0B", ")", "data", ".", "append", "(", "BROADCAST_ID", ")", "data", ".", "append", "(", "RAM_WRITE_REQ", ")", "data", ".", "append", "(", "STATUS_ERROR_RAM", ")", "data", ".", "append", "(", "BYTE2", ")", "data", ".", "append", "(", "0x00", ")", "data", ".", "append", "(", "0x00", ")", "send_data", "(", "data", ")" ]
Clears the errors register of all Herkulex servos Args: none
[ "Clears", "the", "errors", "register", "of", "all", "Herkulex", "servos" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L248-L263
train
sastrarobotics/pyHerkulex
herkulex.py
scale
def scale(input_value, input_min, input_max, out_min, out_max): """ scale a value from one range to another """ # Figure out how 'wide' each range is input_span = input_max - input_min output_span = out_max - out_min # Convert the left range into a 0-1 range (float) valuescaled = float(input_value - input_min) / float(input_span) # Convert the 0-1 range into a value in the right range. return out_min + (valuescaled * output_span)
python
def scale(input_value, input_min, input_max, out_min, out_max): """ scale a value from one range to another """ # Figure out how 'wide' each range is input_span = input_max - input_min output_span = out_max - out_min # Convert the left range into a 0-1 range (float) valuescaled = float(input_value - input_min) / float(input_span) # Convert the 0-1 range into a value in the right range. return out_min + (valuescaled * output_span)
[ "def", "scale", "(", "input_value", ",", "input_min", ",", "input_max", ",", "out_min", ",", "out_max", ")", ":", "# Figure out how 'wide' each range is", "input_span", "=", "input_max", "-", "input_min", "output_span", "=", "out_max", "-", "out_min", "# Convert the left range into a 0-1 range (float)", "valuescaled", "=", "float", "(", "input_value", "-", "input_min", ")", "/", "float", "(", "input_span", ")", "# Convert the 0-1 range into a value in the right range.", "return", "out_min", "+", "(", "valuescaled", "*", "output_span", ")" ]
scale a value from one range to another
[ "scale", "a", "value", "from", "one", "range", "to", "another" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L265-L274
train
sastrarobotics/pyHerkulex
herkulex.py
scan_servos
def scan_servos(): """Scan for the herkulex servos connected This function will scan for all the herkulex servos connected to the bus. Args: none Returns: list: a list of tuples of the form [(id, model)] """ servos = [] for servo_id in range(0x00, 0xFE): model = get_model(servo_id) if model: servos += [(servo_id, model)] return servos
python
def scan_servos(): """Scan for the herkulex servos connected This function will scan for all the herkulex servos connected to the bus. Args: none Returns: list: a list of tuples of the form [(id, model)] """ servos = [] for servo_id in range(0x00, 0xFE): model = get_model(servo_id) if model: servos += [(servo_id, model)] return servos
[ "def", "scan_servos", "(", ")", ":", "servos", "=", "[", "]", "for", "servo_id", "in", "range", "(", "0x00", ",", "0xFE", ")", ":", "model", "=", "get_model", "(", "servo_id", ")", "if", "model", ":", "servos", "+=", "[", "(", "servo_id", ",", "model", ")", "]", "return", "servos" ]
Scan for the herkulex servos connected This function will scan for all the herkulex servos connected to the bus. Args: none Returns: list: a list of tuples of the form [(id, model)]
[ "Scan", "for", "the", "herkulex", "servos", "connected" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L276-L293
train
sastrarobotics/pyHerkulex
herkulex.py
get_model
def get_model(servoid): """ Get the servo model This function gets the model of the herkules servo, provided its id Args: servoid(int): the id of the servo Returns: int: an integer corresponding to the model number 0x06 for DRS-602 0x04 for DRS-402 0x02 for DRS-202 """ data = [] data.append(0x09) data.append(servoid) data.append(EEP_READ_REQ) data.append(MODEL_NO1_EEP) data.append(BYTE1) send_data(data) rxdata = [] try: rxdata = SERPORT.read(12) return ord(rxdata[9])&0xFF except: raise HerkulexError("could not communicate with motors")
python
def get_model(servoid): """ Get the servo model This function gets the model of the herkules servo, provided its id Args: servoid(int): the id of the servo Returns: int: an integer corresponding to the model number 0x06 for DRS-602 0x04 for DRS-402 0x02 for DRS-202 """ data = [] data.append(0x09) data.append(servoid) data.append(EEP_READ_REQ) data.append(MODEL_NO1_EEP) data.append(BYTE1) send_data(data) rxdata = [] try: rxdata = SERPORT.read(12) return ord(rxdata[9])&0xFF except: raise HerkulexError("could not communicate with motors")
[ "def", "get_model", "(", "servoid", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x09", ")", "data", ".", "append", "(", "servoid", ")", "data", ".", "append", "(", "EEP_READ_REQ", ")", "data", ".", "append", "(", "MODEL_NO1_EEP", ")", "data", ".", "append", "(", "BYTE1", ")", "send_data", "(", "data", ")", "rxdata", "=", "[", "]", "try", ":", "rxdata", "=", "SERPORT", ".", "read", "(", "12", ")", "return", "ord", "(", "rxdata", "[", "9", "]", ")", "&", "0xFF", "except", ":", "raise", "HerkulexError", "(", "\"could not communicate with motors\"", ")" ]
Get the servo model This function gets the model of the herkules servo, provided its id Args: servoid(int): the id of the servo Returns: int: an integer corresponding to the model number 0x06 for DRS-602 0x04 for DRS-402 0x02 for DRS-202
[ "Get", "the", "servo", "model" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L295-L321
train
sastrarobotics/pyHerkulex
herkulex.py
servo.get_servo_status
def get_servo_status(self): """ Get the error status of servo This function gets the error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(STATUS_ERROR_RAM) data.append(BYTE1) send_data(data) rxdata = [] try: rxdata = SERPORT.read(12) return ord(rxdata[9])&0xFF except: raise HerkulexError("could not communicate with motors")
python
def get_servo_status(self): """ Get the error status of servo This function gets the error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(STATUS_ERROR_RAM) data.append(BYTE1) send_data(data) rxdata = [] try: rxdata = SERPORT.read(12) return ord(rxdata[9])&0xFF except: raise HerkulexError("could not communicate with motors")
[ "def", "get_servo_status", "(", "self", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x09", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_READ_REQ", ")", "data", ".", "append", "(", "STATUS_ERROR_RAM", ")", "data", ".", "append", "(", "BYTE1", ")", "send_data", "(", "data", ")", "rxdata", "=", "[", "]", "try", ":", "rxdata", "=", "SERPORT", ".", "read", "(", "12", ")", "return", "ord", "(", "rxdata", "[", "9", "]", ")", "&", "0xFF", "except", ":", "raise", "HerkulexError", "(", "\"could not communicate with motors\"", ")" ]
Get the error status of servo This function gets the error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet
[ "Get", "the", "error", "status", "of", "servo" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L379-L405
train
sastrarobotics/pyHerkulex
herkulex.py
servo.get_servo_status_detail
def get_servo_status_detail(self): """ Get the detailed error status of servo This function gets the detailed error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(STATUS_DETAIL_RAM) data.append(BYTE1) send_data(data) rxdata = [] try: rxdata = SERPORT.read(12) return ord(rxdata[9])&0xFF except HerkulexError: raise HerkulexError("could not communicate with motors")
python
def get_servo_status_detail(self): """ Get the detailed error status of servo This function gets the detailed error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(STATUS_DETAIL_RAM) data.append(BYTE1) send_data(data) rxdata = [] try: rxdata = SERPORT.read(12) return ord(rxdata[9])&0xFF except HerkulexError: raise HerkulexError("could not communicate with motors")
[ "def", "get_servo_status_detail", "(", "self", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x09", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_READ_REQ", ")", "data", ".", "append", "(", "STATUS_DETAIL_RAM", ")", "data", ".", "append", "(", "BYTE1", ")", "send_data", "(", "data", ")", "rxdata", "=", "[", "]", "try", ":", "rxdata", "=", "SERPORT", ".", "read", "(", "12", ")", "return", "ord", "(", "rxdata", "[", "9", "]", ")", "&", "0xFF", "except", "HerkulexError", ":", "raise", "HerkulexError", "(", "\"could not communicate with motors\"", ")" ]
Get the detailed error status of servo This function gets the detailed error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet
[ "Get", "the", "detailed", "error", "status", "of", "servo" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L407-L433
train
sastrarobotics/pyHerkulex
herkulex.py
servo.set_led
def set_led(self, colorcode): """ Set the LED Color of Herkulex Args: colorcode (int): The code for colors (0x00-OFF 0x02-BLUE 0x03-CYAN 0x04-RED 0x05-ORANGE 0x06-VIOLET 0x07-WHITE """ data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(LED_CONTROL_RAM) data.append(0x01) data.append(colorcode) send_data(data)
python
def set_led(self, colorcode): """ Set the LED Color of Herkulex Args: colorcode (int): The code for colors (0x00-OFF 0x02-BLUE 0x03-CYAN 0x04-RED 0x05-ORANGE 0x06-VIOLET 0x07-WHITE """ data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(LED_CONTROL_RAM) data.append(0x01) data.append(colorcode) send_data(data)
[ "def", "set_led", "(", "self", ",", "colorcode", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x0A", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_WRITE_REQ", ")", "data", ".", "append", "(", "LED_CONTROL_RAM", ")", "data", ".", "append", "(", "0x01", ")", "data", ".", "append", "(", "colorcode", ")", "send_data", "(", "data", ")" ]
Set the LED Color of Herkulex Args: colorcode (int): The code for colors (0x00-OFF 0x02-BLUE 0x03-CYAN 0x04-RED 0x05-ORANGE 0x06-VIOLET 0x07-WHITE
[ "Set", "the", "LED", "Color", "of", "Herkulex" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L435-L455
train
sastrarobotics/pyHerkulex
herkulex.py
servo.brake_on
def brake_on(self): """ Set the Brakes of Herkulex In braked mode, position control and velocity control will not work, enable torque before that Args: none """ data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(TORQUE_CONTROL_RAM) data.append(0x01) data.append(0x40) send_data(data)
python
def brake_on(self): """ Set the Brakes of Herkulex In braked mode, position control and velocity control will not work, enable torque before that Args: none """ data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(TORQUE_CONTROL_RAM) data.append(0x01) data.append(0x40) send_data(data)
[ "def", "brake_on", "(", "self", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x0A", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_WRITE_REQ", ")", "data", ".", "append", "(", "TORQUE_CONTROL_RAM", ")", "data", ".", "append", "(", "0x01", ")", "data", ".", "append", "(", "0x40", ")", "send_data", "(", "data", ")" ]
Set the Brakes of Herkulex In braked mode, position control and velocity control will not work, enable torque before that Args: none
[ "Set", "the", "Brakes", "of", "Herkulex" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L457-L473
train
sastrarobotics/pyHerkulex
herkulex.py
servo.torque_off
def torque_off(self): """ Set the torques of Herkulex to zero In this mode, position control and velocity control will not work, enable torque before that. Also the servo shaft is freely movable Args: none """ data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(TORQUE_CONTROL_RAM) data.append(0x01) data.append(0x00) send_data(data)
python
def torque_off(self): """ Set the torques of Herkulex to zero In this mode, position control and velocity control will not work, enable torque before that. Also the servo shaft is freely movable Args: none """ data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(TORQUE_CONTROL_RAM) data.append(0x01) data.append(0x00) send_data(data)
[ "def", "torque_off", "(", "self", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x0A", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_WRITE_REQ", ")", "data", ".", "append", "(", "TORQUE_CONTROL_RAM", ")", "data", ".", "append", "(", "0x01", ")", "data", ".", "append", "(", "0x00", ")", "send_data", "(", "data", ")" ]
Set the torques of Herkulex to zero In this mode, position control and velocity control will not work, enable torque before that. Also the servo shaft is freely movable Args: none
[ "Set", "the", "torques", "of", "Herkulex", "to", "zero" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L475-L492
train
sastrarobotics/pyHerkulex
herkulex.py
servo.torque_on
def torque_on(self): """ Enable the torques of Herkulex In this mode, position control and velocity control will work. Args: none """ data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(TORQUE_CONTROL_RAM) data.append(0x01) data.append(0x60) send_data(data)
python
def torque_on(self): """ Enable the torques of Herkulex In this mode, position control and velocity control will work. Args: none """ data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(TORQUE_CONTROL_RAM) data.append(0x01) data.append(0x60) send_data(data)
[ "def", "torque_on", "(", "self", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x0A", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_WRITE_REQ", ")", "data", ".", "append", "(", "TORQUE_CONTROL_RAM", ")", "data", ".", "append", "(", "0x01", ")", "data", ".", "append", "(", "0x60", ")", "send_data", "(", "data", ")" ]
Enable the torques of Herkulex In this mode, position control and velocity control will work. Args: none
[ "Enable", "the", "torques", "of", "Herkulex" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L494-L510
train
sastrarobotics/pyHerkulex
herkulex.py
servo.get_torque_state
def get_torque_state(self): """ get the torque state of motor Returns: bool: True if torque is enabled, else False """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(TORQUE_CONTROL_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) return bool(ord(rxdata[9])) except HerkulexError: raise HerkulexError("could not communicate with motors")
python
def get_torque_state(self): """ get the torque state of motor Returns: bool: True if torque is enabled, else False """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(TORQUE_CONTROL_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) return bool(ord(rxdata[9])) except HerkulexError: raise HerkulexError("could not communicate with motors")
[ "def", "get_torque_state", "(", "self", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x09", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_READ_REQ", ")", "data", ".", "append", "(", "TORQUE_CONTROL_RAM", ")", "data", ".", "append", "(", "BYTE2", ")", "send_data", "(", "data", ")", "rxdata", "=", "[", "]", "try", ":", "rxdata", "=", "SERPORT", ".", "read", "(", "13", ")", "return", "bool", "(", "ord", "(", "rxdata", "[", "9", "]", ")", ")", "except", "HerkulexError", ":", "raise", "HerkulexError", "(", "\"could not communicate with motors\"", ")" ]
get the torque state of motor Returns: bool: True if torque is enabled, else False
[ "get", "the", "torque", "state", "of", "motor" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L512-L530
train
sastrarobotics/pyHerkulex
herkulex.py
servo.set_servo_position
def set_servo_position(self, goalposition, goaltime, led): """ Set the position of Herkulex Enable torque using torque_on function before calling this Args: goalposition (int): The desired position, min-0 & max-1023 goaltime (int): the time taken to move from present position to goalposition led (int): the LED color 0x00 LED off 0x04 GREEN 0x08 BLUE 0x10 RED """ goalposition_msb = int(goalposition) >> 8 goalposition_lsb = int(goalposition) & 0xff data = [] data.append(0x0C) data.append(self.servoid) data.append(I_JOG_REQ) data.append(goalposition_lsb) data.append(goalposition_msb) data.append(led) data.append(self.servoid) data.append(goaltime) send_data(data)
python
def set_servo_position(self, goalposition, goaltime, led): """ Set the position of Herkulex Enable torque using torque_on function before calling this Args: goalposition (int): The desired position, min-0 & max-1023 goaltime (int): the time taken to move from present position to goalposition led (int): the LED color 0x00 LED off 0x04 GREEN 0x08 BLUE 0x10 RED """ goalposition_msb = int(goalposition) >> 8 goalposition_lsb = int(goalposition) & 0xff data = [] data.append(0x0C) data.append(self.servoid) data.append(I_JOG_REQ) data.append(goalposition_lsb) data.append(goalposition_msb) data.append(led) data.append(self.servoid) data.append(goaltime) send_data(data)
[ "def", "set_servo_position", "(", "self", ",", "goalposition", ",", "goaltime", ",", "led", ")", ":", "goalposition_msb", "=", "int", "(", "goalposition", ")", ">>", "8", "goalposition_lsb", "=", "int", "(", "goalposition", ")", "&", "0xff", "data", "=", "[", "]", "data", ".", "append", "(", "0x0C", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "I_JOG_REQ", ")", "data", ".", "append", "(", "goalposition_lsb", ")", "data", ".", "append", "(", "goalposition_msb", ")", "data", ".", "append", "(", "led", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "goaltime", ")", "send_data", "(", "data", ")" ]
Set the position of Herkulex Enable torque using torque_on function before calling this Args: goalposition (int): The desired position, min-0 & max-1023 goaltime (int): the time taken to move from present position to goalposition led (int): the LED color 0x00 LED off 0x04 GREEN 0x08 BLUE 0x10 RED
[ "Set", "the", "position", "of", "Herkulex" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L532-L560
train
sastrarobotics/pyHerkulex
herkulex.py
servo.get_servo_position
def get_servo_position(self): """ Gets the current position of Herkulex Args: none Returns: int: position of the servo- 0 to 1023 Raises: SerialException: Error occured while opening serial port """ #global SERPORT data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(CALIBRATED_POSITION_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) if (self.servomodel==0x06) or (self.servomodel == 0x04): return ((ord(rxdata[10])&0xff)<<8) | (ord(rxdata[9])&0xFF) else: #print ord(rxdata[9]),ord(rxdata[10]) return ((ord(rxdata[10])&0x03)<<8) | (ord(rxdata[9])&0xFF) except HerkulexError: print "Could not read from the servos. Check connection"
python
def get_servo_position(self): """ Gets the current position of Herkulex Args: none Returns: int: position of the servo- 0 to 1023 Raises: SerialException: Error occured while opening serial port """ #global SERPORT data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(CALIBRATED_POSITION_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) if (self.servomodel==0x06) or (self.servomodel == 0x04): return ((ord(rxdata[10])&0xff)<<8) | (ord(rxdata[9])&0xFF) else: #print ord(rxdata[9]),ord(rxdata[10]) return ((ord(rxdata[10])&0x03)<<8) | (ord(rxdata[9])&0xFF) except HerkulexError: print "Could not read from the servos. Check connection"
[ "def", "get_servo_position", "(", "self", ")", ":", "#global SERPORT", "data", "=", "[", "]", "data", ".", "append", "(", "0x09", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_READ_REQ", ")", "data", ".", "append", "(", "CALIBRATED_POSITION_RAM", ")", "data", ".", "append", "(", "BYTE2", ")", "send_data", "(", "data", ")", "rxdata", "=", "[", "]", "try", ":", "rxdata", "=", "SERPORT", ".", "read", "(", "13", ")", "if", "(", "self", ".", "servomodel", "==", "0x06", ")", "or", "(", "self", ".", "servomodel", "==", "0x04", ")", ":", "return", "(", "(", "ord", "(", "rxdata", "[", "10", "]", ")", "&", "0xff", ")", "<<", "8", ")", "|", "(", "ord", "(", "rxdata", "[", "9", "]", ")", "&", "0xFF", ")", "else", ":", "#print ord(rxdata[9]),ord(rxdata[10])", "return", "(", "(", "ord", "(", "rxdata", "[", "10", "]", ")", "&", "0x03", ")", "<<", "8", ")", "|", "(", "ord", "(", "rxdata", "[", "9", "]", ")", "&", "0xFF", ")", "except", "HerkulexError", ":", "print", "\"Could not read from the servos. Check connection\"" ]
Gets the current position of Herkulex Args: none Returns: int: position of the servo- 0 to 1023 Raises: SerialException: Error occured while opening serial port
[ "Gets", "the", "current", "position", "of", "Herkulex" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L562-L594
train
sastrarobotics/pyHerkulex
herkulex.py
servo.get_servo_temperature
def get_servo_temperature(self): """ Gets the current temperature of Herkulex Args: none Returns: int: the current temperature register of Herkulex Raises: SerialException: Error occured while opening serial port """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(TEMPERATURE_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) return ord(rxdata[9]) except HerkulexError: raise HerkulexError("Could not communicate with motors")
python
def get_servo_temperature(self): """ Gets the current temperature of Herkulex Args: none Returns: int: the current temperature register of Herkulex Raises: SerialException: Error occured while opening serial port """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(TEMPERATURE_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) return ord(rxdata[9]) except HerkulexError: raise HerkulexError("Could not communicate with motors")
[ "def", "get_servo_temperature", "(", "self", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x09", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_READ_REQ", ")", "data", ".", "append", "(", "TEMPERATURE_RAM", ")", "data", ".", "append", "(", "BYTE2", ")", "send_data", "(", "data", ")", "rxdata", "=", "[", "]", "try", ":", "rxdata", "=", "SERPORT", ".", "read", "(", "13", ")", "return", "ord", "(", "rxdata", "[", "9", "]", ")", "except", "HerkulexError", ":", "raise", "HerkulexError", "(", "\"Could not communicate with motors\"", ")" ]
Gets the current temperature of Herkulex Args: none Returns: int: the current temperature register of Herkulex Raises: SerialException: Error occured while opening serial port
[ "Gets", "the", "current", "temperature", "of", "Herkulex" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L596-L621
train
sastrarobotics/pyHerkulex
herkulex.py
servo.get_servo_torque
def get_servo_torque(self): """ Gets the current torque of Herkulex Gives the current load on the servo shaft. It is actually the PWM value to the motors Args: none Returns: int: the torque on servo shaft. range from -1023 to 1023 Raises: SerialException: Error occured while opening serial port """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(PWM_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) if ord(rxdata[10])<=127: return ((ord(rxdata[10])&0x03)<<8) | (ord(rxdata[9])&0xFF) else: return (ord(rxdata[10])-0xFF)*0xFF + (ord(rxdata[9])&0xFF)-0xFF except HerkulexError: raise HerkulexError("could not communicate with motors")
python
def get_servo_torque(self): """ Gets the current torque of Herkulex Gives the current load on the servo shaft. It is actually the PWM value to the motors Args: none Returns: int: the torque on servo shaft. range from -1023 to 1023 Raises: SerialException: Error occured while opening serial port """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(PWM_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) if ord(rxdata[10])<=127: return ((ord(rxdata[10])&0x03)<<8) | (ord(rxdata[9])&0xFF) else: return (ord(rxdata[10])-0xFF)*0xFF + (ord(rxdata[9])&0xFF)-0xFF except HerkulexError: raise HerkulexError("could not communicate with motors")
[ "def", "get_servo_torque", "(", "self", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x09", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_READ_REQ", ")", "data", ".", "append", "(", "PWM_RAM", ")", "data", ".", "append", "(", "BYTE2", ")", "send_data", "(", "data", ")", "rxdata", "=", "[", "]", "try", ":", "rxdata", "=", "SERPORT", ".", "read", "(", "13", ")", "if", "ord", "(", "rxdata", "[", "10", "]", ")", "<=", "127", ":", "return", "(", "(", "ord", "(", "rxdata", "[", "10", "]", ")", "&", "0x03", ")", "<<", "8", ")", "|", "(", "ord", "(", "rxdata", "[", "9", "]", ")", "&", "0xFF", ")", "else", ":", "return", "(", "ord", "(", "rxdata", "[", "10", "]", ")", "-", "0xFF", ")", "*", "0xFF", "+", "(", "ord", "(", "rxdata", "[", "9", "]", ")", "&", "0xFF", ")", "-", "0xFF", "except", "HerkulexError", ":", "raise", "HerkulexError", "(", "\"could not communicate with motors\"", ")" ]
Gets the current torque of Herkulex Gives the current load on the servo shaft. It is actually the PWM value to the motors Args: none Returns: int: the torque on servo shaft. range from -1023 to 1023 Raises: SerialException: Error occured while opening serial port
[ "Gets", "the", "current", "torque", "of", "Herkulex" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L623-L654
train
sastrarobotics/pyHerkulex
herkulex.py
servo.set_servo_speed
def set_servo_speed(self, goalspeed, led): """ Set the Herkulex in continuous rotation mode Args: goalspeed (int): the speed , range -1023 to 1023 led (int): the LED color 0x00 LED off 0x04 GREEN 0x08 BLUE 0x10 RED """ if goalspeed>0 : goalspeed_msb = (int(goalspeed)& 0xFF00) >> 8 goalspeed_lsb = int(goalspeed) & 0xff elif goalspeed<0 : goalspeed_msb = 64+(255- ((int(goalspeed)& 0xFF00) >> 8)) goalspeed_lsb = (abs(goalspeed) & 0xff) #print goalspeed_msb,goalspeed_lsb data = [] data.append(0x0C) data.append(self.servoid) data.append(I_JOG_REQ) data.append(goalspeed_lsb) data.append(goalspeed_msb) data.append(0x02|led) data.append(self.servoid) data.append(0x00) send_data(data)
python
def set_servo_speed(self, goalspeed, led): """ Set the Herkulex in continuous rotation mode Args: goalspeed (int): the speed , range -1023 to 1023 led (int): the LED color 0x00 LED off 0x04 GREEN 0x08 BLUE 0x10 RED """ if goalspeed>0 : goalspeed_msb = (int(goalspeed)& 0xFF00) >> 8 goalspeed_lsb = int(goalspeed) & 0xff elif goalspeed<0 : goalspeed_msb = 64+(255- ((int(goalspeed)& 0xFF00) >> 8)) goalspeed_lsb = (abs(goalspeed) & 0xff) #print goalspeed_msb,goalspeed_lsb data = [] data.append(0x0C) data.append(self.servoid) data.append(I_JOG_REQ) data.append(goalspeed_lsb) data.append(goalspeed_msb) data.append(0x02|led) data.append(self.servoid) data.append(0x00) send_data(data)
[ "def", "set_servo_speed", "(", "self", ",", "goalspeed", ",", "led", ")", ":", "if", "goalspeed", ">", "0", ":", "goalspeed_msb", "=", "(", "int", "(", "goalspeed", ")", "&", "0xFF00", ")", ">>", "8", "goalspeed_lsb", "=", "int", "(", "goalspeed", ")", "&", "0xff", "elif", "goalspeed", "<", "0", ":", "goalspeed_msb", "=", "64", "+", "(", "255", "-", "(", "(", "int", "(", "goalspeed", ")", "&", "0xFF00", ")", ">>", "8", ")", ")", "goalspeed_lsb", "=", "(", "abs", "(", "goalspeed", ")", "&", "0xff", ")", "#print goalspeed_msb,goalspeed_lsb", "data", "=", "[", "]", "data", ".", "append", "(", "0x0C", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "I_JOG_REQ", ")", "data", ".", "append", "(", "goalspeed_lsb", ")", "data", ".", "append", "(", "goalspeed_msb", ")", "data", ".", "append", "(", "0x02", "|", "led", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "0x00", ")", "send_data", "(", "data", ")" ]
Set the Herkulex in continuous rotation mode Args: goalspeed (int): the speed , range -1023 to 1023 led (int): the LED color 0x00 LED off 0x04 GREEN 0x08 BLUE 0x10 RED
[ "Set", "the", "Herkulex", "in", "continuous", "rotation", "mode" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L656-L686
train
sastrarobotics/pyHerkulex
herkulex.py
servo.set_position_p
def set_position_p(self, pvalue): """ Set the P gain of the position PID Args: pvalue (int): P value """ pvalue_msb = int(pvalue) >> 8 pvalue_lsb = int(pvalue) & 0xff data = [] data.append(0x0B) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(POSITION_KP_RAM) data.append(BYTE2) data.append( pvalue_lsb) data.append( pvalue_msb) send_data(data)
python
def set_position_p(self, pvalue): """ Set the P gain of the position PID Args: pvalue (int): P value """ pvalue_msb = int(pvalue) >> 8 pvalue_lsb = int(pvalue) & 0xff data = [] data.append(0x0B) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(POSITION_KP_RAM) data.append(BYTE2) data.append( pvalue_lsb) data.append( pvalue_msb) send_data(data)
[ "def", "set_position_p", "(", "self", ",", "pvalue", ")", ":", "pvalue_msb", "=", "int", "(", "pvalue", ")", ">>", "8", "pvalue_lsb", "=", "int", "(", "pvalue", ")", "&", "0xff", "data", "=", "[", "]", "data", ".", "append", "(", "0x0B", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_WRITE_REQ", ")", "data", ".", "append", "(", "POSITION_KP_RAM", ")", "data", ".", "append", "(", "BYTE2", ")", "data", ".", "append", "(", "pvalue_lsb", ")", "data", ".", "append", "(", "pvalue_msb", ")", "send_data", "(", "data", ")" ]
Set the P gain of the position PID Args: pvalue (int): P value
[ "Set", "the", "P", "gain", "of", "the", "position", "PID" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L688-L705
train
sastrarobotics/pyHerkulex
herkulex.py
servo.set_position_i
def set_position_i(self, ivalue): """ Set the I gain of the position PID Args: ivalue (int): I value """ ivalue_msb = int(ivalue) >> 8 ivalue_lsb = int(ivalue) & 0xff data = [] data.append(0x0B) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(POSITION_KI_RAM) data.append(BYTE2) data.append(ivalue_lsb) data.append(ivalue_msb) send_data(data)
python
def set_position_i(self, ivalue): """ Set the I gain of the position PID Args: ivalue (int): I value """ ivalue_msb = int(ivalue) >> 8 ivalue_lsb = int(ivalue) & 0xff data = [] data.append(0x0B) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(POSITION_KI_RAM) data.append(BYTE2) data.append(ivalue_lsb) data.append(ivalue_msb) send_data(data)
[ "def", "set_position_i", "(", "self", ",", "ivalue", ")", ":", "ivalue_msb", "=", "int", "(", "ivalue", ")", ">>", "8", "ivalue_lsb", "=", "int", "(", "ivalue", ")", "&", "0xff", "data", "=", "[", "]", "data", ".", "append", "(", "0x0B", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_WRITE_REQ", ")", "data", ".", "append", "(", "POSITION_KI_RAM", ")", "data", ".", "append", "(", "BYTE2", ")", "data", ".", "append", "(", "ivalue_lsb", ")", "data", ".", "append", "(", "ivalue_msb", ")", "send_data", "(", "data", ")" ]
Set the I gain of the position PID Args: ivalue (int): I value
[ "Set", "the", "I", "gain", "of", "the", "position", "PID" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L707-L724
train
sastrarobotics/pyHerkulex
herkulex.py
servo.set_position_d
def set_position_d(self, dvalue): """ Set the D gain of the PID Args: dvalue (int): D value """ dvalue_msb = int(dvalue) >> 8 dvalue_lsb = int(dvalue) & 0xff data = [] data.append(0x0B) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(POSITION_KD_RAM) data.append(BYTE2) data.append(dvalue_lsb) data.append(dvalue_msb) send_data(data)
python
def set_position_d(self, dvalue): """ Set the D gain of the PID Args: dvalue (int): D value """ dvalue_msb = int(dvalue) >> 8 dvalue_lsb = int(dvalue) & 0xff data = [] data.append(0x0B) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(POSITION_KD_RAM) data.append(BYTE2) data.append(dvalue_lsb) data.append(dvalue_msb) send_data(data)
[ "def", "set_position_d", "(", "self", ",", "dvalue", ")", ":", "dvalue_msb", "=", "int", "(", "dvalue", ")", ">>", "8", "dvalue_lsb", "=", "int", "(", "dvalue", ")", "&", "0xff", "data", "=", "[", "]", "data", ".", "append", "(", "0x0B", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_WRITE_REQ", ")", "data", ".", "append", "(", "POSITION_KD_RAM", ")", "data", ".", "append", "(", "BYTE2", ")", "data", ".", "append", "(", "dvalue_lsb", ")", "data", ".", "append", "(", "dvalue_msb", ")", "send_data", "(", "data", ")" ]
Set the D gain of the PID Args: dvalue (int): D value
[ "Set", "the", "D", "gain", "of", "the", "PID" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L726-L742
train
sastrarobotics/pyHerkulex
herkulex.py
servo.get_position_p
def get_position_p(self): """ Get the P value of the current PID for position """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(POSITION_KP_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) return (ord(rxdata[10])*256)+(ord(rxdata[9])&0xff) except HerkulexError: raise HerkulexError("could not communicate with motors")
python
def get_position_p(self): """ Get the P value of the current PID for position """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(POSITION_KP_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) return (ord(rxdata[10])*256)+(ord(rxdata[9])&0xff) except HerkulexError: raise HerkulexError("could not communicate with motors")
[ "def", "get_position_p", "(", "self", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x09", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_READ_REQ", ")", "data", ".", "append", "(", "POSITION_KP_RAM", ")", "data", ".", "append", "(", "BYTE2", ")", "send_data", "(", "data", ")", "rxdata", "=", "[", "]", "try", ":", "rxdata", "=", "SERPORT", ".", "read", "(", "13", ")", "return", "(", "ord", "(", "rxdata", "[", "10", "]", ")", "*", "256", ")", "+", "(", "ord", "(", "rxdata", "[", "9", "]", ")", "&", "0xff", ")", "except", "HerkulexError", ":", "raise", "HerkulexError", "(", "\"could not communicate with motors\"", ")" ]
Get the P value of the current PID for position
[ "Get", "the", "P", "value", "of", "the", "current", "PID", "for", "position" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L744-L760
train
sastrarobotics/pyHerkulex
herkulex.py
servo.get_position_i
def get_position_i(self): """ Get the I value of the current PID for position """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(POSITION_KI_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) return (ord(rxdata[10])*256)+(ord(rxdata[9])&0xff) except HerkulexError: raise HerkulexError("Could not read from motors")
python
def get_position_i(self): """ Get the I value of the current PID for position """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(POSITION_KI_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) return (ord(rxdata[10])*256)+(ord(rxdata[9])&0xff) except HerkulexError: raise HerkulexError("Could not read from motors")
[ "def", "get_position_i", "(", "self", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x09", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_READ_REQ", ")", "data", ".", "append", "(", "POSITION_KI_RAM", ")", "data", ".", "append", "(", "BYTE2", ")", "send_data", "(", "data", ")", "rxdata", "=", "[", "]", "try", ":", "rxdata", "=", "SERPORT", ".", "read", "(", "13", ")", "return", "(", "ord", "(", "rxdata", "[", "10", "]", ")", "*", "256", ")", "+", "(", "ord", "(", "rxdata", "[", "9", "]", ")", "&", "0xff", ")", "except", "HerkulexError", ":", "raise", "HerkulexError", "(", "\"Could not read from motors\"", ")" ]
Get the I value of the current PID for position
[ "Get", "the", "I", "value", "of", "the", "current", "PID", "for", "position" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L762-L778
train
sastrarobotics/pyHerkulex
herkulex.py
servo.get_position_d
def get_position_d(self): """ Get the D value of the current PID for position """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(POSITION_KD_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) return (ord(rxdata[10])*256)+(ord(rxdata[9])&0xff) except HerkulexError: raise HerkulexError("could not communicate with motors")
python
def get_position_d(self): """ Get the D value of the current PID for position """ data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(POSITION_KD_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) return (ord(rxdata[10])*256)+(ord(rxdata[9])&0xff) except HerkulexError: raise HerkulexError("could not communicate with motors")
[ "def", "get_position_d", "(", "self", ")", ":", "data", "=", "[", "]", "data", ".", "append", "(", "0x09", ")", "data", ".", "append", "(", "self", ".", "servoid", ")", "data", ".", "append", "(", "RAM_READ_REQ", ")", "data", ".", "append", "(", "POSITION_KD_RAM", ")", "data", ".", "append", "(", "BYTE2", ")", "send_data", "(", "data", ")", "rxdata", "=", "[", "]", "try", ":", "rxdata", "=", "SERPORT", ".", "read", "(", "13", ")", "return", "(", "ord", "(", "rxdata", "[", "10", "]", ")", "*", "256", ")", "+", "(", "ord", "(", "rxdata", "[", "9", "]", ")", "&", "0xff", ")", "except", "HerkulexError", ":", "raise", "HerkulexError", "(", "\"could not communicate with motors\"", ")" ]
Get the D value of the current PID for position
[ "Get", "the", "D", "value", "of", "the", "current", "PID", "for", "position" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L780-L796
train
sastrarobotics/pyHerkulex
herkulex.py
servo.save_pid_eeprom
def save_pid_eeprom(self): """ saves the PID values from RAM to EEPROM """ pval = self.get_position_p() ival = self.get_position_i() dval = self.get_position_d() #write P value pvalue_msb = int(pval) >> 8 pvalue_lsb = int(pval) & 0xff data_p = [] data_p.append(0x0B) data_p.append(self.servoid) data_p.append(EEP_WRITE_REQ) data_p.append(POSITION_KP_EEP) data_p.append(BYTE2) data_p.append( pvalue_lsb) data_p.append( pvalue_msb) send_data(data_p) # write I value ivalue_msb = int(ival) >> 8 ivalue_lsb = int(ival) & 0xff data_i = [] data_i.append(0x0B) data_i.append(self.servoid) data_i.append(EEP_WRITE_REQ) data_i.append(POSITION_KI_EEP) data_i.append(BYTE2) data_i.append( ivalue_lsb) data_i.append( ivalue_msb) send_data(data_i) # write D value dvalue_msb = int(dval) >> 8 dvalue_lsb = int(dval) & 0xff data_d = [] data_d.append(0x0B) data_d.append(self.servoid) data_d.append(EEP_WRITE_REQ) data_d.append(POSITION_KD_EEP) data_d.append(BYTE2) data_d.append( dvalue_lsb) data_d.append( dvalue_msb) send_data(data_d)
python
def save_pid_eeprom(self): """ saves the PID values from RAM to EEPROM """ pval = self.get_position_p() ival = self.get_position_i() dval = self.get_position_d() #write P value pvalue_msb = int(pval) >> 8 pvalue_lsb = int(pval) & 0xff data_p = [] data_p.append(0x0B) data_p.append(self.servoid) data_p.append(EEP_WRITE_REQ) data_p.append(POSITION_KP_EEP) data_p.append(BYTE2) data_p.append( pvalue_lsb) data_p.append( pvalue_msb) send_data(data_p) # write I value ivalue_msb = int(ival) >> 8 ivalue_lsb = int(ival) & 0xff data_i = [] data_i.append(0x0B) data_i.append(self.servoid) data_i.append(EEP_WRITE_REQ) data_i.append(POSITION_KI_EEP) data_i.append(BYTE2) data_i.append( ivalue_lsb) data_i.append( ivalue_msb) send_data(data_i) # write D value dvalue_msb = int(dval) >> 8 dvalue_lsb = int(dval) & 0xff data_d = [] data_d.append(0x0B) data_d.append(self.servoid) data_d.append(EEP_WRITE_REQ) data_d.append(POSITION_KD_EEP) data_d.append(BYTE2) data_d.append( dvalue_lsb) data_d.append( dvalue_msb) send_data(data_d)
[ "def", "save_pid_eeprom", "(", "self", ")", ":", "pval", "=", "self", ".", "get_position_p", "(", ")", "ival", "=", "self", ".", "get_position_i", "(", ")", "dval", "=", "self", ".", "get_position_d", "(", ")", "#write P value", "pvalue_msb", "=", "int", "(", "pval", ")", ">>", "8", "pvalue_lsb", "=", "int", "(", "pval", ")", "&", "0xff", "data_p", "=", "[", "]", "data_p", ".", "append", "(", "0x0B", ")", "data_p", ".", "append", "(", "self", ".", "servoid", ")", "data_p", ".", "append", "(", "EEP_WRITE_REQ", ")", "data_p", ".", "append", "(", "POSITION_KP_EEP", ")", "data_p", ".", "append", "(", "BYTE2", ")", "data_p", ".", "append", "(", "pvalue_lsb", ")", "data_p", ".", "append", "(", "pvalue_msb", ")", "send_data", "(", "data_p", ")", "# write I value", "ivalue_msb", "=", "int", "(", "ival", ")", ">>", "8", "ivalue_lsb", "=", "int", "(", "ival", ")", "&", "0xff", "data_i", "=", "[", "]", "data_i", ".", "append", "(", "0x0B", ")", "data_i", ".", "append", "(", "self", ".", "servoid", ")", "data_i", ".", "append", "(", "EEP_WRITE_REQ", ")", "data_i", ".", "append", "(", "POSITION_KI_EEP", ")", "data_i", ".", "append", "(", "BYTE2", ")", "data_i", ".", "append", "(", "ivalue_lsb", ")", "data_i", ".", "append", "(", "ivalue_msb", ")", "send_data", "(", "data_i", ")", "# write D value", "dvalue_msb", "=", "int", "(", "dval", ")", ">>", "8", "dvalue_lsb", "=", "int", "(", "dval", ")", "&", "0xff", "data_d", "=", "[", "]", "data_d", ".", "append", "(", "0x0B", ")", "data_d", ".", "append", "(", "self", ".", "servoid", ")", "data_d", ".", "append", "(", "EEP_WRITE_REQ", ")", "data_d", ".", "append", "(", "POSITION_KD_EEP", ")", "data_d", ".", "append", "(", "BYTE2", ")", "data_d", ".", "append", "(", "dvalue_lsb", ")", "data_d", ".", "append", "(", "dvalue_msb", ")", "send_data", "(", "data_d", ")" ]
saves the PID values from RAM to EEPROM
[ "saves", "the", "PID", "values", "from", "RAM", "to", "EEPROM" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L798-L846
train
sastrarobotics/pyHerkulex
herkulex.py
servo.get_servo_angle
def get_servo_angle(self): """ Gets the current angle of the servo in degrees Args: none Returns: int : the current servo angle """ servoposition = self.get_servo_position() if (self.servomodel==0x06) or (self.servomodel == 0x04): return scale(servoposition, 10627, 22129, -159.9, 159.6) else: return scale(servoposition, 21, 1002, -150, 150)
python
def get_servo_angle(self): """ Gets the current angle of the servo in degrees Args: none Returns: int : the current servo angle """ servoposition = self.get_servo_position() if (self.servomodel==0x06) or (self.servomodel == 0x04): return scale(servoposition, 10627, 22129, -159.9, 159.6) else: return scale(servoposition, 21, 1002, -150, 150)
[ "def", "get_servo_angle", "(", "self", ")", ":", "servoposition", "=", "self", ".", "get_servo_position", "(", ")", "if", "(", "self", ".", "servomodel", "==", "0x06", ")", "or", "(", "self", ".", "servomodel", "==", "0x04", ")", ":", "return", "scale", "(", "servoposition", ",", "10627", ",", "22129", ",", "-", "159.9", ",", "159.6", ")", "else", ":", "return", "scale", "(", "servoposition", ",", "21", ",", "1002", ",", "-", "150", ",", "150", ")" ]
Gets the current angle of the servo in degrees Args: none Returns: int : the current servo angle
[ "Gets", "the", "current", "angle", "of", "the", "servo", "in", "degrees" ]
3a42046cbfea8c7e343a04f42facba5e7bca570e
https://github.com/sastrarobotics/pyHerkulex/blob/3a42046cbfea8c7e343a04f42facba5e7bca570e/herkulex.py#L870-L883
train
johnnoone/json-spec
src/jsonspec/cli.py
disable_logging
def disable_logging(func): return func """ Temporary disable logging. """ handler = logging.NullHandler() @wraps(func) def wrapper(*args, **kwargs): logger = logging.getLogger() logger.addHandler(handler) resp = func(*args, **kwargs) logger.removeHandler(handler) return resp return wrapper
python
def disable_logging(func): return func """ Temporary disable logging. """ handler = logging.NullHandler() @wraps(func) def wrapper(*args, **kwargs): logger = logging.getLogger() logger.addHandler(handler) resp = func(*args, **kwargs) logger.removeHandler(handler) return resp return wrapper
[ "def", "disable_logging", "(", "func", ")", ":", "return", "func", "handler", "=", "logging", ".", "NullHandler", "(", ")", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "logger", ".", "addHandler", "(", "handler", ")", "resp", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "logger", ".", "removeHandler", "(", "handler", ")", "return", "resp", "return", "wrapper" ]
Temporary disable logging.
[ "Temporary", "disable", "logging", "." ]
f91981724cea0c366bd42a6670eb07bbe31c0e0c
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/cli.py#L28-L42
train
johnnoone/json-spec
src/jsonspec/cli.py
format_output
def format_output(func): return func """ Format output. """ @wraps(func) def wrapper(*args, **kwargs): try: response = func(*args, **kwargs) except Exception as error: print(colored(error, 'red'), file=sys.stderr) sys.exit(1) else: print(response) sys.exit(0) return wrapper
python
def format_output(func): return func """ Format output. """ @wraps(func) def wrapper(*args, **kwargs): try: response = func(*args, **kwargs) except Exception as error: print(colored(error, 'red'), file=sys.stderr) sys.exit(1) else: print(response) sys.exit(0) return wrapper
[ "def", "format_output", "(", "func", ")", ":", "return", "func", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "response", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "error", ":", "print", "(", "colored", "(", "error", ",", "'red'", ")", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "else", ":", "print", "(", "response", ")", "sys", ".", "exit", "(", "0", ")", "return", "wrapper" ]
Format output.
[ "Format", "output", "." ]
f91981724cea0c366bd42a6670eb07bbe31c0e0c
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/cli.py#L45-L61
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/read_probes.py
ReadProbes.start
def start(self, *args, **kwargs): """ start the read_probe thread """ self._stop = False super(ReadProbes, self).start(*args, **kwargs)
python
def start(self, *args, **kwargs): """ start the read_probe thread """ self._stop = False super(ReadProbes, self).start(*args, **kwargs)
[ "def", "start", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_stop", "=", "False", "super", "(", "ReadProbes", ",", "self", ")", ".", "start", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
start the read_probe thread
[ "start", "the", "read_probe", "thread" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/read_probes.py#L70-L75
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/read_probes.py
ReadProbes.quit
def quit(self, *args, **kwargs): # real signature unknown """ quit the read_probe thread """ self._stop = True super(ReadProbes, self).quit(*args, **kwargs)
python
def quit(self, *args, **kwargs): # real signature unknown """ quit the read_probe thread """ self._stop = True super(ReadProbes, self).quit(*args, **kwargs)
[ "def", "quit", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# real signature unknown", "self", ".", "_stop", "=", "True", "super", "(", "ReadProbes", ",", "self", ")", ".", "quit", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
quit the read_probe thread
[ "quit", "the", "read_probe", "thread" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/read_probes.py#L78-L83
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/scripts.py
Script._set_current_subscript
def _set_current_subscript(self, active): """ sets the current subscript and keeps a counter of how ofter a particular subscript has been executed this information is usefull when implementing a status update or plotting functions that depend on which subscript is being executed keeps track of the following dictionary: self._current_subscript_stage = { 'current_subscript' : reference to the current subscrit 'subscript_exec_count' : dictionary where key is the subscript name and value how often is has been executed 'subscript_exec_duration' : dictionary where key is the subscript name and value the average duration of executing the subscript } Args: active: True if the current subscript is just started, False if it just finished """ current_subscript = self.sender() if active: for subscript_name in list(self._current_subscript_stage['subscript_exec_count'].keys()): if subscript_name == current_subscript.name: self._current_subscript_stage['subscript_exec_count'][subscript_name] += 1 self._current_subscript_stage['current_subscript'] = current_subscript else: self._current_subscript_stage['current_subscript'] = current_subscript for subscript_name in list(self._current_subscript_stage['subscript_exec_count'].keys()): # calculate the average duration to execute the subscript if subscript_name == current_subscript.name: duration = current_subscript.end_time - current_subscript.start_time if subscript_name in self._current_subscript_stage['subscript_exec_duration']: duration_old = self._current_subscript_stage['subscript_exec_duration'][subscript_name] else: duration_old = datetime.timedelta(0) exec_count = self._current_subscript_stage['subscript_exec_count'][subscript_name] duration_new = (duration_old * (exec_count - 1) + duration) self._current_subscript_stage['subscript_exec_duration'][subscript_name] = (duration_old * ( exec_count - 1) + duration) / exec_count
python
def _set_current_subscript(self, active): """ sets the current subscript and keeps a counter of how ofter a particular subscript has been executed this information is usefull when implementing a status update or plotting functions that depend on which subscript is being executed keeps track of the following dictionary: self._current_subscript_stage = { 'current_subscript' : reference to the current subscrit 'subscript_exec_count' : dictionary where key is the subscript name and value how often is has been executed 'subscript_exec_duration' : dictionary where key is the subscript name and value the average duration of executing the subscript } Args: active: True if the current subscript is just started, False if it just finished """ current_subscript = self.sender() if active: for subscript_name in list(self._current_subscript_stage['subscript_exec_count'].keys()): if subscript_name == current_subscript.name: self._current_subscript_stage['subscript_exec_count'][subscript_name] += 1 self._current_subscript_stage['current_subscript'] = current_subscript else: self._current_subscript_stage['current_subscript'] = current_subscript for subscript_name in list(self._current_subscript_stage['subscript_exec_count'].keys()): # calculate the average duration to execute the subscript if subscript_name == current_subscript.name: duration = current_subscript.end_time - current_subscript.start_time if subscript_name in self._current_subscript_stage['subscript_exec_duration']: duration_old = self._current_subscript_stage['subscript_exec_duration'][subscript_name] else: duration_old = datetime.timedelta(0) exec_count = self._current_subscript_stage['subscript_exec_count'][subscript_name] duration_new = (duration_old * (exec_count - 1) + duration) self._current_subscript_stage['subscript_exec_duration'][subscript_name] = (duration_old * ( exec_count - 1) + duration) / exec_count
[ "def", "_set_current_subscript", "(", "self", ",", "active", ")", ":", "current_subscript", "=", "self", ".", "sender", "(", ")", "if", "active", ":", "for", "subscript_name", "in", "list", "(", "self", ".", "_current_subscript_stage", "[", "'subscript_exec_count'", "]", ".", "keys", "(", ")", ")", ":", "if", "subscript_name", "==", "current_subscript", ".", "name", ":", "self", ".", "_current_subscript_stage", "[", "'subscript_exec_count'", "]", "[", "subscript_name", "]", "+=", "1", "self", ".", "_current_subscript_stage", "[", "'current_subscript'", "]", "=", "current_subscript", "else", ":", "self", ".", "_current_subscript_stage", "[", "'current_subscript'", "]", "=", "current_subscript", "for", "subscript_name", "in", "list", "(", "self", ".", "_current_subscript_stage", "[", "'subscript_exec_count'", "]", ".", "keys", "(", ")", ")", ":", "# calculate the average duration to execute the subscript", "if", "subscript_name", "==", "current_subscript", ".", "name", ":", "duration", "=", "current_subscript", ".", "end_time", "-", "current_subscript", ".", "start_time", "if", "subscript_name", "in", "self", ".", "_current_subscript_stage", "[", "'subscript_exec_duration'", "]", ":", "duration_old", "=", "self", ".", "_current_subscript_stage", "[", "'subscript_exec_duration'", "]", "[", "subscript_name", "]", "else", ":", "duration_old", "=", "datetime", ".", "timedelta", "(", "0", ")", "exec_count", "=", "self", ".", "_current_subscript_stage", "[", "'subscript_exec_count'", "]", "[", "subscript_name", "]", "duration_new", "=", "(", "duration_old", "*", "(", "exec_count", "-", "1", ")", "+", "duration", ")", "self", ".", "_current_subscript_stage", "[", "'subscript_exec_duration'", "]", "[", "subscript_name", "]", "=", "(", "duration_old", "*", "(", "exec_count", "-", "1", ")", "+", "duration", ")", "/", "exec_count" ]
sets the current subscript and keeps a counter of how ofter a particular subscript has been executed this information is usefull when implementing a status update or plotting functions that depend on which subscript is being executed keeps track of the following dictionary: self._current_subscript_stage = { 'current_subscript' : reference to the current subscrit 'subscript_exec_count' : dictionary where key is the subscript name and value how often is has been executed 'subscript_exec_duration' : dictionary where key is the subscript name and value the average duration of executing the subscript } Args: active: True if the current subscript is just started, False if it just finished
[ "sets", "the", "current", "subscript", "and", "keeps", "a", "counter", "of", "how", "ofter", "a", "particular", "subscript", "has", "been", "executed", "this", "information", "is", "usefull", "when", "implementing", "a", "status", "update", "or", "plotting", "functions", "that", "depend", "on", "which", "subscript", "is", "being", "executed" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/scripts.py#L147-L185
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/scripts.py
Script.remaining_time
def remaining_time(self): """ estimates the time remaining until script is finished """ elapsed_time = (datetime.datetime.now() - self.start_time).total_seconds() # safety to avoid devision by zero if self.progress == 0: self.progress = 1 estimated_total_time = 100. / self.progress * elapsed_time return datetime.timedelta(seconds = max(estimated_total_time - elapsed_time, 0))
python
def remaining_time(self): """ estimates the time remaining until script is finished """ elapsed_time = (datetime.datetime.now() - self.start_time).total_seconds() # safety to avoid devision by zero if self.progress == 0: self.progress = 1 estimated_total_time = 100. / self.progress * elapsed_time return datetime.timedelta(seconds = max(estimated_total_time - elapsed_time, 0))
[ "def", "remaining_time", "(", "self", ")", ":", "elapsed_time", "=", "(", "datetime", ".", "datetime", ".", "now", "(", ")", "-", "self", ".", "start_time", ")", ".", "total_seconds", "(", ")", "# safety to avoid devision by zero", "if", "self", ".", "progress", "==", "0", ":", "self", ".", "progress", "=", "1", "estimated_total_time", "=", "100.", "/", "self", ".", "progress", "*", "elapsed_time", "return", "datetime", ".", "timedelta", "(", "seconds", "=", "max", "(", "estimated_total_time", "-", "elapsed_time", ",", "0", ")", ")" ]
estimates the time remaining until script is finished
[ "estimates", "the", "time", "remaining", "until", "script", "is", "finished" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/scripts.py#L340-L351
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/scripts.py
Script.stop
def stop(self): """ stops itself and all the subscript """ for subscript in list(self.scripts.values()): subscript.stop() print(('--- stopping: ', self.name)) self._abort = True
python
def stop(self): """ stops itself and all the subscript """ for subscript in list(self.scripts.values()): subscript.stop() print(('--- stopping: ', self.name)) self._abort = True
[ "def", "stop", "(", "self", ")", ":", "for", "subscript", "in", "list", "(", "self", ".", "scripts", ".", "values", "(", ")", ")", ":", "subscript", ".", "stop", "(", ")", "print", "(", "(", "'--- stopping: '", ",", "self", ".", "name", ")", ")", "self", ".", "_abort", "=", "True" ]
stops itself and all the subscript
[ "stops", "itself", "and", "all", "the", "subscript" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/scripts.py#L447-L454
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/scripts.py
Script.get_script_module
def get_script_module(script_information, package='pylabcontrol', verbose=False): """ wrapper to get the module for a script Args: script_information: information of the script. This can be - a dictionary - a Script instance - name of Script class package (optional): name of the package to which the script belongs, i.e. pylabcontrol or b26toolkit only used when script_information is a string Returns: module """ module, _, _, _, _, _, _ = Script.get_script_information(script_information=script_information, package=package, verbose=verbose) return module
python
def get_script_module(script_information, package='pylabcontrol', verbose=False): """ wrapper to get the module for a script Args: script_information: information of the script. This can be - a dictionary - a Script instance - name of Script class package (optional): name of the package to which the script belongs, i.e. pylabcontrol or b26toolkit only used when script_information is a string Returns: module """ module, _, _, _, _, _, _ = Script.get_script_information(script_information=script_information, package=package, verbose=verbose) return module
[ "def", "get_script_module", "(", "script_information", ",", "package", "=", "'pylabcontrol'", ",", "verbose", "=", "False", ")", ":", "module", ",", "_", ",", "_", ",", "_", ",", "_", ",", "_", ",", "_", "=", "Script", ".", "get_script_information", "(", "script_information", "=", "script_information", ",", "package", "=", "package", ",", "verbose", "=", "verbose", ")", "return", "module" ]
wrapper to get the module for a script Args: script_information: information of the script. This can be - a dictionary - a Script instance - name of Script class package (optional): name of the package to which the script belongs, i.e. pylabcontrol or b26toolkit only used when script_information is a string Returns: module
[ "wrapper", "to", "get", "the", "module", "for", "a", "script" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/scripts.py#L1233-L1250
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/scripts.py
Script.duplicate
def duplicate(self): """ create an copy of the script Returns: """ # get settings of script class_of_script = self.__class__ script_name = self.name script_instruments = self.instruments sub_scripts = self.scripts script_settings = self.settings log_function = self.log_function data_path = self.data_path #create a new instance of same script type class_creation_string = '' if script_instruments != {}: class_creation_string += ', instruments = script_instruments' if sub_scripts != {}: class_creation_string += ', scripts = sub_scripts' if script_settings != {}: class_creation_string += ', settings = script_settings' if log_function is not None: class_creation_string += ', log_function = log_function' if data_path is not None: class_creation_string += ', data_path = data_path' class_creation_string = 'class_of_script(name=script_name{:s})'.format(class_creation_string) # create instance script_instance = eval(class_creation_string) # copy some other properties that might be checked later for the duplicated script script_instance.data = deepcopy(self.data) script_instance.start_time = self.start_time script_instance.end_time = self.end_time script_instance.is_running = self.is_running return script_instance
python
def duplicate(self): """ create an copy of the script Returns: """ # get settings of script class_of_script = self.__class__ script_name = self.name script_instruments = self.instruments sub_scripts = self.scripts script_settings = self.settings log_function = self.log_function data_path = self.data_path #create a new instance of same script type class_creation_string = '' if script_instruments != {}: class_creation_string += ', instruments = script_instruments' if sub_scripts != {}: class_creation_string += ', scripts = sub_scripts' if script_settings != {}: class_creation_string += ', settings = script_settings' if log_function is not None: class_creation_string += ', log_function = log_function' if data_path is not None: class_creation_string += ', data_path = data_path' class_creation_string = 'class_of_script(name=script_name{:s})'.format(class_creation_string) # create instance script_instance = eval(class_creation_string) # copy some other properties that might be checked later for the duplicated script script_instance.data = deepcopy(self.data) script_instance.start_time = self.start_time script_instance.end_time = self.end_time script_instance.is_running = self.is_running return script_instance
[ "def", "duplicate", "(", "self", ")", ":", "# get settings of script", "class_of_script", "=", "self", ".", "__class__", "script_name", "=", "self", ".", "name", "script_instruments", "=", "self", ".", "instruments", "sub_scripts", "=", "self", ".", "scripts", "script_settings", "=", "self", ".", "settings", "log_function", "=", "self", ".", "log_function", "data_path", "=", "self", ".", "data_path", "#create a new instance of same script type", "class_creation_string", "=", "''", "if", "script_instruments", "!=", "{", "}", ":", "class_creation_string", "+=", "', instruments = script_instruments'", "if", "sub_scripts", "!=", "{", "}", ":", "class_creation_string", "+=", "', scripts = sub_scripts'", "if", "script_settings", "!=", "{", "}", ":", "class_creation_string", "+=", "', settings = script_settings'", "if", "log_function", "is", "not", "None", ":", "class_creation_string", "+=", "', log_function = log_function'", "if", "data_path", "is", "not", "None", ":", "class_creation_string", "+=", "', data_path = data_path'", "class_creation_string", "=", "'class_of_script(name=script_name{:s})'", ".", "format", "(", "class_creation_string", ")", "# create instance", "script_instance", "=", "eval", "(", "class_creation_string", ")", "# copy some other properties that might be checked later for the duplicated script", "script_instance", ".", "data", "=", "deepcopy", "(", "self", ".", "data", ")", "script_instance", ".", "start_time", "=", "self", ".", "start_time", "script_instance", ".", "end_time", "=", "self", ".", "end_time", "script_instance", ".", "is_running", "=", "self", ".", "is_running", "return", "script_instance" ]
create an copy of the script Returns:
[ "create", "an", "copy", "of", "the", "script" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/scripts.py#L1252-L1292
train
LISE-B26/pylabcontrol
build/lib/pylabcontrol/src/core/scripts.py
Script.plot_validate
def plot_validate(self, figure_list): """ plots the data contained in self.data, which should be a dictionary or a deque of dictionaries for the latter use the last entry """ axes_list = self.get_axes_layout_validate(figure_list) self._plot_validate(axes_list)
python
def plot_validate(self, figure_list): """ plots the data contained in self.data, which should be a dictionary or a deque of dictionaries for the latter use the last entry """ axes_list = self.get_axes_layout_validate(figure_list) self._plot_validate(axes_list)
[ "def", "plot_validate", "(", "self", ",", "figure_list", ")", ":", "axes_list", "=", "self", ".", "get_axes_layout_validate", "(", "figure_list", ")", "self", ".", "_plot_validate", "(", "axes_list", ")" ]
plots the data contained in self.data, which should be a dictionary or a deque of dictionaries for the latter use the last entry
[ "plots", "the", "data", "contained", "in", "self", ".", "data", "which", "should", "be", "a", "dictionary", "or", "a", "deque", "of", "dictionaries", "for", "the", "latter", "use", "the", "last", "entry" ]
67482e5157fcd1c40705e5c2cacfb93564703ed0
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/scripts.py#L1379-L1386
train
etal/biofrills
biofrills/stats/__init__.py
uniqueof20
def uniqueof20(k, rep=10000): """Sample k times out of alphabet, how many different?""" alphabet = 'ACDEFGHIKLMNPQRSTVWY' reps = [len(set(random.choice(alphabet) for i in range(k))) for j in range(rep)] return sum(reps) / len(reps)
python
def uniqueof20(k, rep=10000): """Sample k times out of alphabet, how many different?""" alphabet = 'ACDEFGHIKLMNPQRSTVWY' reps = [len(set(random.choice(alphabet) for i in range(k))) for j in range(rep)] return sum(reps) / len(reps)
[ "def", "uniqueof20", "(", "k", ",", "rep", "=", "10000", ")", ":", "alphabet", "=", "'ACDEFGHIKLMNPQRSTVWY'", "reps", "=", "[", "len", "(", "set", "(", "random", ".", "choice", "(", "alphabet", ")", "for", "i", "in", "range", "(", "k", ")", ")", ")", "for", "j", "in", "range", "(", "rep", ")", "]", "return", "sum", "(", "reps", ")", "/", "len", "(", "reps", ")" ]
Sample k times out of alphabet, how many different?
[ "Sample", "k", "times", "out", "of", "alphabet", "how", "many", "different?" ]
36684bb6c7632f96215e8b2b4ebc86640f331bcd
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/stats/__init__.py#L6-L12
train