code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
jf = JFS.post('%s?mkDir=true' % jottapath)
return instanceof(jf, JFSFolder) | def mkdir(jottapath, JFS) | Make a new directory (a.k.a. folder) on JottaCloud.
Returns boolean | 13.533113 | 18.291155 | 0.739872 |
filedirlist = JFS.getObject('%s?mode=list' % jottapath)
log.debug("got tree: %s", filedirlist)
if not isinstance(filedirlist, JFSFileDirList):
yield ( '', tuple(), tuple() )
for path in filedirlist.tree:
yield path | def iter_tree(jottapath, JFS) | Get a tree of of files and folders. use as an iterator, you get something like os.walk | 8.087621 | 7.760024 | 1.042216 |
# - Query metadata of one file
# - Return a dict with a 'size' key, and a file size value (-1 for not found)
# - Retried if an exception is thrown
log.Info('Querying size of %s' % filename)
from jottalib.JFS import JFSNotFoundError, JFSIncompleteFile
remote_pa... | def _query(self, filename) | Get size of filename | 7.779423 | 7.034285 | 1.105929 |
_blip = elem.xpath('.//a:blip', namespaces=NAMESPACES)
if len(_blip) > 0:
blip = _blip[0]
_rid = blip.attrib[_name('{{{r}}}embed')]
img = doc.Image(_rid)
container.elements.append(img) | def parse_drawing(document, container, elem) | Parse drawing element.
We don't do much with drawing element. We can find embeded image but we don't do more than that. | 6.46057 | 6.292333 | 1.026737 |
"Parse the footnote element."
_rid = elem.attrib[_name('{{{w}}}id')]
foot = doc.Footnote(_rid)
container.elements.append(foot) | def parse_footnote(document, container, elem) | Parse the footnote element. | 20.226194 | 17.928257 | 1.128174 |
"Parse the endnote element."
_rid = elem.attrib[_name('{{{w}}}id')]
note = doc.Endnote(_rid)
container.elements.append(note) | def parse_endnote(document, container, elem) | Parse the endnote element. | 20.797958 | 18.213816 | 1.141878 |
"Parse text element."
txt = None
alternate = element.find(_name('{{{mc}}}AlternateContent'))
if alternate is not None:
parse_alternate(document, container, alternate)
br = element.find(_name('{{{w}}}br'))
if br is not None:
if _name('{{{w}}}type') in br.attrib:
_... | def parse_text(document, container, element) | Parse text element. | 2.614749 | 2.596587 | 1.006995 |
"Parse the endnote element."
tag = doc.SmartTag()
tag.element = tag_elem.attrib[_name('{{{w}}}element')]
for elem in tag_elem:
if elem.tag == _name('{{{w}}}r'):
parse_text(document, tag, elem)
if elem.tag == _name('{{{w}}}smartTag'):
parse_smarttag(document, t... | def parse_smarttag(document, container, tag_elem) | Parse the endnote element. | 5.705405 | 4.767616 | 1.1967 |
paragraph = doc.Paragraph()
paragraph.document = document
for elem in par:
if elem.tag == _name('{{{w}}}pPr'):
parse_paragraph_properties(document, paragraph, elem)
if elem.tag == _name('{{{w}}}r'):
parse_text(document, paragraph, elem)
if elem.tag ==... | def parse_paragraph(document, par) | Parse paragraph element.
Some other elements could be found inside of paragraph element (math, links). | 2.504982 | 2.546276 | 0.983783 |
"Parse table properties."
if not table:
return
style = prop.find(_name('{{{w}}}tblStyle'))
if style is not None:
table.style_id = style.attrib[_name('{{{w}}}val')]
doc.add_style_as_used(table.style_id) | def parse_table_properties(doc, table, prop) | Parse table properties. | 7.174483 | 7.02545 | 1.021213 |
"Parse table column properties."
if not cell:
return
grid = prop.find(_name('{{{w}}}gridSpan'))
if grid is not None:
cell.grid_span = int(grid.attrib[_name('{{{w}}}val')])
vmerge = prop.find(_name('{{{w}}}vMerge'))
if vmerge is not None:
if _name('{{{w}}}val') in vme... | def parse_table_column_properties(doc, cell, prop) | Parse table column properties. | 3.513923 | 3.427737 | 1.025144 |
"Parse table element."
def _change(rows, pos_x):
if len(rows) == 1:
return rows
count_x = 1
for x in rows[-1]:
if count_x == pos_x:
x.row_span += 1
count_x += x.grid_span
return rows
table = doc.Table()
tbl_pr = t... | def parse_table(document, tbl) | Parse table element. | 3.46579 | 3.452838 | 1.003751 |
document = etree.fromstring(xmlcontent)
body = document.xpath('.//w:body', namespaces=NAMESPACES)[0]
document = doc.Document()
for elem in body:
if elem.tag == _name('{{{w}}}p'):
document.elements.append(parse_paragraph(document, elem))
if elem.tag == _name('{{{w}}}... | def parse_document(xmlcontent) | Parse document with content.
Content is placed in file 'document.xml'. | 3.401081 | 3.552709 | 0.957321 |
doc = etree.fromstring(xmlcontent)
for elem in doc:
if elem.tag == _name('{{{pr}}}Relationship'):
rel = {'target': elem.attrib['Target'],
'type': elem.attrib['Type'],
'target_mode': elem.attrib.get('TargetMode', 'Internal')}
document.... | def parse_relationship(document, xmlcontent, rel_type) | Parse relationship document.
Relationships hold information like external or internal references for links.
Relationships are placed in file '_rels/document.xml.rels'. | 4.097334 | 4.009856 | 1.021816 |
styles = etree.fromstring(xmlcontent)
_r = styles.xpath('.//w:rPrDefault', namespaces=NAMESPACES)
if len(_r) > 0:
rpr = _r[0].find(_name('{{{w}}}rPr'))
if rpr is not None:
st = doc.Style()
parse_previous_properties(document, st, rpr)
document.defa... | def parse_style(document, xmlcontent) | Parse styles document.
Styles are defined in file 'styles.xml'. | 2.148237 | 2.184673 | 0.983322 |
comments = etree.fromstring(xmlcontent)
document.comments = {}
for comment in comments.xpath('.//w:comment', namespaces=NAMESPACES):
# w:author
# w:id
# w: date
comment_id = comment.attrib[_name('{{{w}}}id')]
comm = doc.CommentContent(comment_id)
comm.... | def parse_comments(document, xmlcontent) | Parse comments document.
Comments are defined in file 'comments.xml' | 3.485991 | 3.605919 | 0.966741 |
footnotes = etree.fromstring(xmlcontent)
document.footnotes = {}
for footnote in footnotes.xpath('.//w:footnote', namespaces=NAMESPACES):
_type = footnote.attrib.get(_name('{{{w}}}type'), None)
# don't know what to do with these now
if _type in ['separator', 'continuationSepa... | def parse_footnotes(document, xmlcontent) | Parse footnotes document.
Footnotes are defined in file 'footnotes.xml' | 3.817869 | 3.98868 | 0.957176 |
endnotes = etree.fromstring(xmlcontent)
document.endnotes = {}
for note in endnotes.xpath('.//w:endnote', namespaces=NAMESPACES):
paragraphs = [parse_paragraph(document, para) for para in note.xpath('.//w:p', namespaces=NAMESPACES)]
document.endnotes[note.attrib[_name('{{{w}}}id')]] ... | def parse_endnotes(document, xmlcontent) | Parse endnotes document.
Endnotes are defined in file 'endnotes.xml' | 3.800136 | 4.001749 | 0.949619 |
numbering = etree.fromstring(xmlcontent)
document.abstruct_numbering = {}
document.numbering = {}
for abstruct_num in numbering.xpath('.//w:abstractNum', namespaces=NAMESPACES):
numb = {}
for lvl in abstruct_num.xpath('./w:lvl', namespaces=NAMESPACES):
ilvl = int(lvl.... | def parse_numbering(document, xmlcontent) | Parse numbering document.
Numbering is defined in file 'numbering.xml'. | 2.535556 | 2.587344 | 0.979984 |
logger.info('Parsing %s file.', file_object.file_name)
# Read the files
doc_content = file_object.read_file('document.xml')
# Parse the document
document = parse_document(doc_content)
try:
style_content = file_object.read_file('styles.xml')
parse_style(document, style_co... | def parse_from_file(file_object) | Parses existing OOXML file.
:Args:
- file_object (:class:`ooxml.docx.DOCXFile`): OOXML file object
:Returns:
Returns parsed document of type :class:`ooxml.doc.Document` | 1.590321 | 1.565861 | 1.015621 |
for st in self.styles.values():
if st:
if st.name == name:
return st
if style_type and not st:
st = self.styles.get(self.default_styles[style_type], None)
return st | def get_by_name(self, name, style_type = None) | Find style by it's descriptive name.
:Returns:
Returns found style of type :class:`ooxml.doc.Style`. | 3.760658 | 4.543846 | 0.827638 |
for st in self.styles.values():
if st:
if st.style_id == style_id:
return st
if style_type:
return self.styles.get(self.default_styles[style_type], None)
return None | def get_by_id(self, style_id, style_type = None) | Find style by it's unique identifier
:Returns:
Returns found style of type :class:`ooxml.doc.Style`. | 3.074494 | 3.51908 | 0.873664 |
if affinity is not None:
affinity = CPUSet(affinity)
if not affinity.issubset(system_affinity()):
raise ValueError("unknown cpus: %s" % affinity)
return system_affinity() | def process_affinity(affinity=None) | Get or set the CPU affinity set for the current process.
This will affect all future threads spawned by this process. It is
implementation-defined whether it will also affect previously-spawned
threads. | 5.341909 | 5.288791 | 1.010043 |
if timeout is None:
return self.__lock.acquire(blocking)
else:
# Simulated timeout using progressively longer sleeps.
# This is the same timeout scheme used in the stdlib Condition
# class. If there's lots of contention on the lock then there'... | def acquire(self,blocking=True,timeout=None) | Attempt to acquire this lock.
If the optional argument "blocking" is True and "timeout" is None,
this methods blocks until is successfully acquires the lock. If
"blocking" is False, it returns immediately if the lock could not
be acquired. Otherwise, it blocks for at most "timeout" se... | 5.324925 | 5.419541 | 0.982542 |
new_classes = []
for new_cls in cls.__mro__:
if new_cls not in thread.__class__.__mro__:
new_classes.append(new_cls)
if isinstance(thread,cls):
pass
elif issubclass(cls,thread.__class__):
thread.__class__ = cls
else:
... | def from_thread(cls,thread) | Convert a vanilla thread object into an instance of this class.
This method "upgrades" a vanilla thread object to an instance of this
extended class. You might need to call this if you obtain a reference
to a thread by some means other than (a) creating it, or (b) from the
methods of ... | 2.403466 | 2.384577 | 1.007921 |
with self._lock:
if shared:
self._acquire_shared(blocking,timeout)
else:
self._acquire_exclusive(blocking,timeout)
assert not (self.is_shared and self.is_exclusive) | def acquire(self,blocking=True,timeout=None,shared=False) | Acquire the lock in shared or exclusive mode. | 2.863129 | 2.736292 | 1.046354 |
# This decrements the appropriate lock counters, and if the lock
# becomes free, it looks for a queued thread to hand it off to.
# By doing the handoff here we ensure fairness.
me = currentThread()
with self._lock:
if self.is_exclusive:
if ... | def release(self) | Release the lock. | 2.926199 | 2.834651 | 1.032296 |
from .docxfile import DOCXFile
dfile = DOCXFile(file_name)
dfile.parse()
return dfile | def read_from_file(file_name) | Parser OOXML file and returns parsed document.
:Args:
- file_name (str): Path to OOXML file
:Returns:
Returns object of type :class:`ooxml.docx.DOCXFile`. | 6.920949 | 6.853803 | 1.009797 |
font_size = style.get_font_size()
if font_size == -1:
if style.based_on:
based_on = document.styles.get_by_id(style.based_on)
if based_on:
return _get_font_size(document, based_on)
return font_size | def _get_font_size(document, style) | Get font size defined for this style.
It will try to get font size from it's parent style if it is not defined by original style.
:Args:
- document (:class:`ooxml.doc.Document`): Document object
- style (:class:`ooxml.doc.Style`): Style object
:Returns:
Returns font size as a number. -... | 2.799126 | 2.808205 | 0.996767 |
try:
abs_num = document.numbering[numid]
return document.abstruct_numbering[abs_num][ilvl]['numFmt']
except:
return 'bullet' | def _get_numbering(document, numid, ilvl) | Returns type for the list.
:Returns:
Returns type for the list. Returns "bullet" by default or in case of an error. | 7.819151 | 7.348363 | 1.064067 |
elem = root
while True:
elem = elem.getparent()
if elem.tag in ['ul', 'ol']:
return elem | def _get_parent(root) | Returns root element for a list.
:Args:
root (Element): lxml element of current location
:Returns:
lxml element representing list | 5.144139 | 5.811415 | 0.885178 |
try:
n = len(ctx.in_list)
if n <= 0:
return root
elem = root
while n > 0:
while True:
if elem.tag in ['ul', 'ol', 'td']:
elem = elem.getparent()
break
elem = e... | def close_list(ctx, root) | Close already opened list if needed.
This will try to see if it is needed to close already opened list.
:Args:
- ctx (:class:`Context`): Context object
- root (Element): lxml element representing current position.
:Returns:
lxml element where future content should be placed. | 4.278613 | 3.877301 | 1.103503 |
_ls = None
if par.ilvl != ctx.ilvl or par.numid != ctx.numid:
# start
if ctx.ilvl is not None and (par.ilvl > ctx.ilvl):
fmt = _get_numbering(document, par.numid, par.ilvl)
if par.ilvl > 0:
# get last <li> in <ul>
# could be nicer
... | def open_list(ctx, document, par, root, elem) | Open list if it is needed and place current element as first member of a list.
:Args:
- ctx (:class:`Context`): Context object
- document (:class:`ooxml.doc.Document`): Document object
- par (:class:`ooxml.doc.Paragraph`): Paragraph element
- root (Element): lxml element of current location... | 2.678896 | 2.586424 | 1.035753 |
"Serialize break element."
if elem.break_type == u'textWrapping':
_div = etree.SubElement(root, 'br')
else:
_div = etree.SubElement(root, 'span')
if ctx.options['embed_styles']:
_div.set('style', 'page-break-after: always;')
fire_hooks(ctx, document, elem, _div, ctx... | def serialize_break(ctx, document, elem, root) | Serialize break element. | 5.676004 | 5.883484 | 0.964735 |
_div = etree.SubElement(root, 'span')
if ctx.options['embed_styles']:
_div.set('style', 'border: 1px solid red')
_div.text = 'We do not support Math blocks at the moment.'
fire_hooks(ctx, document, elem, _div, ctx.get_hook('math'))
return root | def serialize_math(ctx, document, elem, root) | Serialize math element.
Math objects are not supported at the moment. This is wht we only show error message. | 6.966039 | 5.758382 | 1.209722 |
_a = etree.SubElement(root, 'a')
for el in elem.elements:
_ser = ctx.get_serializer(el)
if _ser:
_td = _ser(ctx, document, el, _a)
else:
if isinstance(el, doc.Text):
children = list(_a)
if len(children) == 0:
... | def serialize_link(ctx, document, elem, root) | Serilaze link element.
This works only for external links at the moment. | 3.800437 | 3.826188 | 0.99327 |
_img = etree.SubElement(root, 'img')
# make path configurable
if elem.rid in document.relationships[ctx.options['relationship']]:
img_src = document.relationships[ctx.options['relationship']][elem.rid].get('target', '')
img_name, img_extension = os.path.splitext(img_src)
_img... | def serialize_image(ctx, document, elem, root) | Serialize image element.
This is not abstract enough. | 5.405733 | 5.459208 | 0.990205 |
if not hooks:
return
for hook in hooks:
hook(ctx, document, elem, element) | def fire_hooks(ctx, document, elem, element, hooks) | Fire hooks on newly created element.
For each newly created element we will try to find defined hooks and execute them.
:Args:
- ctx (:class:`Context`): Context object
- document (:class:`ooxml.doc.Document`): Document object
- elem (:class:`ooxml.doc.Element`): Element which we serialized
... | 3.025969 | 3.77303 | 0.802 |
def has_style(node):
elements = ['b', 'i', 'u', 'strike', 'color', 'jc', 'sz', 'ind', 'superscript', 'subscript', 'small_caps']
return any([True for elem in elements if elem in node.rpr]) | Tells us if node element has defined styling.
:Args:
- node (:class:`ooxml.doc.Element`): Element
:Returns:
True or False | null | null | null | |
style = []
if not node:
return
if fontsize in [-1, 2]:
if 'sz' in node.rpr:
size = int(node.rpr['sz']) / 2
if ctx.options['embed_fontsize']:
if ctx.options['scale_to_size']:
multiplier = size-ctx.options['sc... | def get_style_css(ctx, node, embed=True, fontsize=-1) | Returns as string defined CSS for this node.
Defined CSS can be different if it is embeded or no. When it is embeded styling
for bold,italic and underline will not be defined with CSS. In that case we
use defined tags <b>,<i>,<u> from the content.
:Args:
- ctx (:class:`Context`): Context object... | 2.243652 | 2.24071 | 1.001313 |
classes = []
while True:
classes.insert(0, get_style_name(style))
if style.based_on:
style = document.styles.get_by_id(style.based_on)
else:
break
return classes | def get_all_styles(document, style) | Returns list of styles on which specified style is based on.
:Args:
- document (:class:`ooxml.doc.Document`): Document object
- style (:class:`ooxml.doc.Style`): Style object
:Returns:
List of style objects. | 3.524284 | 3.890112 | 0.905959 |
lst = [st.lower() for st in get_all_styles(document, style)[-1:]] + \
['{}-fontsize'.format(st.lower()) for st in get_all_styles(document, style)[-1:]]
return ' '.join(lst) | def get_css_classes(document, style) | Returns CSS classes for this style.
This function will check all the styles specified style is based on and return their CSS classes.
:Args:
- document (:class:`ooxml.doc.Document`): Document object
- style (:class:`ooxml.doc.Style`): Style object
:Returns:
String representing all the C... | 4.71763 | 6.534448 | 0.721963 |
"Serialize special symbols."
span = etree.SubElement(root, 'span')
span.text = el.value()
fire_hooks(ctx, document, el, span, ctx.get_hook('symbol'))
return root | def serialize_symbol(ctx, document, el, root) | Serialize special symbols. | 10.19028 | 8.81127 | 1.156505 |
"Serializes footnotes."
footnote_num = el.rid
if el.rid not in ctx.footnote_list:
ctx.footnote_id += 1
ctx.footnote_list[el.rid] = ctx.footnote_id
footnote_num = ctx.footnote_list[el.rid]
note = etree.SubElement(root, 'sup')
link = etree.SubElement(note, 'a')
link.set('hr... | def serialize_footnote(ctx, document, el, root) | Serializes footnotes. | 3.904044 | 3.896258 | 1.001998 |
"Serializes comment."
# Check if option is turned on
if el.comment_type == 'end':
ctx.opened_comments.remove(el.cid)
else:
if el.comment_type != 'reference':
ctx.opened_comments.append(el.cid)
if ctx.options['comment_span']:
link = etree.SubElement(root... | def serialize_comment(ctx, document, el, root) | Serializes comment. | 5.497252 | 5.364255 | 1.024793 |
"Serializes endnotes."
footnote_num = el.rid
if el.rid not in ctx.endnote_list:
ctx.endnote_id += 1
ctx.endnote_list[el.rid] = ctx.endnote_id
footnote_num = ctx.endnote_list[el.rid]
note = etree.SubElement(root, 'sup')
link = etree.SubElement(note, 'a')
link.set('href', '... | def serialize_endnote(ctx, document, el, root) | Serializes endnotes. | 3.956154 | 3.932122 | 1.006112 |
"Serializes smarttag."
if ctx.options['smarttag_span']:
_span = etree.SubElement(root, 'span', {'class': 'smarttag', 'data-smarttag-element': el.element})
else:
_span = root
for elem in el.elements:
_ser = ctx.get_serializer(elem)
if _ser:
_td = _ser(ctx, d... | def serialize_smarttag(ctx, document, el, root) | Serializes smarttag. | 3.626668 | 3.587093 | 1.011033 |
# What we should check really is why do we pass None as root element
# There is a good chance some content is missing after the import
if root is None:
return root
if ctx.ilvl != None:
root = close_list(ctx, root)
ctx.ilvl, ctx.numid = None, None
_table = etree.SubEl... | def serialize_table(ctx, document, table, root) | Serializes table element. | 3.413084 | 3.437698 | 0.99284 |
_div = etree.SubElement(root, 'div')
_div.set('class', 'textbox')
for elem in txtbox.elements:
_ser = ctx.get_serializer(elem)
if _ser:
_ser(ctx, document, elem, _div)
fire_hooks(ctx, document, txtbox, _div, ctx.get_hook('textbox'))
return root | def serialize_textbox(ctx, document, txtbox, root) | Serialize textbox element. | 4.098365 | 4.100156 | 0.999563 |
ctx = Context(document, options)
tree_root = root = etree.Element('div')
for elem in elements:
_ser = ctx.get_serializer(elem)
if _ser:
root = _ser(ctx, document, elem, root)
# TODO:
# - create footnotes now
return etree.tostring(tree_root, pretty_print=... | def serialize_elements(document, elements, options=None) | Serialize list of elements into HTML string.
:Args:
- document (:class:`ooxml.doc.Document`): Document object
- elements (list): List of elements
- options (dict): Optional dictionary with :class:`Context` options
:Returns:
Returns HTML representation of the document. | 4.77816 | 5.190995 | 0.920471 |
# This logic has been disabled for now. Mark this as header if it has
# been marked during the parsing or mark.
# if hasattr(elem, 'possible_header'):
# if elem.possible_header:
# return True
# if not style:
# ret... | def is_header(self, elem, font_size, node, style=None) | Used for checking if specific element is a header or not.
:Returns:
True or False | 4.061992 | 4.097786 | 0.991265 |
font_size = style
if hasattr(elem, 'possible_header'):
if elem.possible_header:
return 'h1'
if not style:
return 'h6'
if hasattr(style, 'style_id'):
font_size = _get_font_size(self.doc, style)
try:
if fon... | def get_header(self, elem, style, node) | Returns HTML tag representing specific header for this element.
:Returns:
String representation of HTML tag. | 3.452183 | 3.558165 | 0.970214 |
return self.options['serializers'].get(type(node), None)
if type(node) in self.options['serializers']:
return self.options['serializers'][type(node)]
return None | def get_serializer(self, node) | Returns serializer for specific element.
:Args:
- node (:class:`ooxml.doc.Element`): Element object
:Returns:
Returns reference to a function which will be used for serialization. | 3.704628 | 3.693348 | 1.003054 |
with self.__lock:
old_priorities = {}
try:
for thread in self.__threads:
old_priorities[thread] = thread.priority
thread.priority = priority
except Exception:
for (thread,old_priority) in old_pri... | def priority(self,priority) | Set the priority for all threads in this group.
If setting priority fails on any thread, the priority of all threads
is restored to its previous value. | 2.76681 | 2.402207 | 1.151778 |
with self.__lock:
old_affinities = {}
try:
for thread in self.__threads:
old_affinities[thread] = thread.affinity
thread.affinity = affinity
except Exception:
for (thread,old_affinity) in old_aff... | def affinity(self,affinity) | Set the affinity for all threads in this group.
If setting affinity fails on any thread, the affinity of all threads
is restored to its previous value. | 2.58849 | 2.27416 | 1.138218 |
if timeout is None:
for thread in self.__threads:
thread.join()
else:
deadline = _time() + timeout
for thread in self.__threads:
delay = deadline - _time()
if delay <= 0:
return False
... | def join(self,timeout=None) | Join all threads in this group.
If the optional "timeout" argument is given, give up after that many
seconds. This method returns True is the threads were successfully
joined, False if a timeout occurred. | 2.518813 | 2.258175 | 1.11542 |
if not elem:
return 0
value = elem.value()
try:
value = len(value)
except:
value = 0
try:
for a in elem.elements:
value += len(a.value())
except:
pass
return value | def text_length(elem) | Returns length of the content in this element.
Return value is not correct but it is **good enough***. | 3.933686 | 3.682292 | 1.068271 |
not_using_styles = False
if ctx.options['not_using_styles']:
if len(doc.used_styles) < ctx.options['minimum_used_styles'] and len(doc.possible_headers) < ctx.options['minimum_possible_headers']:
not_using_styles = True
doc.possible_headers = [POSSIBLE_HEADER_SIZE] + doc.po... | def mark_styles(ctx, doc, elements) | Checks all elements and creates a list of diferent markers for styles or different elements. | 3.168789 | 3.145857 | 1.00729 |
"Resets the values."
self.zf = zipfile.ZipFile(self.file_name, 'r')
self._doc = None | def reset(self) | Resets the values. | 12.204542 | 9.907393 | 1.231862 |
if policy is None:
policy = libc.sched_getscheduler(0)
if policy < 0:
raise OSError(get_errno(),"sched_getscheduler")
max = libc.sched_get_priority_max(policy)
if max < 0:
raise OSError(get_errno(),"sched_get_priority_max")
min = libc.sched_get_priority_min(polic... | def _priority_range(policy=None) | Determine the priority range (min,max) for the given scheduler policy.
If no policy is specified, the current default policy is used. | 1.983278 | 1.922762 | 1.031474 |
try:
attr = getattr(self, attname)
except AttributeError:
return default
if callable(attr):
# Check co_argcount rather than try/excepting the function and
# catching the TypeError, because something inside the function
# may ra... | def _get_dynamic_attr(self, attname, obj, default=None) | Copied from django.contrib.syndication.views.Feed (v1.7.1) | 4.010321 | 3.847145 | 1.042415 |
result = {}
if count is not None:
result['COUNT'] = count
if interval is not None:
result['INTERVAL'] = interval
if bysecond is not None:
result['BYSECOND'] = bysecond
if byminute is not None:
result['BYMINUTE'] = byminute
if byhour is not None:
... | def build_rrule(count=None, interval=None, bysecond=None, byminute=None,
byhour=None, byweekno=None, bymonthday=None, byyearday=None,
bymonth=None, until=None, bysetpos=None, wkst=None, byday=None,
freq=None) | Build rrule dictionary for vRecur class.
:param count: int
:param interval: int
:param bysecond: int
:param byminute: int
:param byhour: int
:param byweekno: int
:param bymonthday: int
:param byyearday: int
:param bymonth: int
:param until: datetime
:param bysetpos: int
... | 1.332898 | 1.332346 | 1.000414 |
from recurrence import serialize
line = serialize(rule)
if line.startswith('RRULE:'):
line = line[6:]
return build_rrule_from_text(line) | def build_rrule_from_recurrences_rrule(rule) | Build rrule dictionary for vRecur class from a django_recurrences rrule.
django_recurrences is a popular implementation for recurrences in django.
https://pypi.org/project/django-recurrence/
this is a shortcut to interface between recurrences and icalendar. | 5.170062 | 4.975122 | 1.039183 |
lines = str(rule).splitlines()
for line in lines:
if line.startswith('DTSTART:'):
continue
if line.startswith('RRULE:'):
line = line[6:]
return build_rrule_from_text(line) | def build_rrule_from_dateutil_rrule(rule) | Build rrule dictionary for vRecur class from a dateutil rrule.
Dateutils rrule is a popular implementation of rrule in python.
https://pypi.org/project/python-dateutil/
this is a shortcut to interface between dateutil and icalendar. | 3.394116 | 3.427954 | 0.990129 |
u
cal = Calendar()
cal.add('version', '2.0')
cal.add('calscale', 'GREGORIAN')
for ifield, efield in FEED_FIELD_MAP:
val = self.feed.get(ifield)
if val is not None:
cal.add(efield, val)
self.write_items(cal)
to_ical = geta... | def write(self, outfile, encoding) | u"""
Writes the feed to the specified file in the
specified encoding. | 4.060952 | 4.195754 | 0.967872 |
for item in self.items:
event = Event()
for ifield, efield in ITEM_EVENT_FIELD_MAP:
val = item.get(ifield)
if val is not None:
event.add(efield, val)
calendar.add_component(event) | def write_items(self, calendar) | Write all events to the calendar | 4.113024 | 3.928617 | 1.04694 |
'''Returns a list of text strings contained within an element and its sub-elements.
Helpful for extracting text from prose-oriented XML (such as XHTML or DocBook).
'''
result = []
if (not _addtail) and (self.text is not None):
result.append(self.text)
for elem in self:
result.ex... | def _textlist(self, _addtail=False) | Returns a list of text strings contained within an element and its sub-elements.
Helpful for extracting text from prose-oriented XML (such as XHTML or DocBook). | 4.035342 | 1.939807 | 2.08028 |
s = textwrap.dedent(s)
s = s.split('\n')
s = [x.rstrip() for x in s]
while s and (not s[0]):
s = s[1:]
while s and (not s[-1]):
s = s[:-1]
if reformat:
s = '\n'.join(s)
s = textwrap.wrap(s, initial_indent=indent, subsequent_indent=indent)
else:
s ... | def _reindent(s, indent, reformat=True) | Remove the existing indentation from each line of a chunk of
text, s, and then prefix each line with a new indent string.
Also removes trailing whitespace from each line, and leading and
trailing blank lines. | 1.848353 | 1.978554 | 0.934194 |
result = []
txt = element.text and element.text.rstrip()
if txt:
result.append(_reindent(txt, indent))
result.append(indent)
for d in element.findall('doc') + element.findall('rule'):
docval = ''.join(d.textlist()).rstrip()
if not docval:
continue
... | def generate_docstr(element, indent='', wrap=None) | Generate a Python docstr for a given element in the AMQP
XML spec file. The element could be a class or method
The 'wrap' parameter is an optional chunk of text that's
added to the beginning and end of the resulting docstring. | 2.943978 | 2.933022 | 1.003735 |
#
# HACK THE SPEC so that 'access' is handled by 'channel' instead of 'connection'
#
for amqp_class in spec.findall('class'):
if amqp_class.attrib['name'] == 'access':
amqp_class.attrib['handler'] = 'channel'
#
# Build up some helper dictionaries
#
for domain in... | def generate_module(spec, out) | Given an AMQP spec parsed into an xml.etree.ElemenTree,
and a file-like 'out' object to write to, generate
the skeleton of a Python module. | 2.283005 | 2.218201 | 1.029214 |
while self.queue.empty():
try:
frame_type, channel, payload = self.source.read_frame()
except Exception, e:
#
# Connection was closed? Framing Error?
#
self.queue.put(e)
break
... | def _next_method(self) | Read the next method from the source, once one complete method has
been assembled it is placed in the internal queue. | 3.66667 | 3.504749 | 1.046201 |
method_sig = unpack('>HH', payload[:4])
args = AMQPReader(payload[4:])
if method_sig in _CONTENT_METHODS:
#
# Save what we've got so far and wait for the content-header
#
self.partial_messages[channel] = _PartialMessage(method_sig, args)
... | def _process_method_frame(self, channel, payload) | Process Method frames | 6.407777 | 6.238024 | 1.027213 |
partial = self.partial_messages[channel]
partial.add_header(payload)
if partial.complete:
#
# a bodyless message, we're done
#
self.queue.put((channel, partial.method_sig, partial.args, partial.msg))
del self.partial_messages[... | def _process_content_header(self, channel, payload) | Process Content Header frames | 5.501374 | 5.282055 | 1.041522 |
partial = self.partial_messages[channel]
partial.add_payload(payload)
if partial.complete:
#
# Stick the message in the queue and go back to
# waiting for method frames
#
self.queue.put((channel, partial.method_sig, partial.arg... | def _process_content_body(self, channel, payload) | Process Content Body frames | 6.897807 | 6.097804 | 1.131195 |
self._next_method()
m = self.queue.get()
if isinstance(m, Exception):
raise m
return m | def read_method(self) | Read a method from the peer. | 6.599878 | 5.673634 | 1.163254 |
AMQP_LOGGER.debug('Closed channel #%d' % self.channel_id)
self.is_open = False
del self.connection.channels[self.channel_id]
self.channel_id = self.connection = None
self.callbacks = {} | def _do_close(self) | Tear down this object, after we've agreed to close with the server. | 4.311017 | 4.100081 | 1.051447 |
reply_code = args.read_short()
reply_text = args.read_shortstr()
details = args.read_table()
self.alerts.put((reply_code, reply_text, details)) | def _alert(self, args) | This method allows the server to send a non-fatal warning to
the client. This is used for methods that are normally
asynchronous and thus do not have confirmations, and for which
the server may detect errors that need to be reported. Fatal
errors are handled as channel or connection ex... | 5.343154 | 3.787627 | 1.410686 |
if not self.is_open:
# already closed
return
args = AMQPWriter()
args.write_short(reply_code)
args.write_shortstr(reply_text)
args.write_short(method_sig[0]) # class_id
args.write_short(method_sig[1]) # method_id
self._send_method... | def close(self, reply_code=0, reply_text='', method_sig=(0, 0)) | request a channel close
This method indicates that the sender wants to close the
channel. This may be due to internal conditions (e.g. a forced
shut-down) or due to an error handling a specific method, i.e.
an exception. When a close is due to an exception, the sender
provides ... | 3.498502 | 3.582238 | 0.976625 |
reply_code = args.read_short()
reply_text = args.read_shortstr()
class_id = args.read_short()
method_id = args.read_short()
# self.close_ok()
# def close_ok(self):
#
self._send_method((20, 41))
self._do_close()
raise AMQPChannelExcep... | def _close(self, args) | request a channel close
This method indicates that the sender wants to close the
channel. This may be due to internal conditions (e.g. a forced
shut-down) or due to an error handling a specific method, i.e.
an exception. When a close is due to an exception, the sender
provides ... | 4.67228 | 4.111672 | 1.136345 |
args = AMQPWriter()
args.write_shortstr(realm)
args.write_bit(exclusive)
args.write_bit(passive)
args.write_bit(active)
args.write_bit(write)
args.write_bit(read)
self._send_method((30, 10), args)
return self.wait(allowed_methods=[
... | def access_request(self, realm, exclusive=False,
passive=False, active=False, write=False, read=False) | request an access ticket
This method requests an access ticket for an access realm. The
server responds by granting the access ticket. If the client
does not have access rights to the requested realm this causes
a connection exception. Access tickets are a per-channel
resource... | 3.212229 | 3.874726 | 0.829021 |
args = AMQPWriter()
if ticket is not None:
args.write_short(ticket)
else:
args.write_short(self.default_ticket)
args.write_shortstr(exchange)
args.write_bit(if_unused)
args.write_bit(nowait)
self._send_method((40, 20), args)
... | def exchange_delete(self, exchange, if_unused=False,
nowait=False, ticket=None) | delete an exchange
This method deletes an exchange. When an exchange is deleted
all queue bindings on the exchange are cancelled.
PARAMETERS:
exchange: shortstr
RULE:
The exchange MUST exist. Attempting to delete a
non-exis... | 3.033401 | 3.541289 | 0.856581 |
if arguments is None:
arguments = {}
args = AMQPWriter()
if ticket is not None:
args.write_short(ticket)
else:
args.write_short(self.default_ticket)
args.write_shortstr(queue)
args.write_shortstr(exchange)
args.write_s... | def queue_bind(self, queue, exchange, routing_key='',
nowait=False, arguments=None, ticket=None) | bind queue to an exchange
This method binds a queue to an exchange. Until a queue is
bound it will not receive any messages. In a classic
messaging model, store-and-forward queues are bound to a dest
exchange and subscription queues are bound to a dest_wild
exchange.
... | 2.508748 | 2.83963 | 0.883477 |
queue = args.read_shortstr()
message_count = args.read_long()
consumer_count = args.read_long()
return queue, message_count, consumer_count | def _queue_declare_ok(self, args) | confirms a queue definition
This method confirms a Declare method and confirms the name of
the queue, essential for automatically-named queues.
PARAMETERS:
queue: shortstr
Reports the name of the queue. If the server generated
a queue name, this fie... | 2.899977 | 3.682809 | 0.787436 |
args = AMQPWriter()
if ticket is not None:
args.write_short(ticket)
else:
args.write_short(self.default_ticket)
args.write_shortstr(queue)
args.write_shortstr(consumer_tag)
args.write_bit(no_local)
args.write_bit(no_ack)
ar... | def basic_consume(self, queue='', consumer_tag='', no_local=False,
no_ack=False, exclusive=False, nowait=False,
callback=None, ticket=None) | start a queue consumer
This method asks the server to start a "consumer", which is a
transient request for messages from a specific queue.
Consumers last as long as the channel they were created on, or
until the client cancels them.
RULE:
The server SHOULD support ... | 2.515551 | 2.882194 | 0.87279 |
consumer_tag = args.read_shortstr()
delivery_tag = args.read_longlong()
redelivered = args.read_bit()
exchange = args.read_shortstr()
routing_key = args.read_shortstr()
msg.delivery_info = {
'channel': self,
'consumer_tag': consumer_tag,
... | def _basic_deliver(self, args, msg) | notify the client of a consumer message
This method delivers a message to the client, via a consumer.
In the asynchronous message delivery model, the client starts
a consumer using the Consume method, then the server responds
with Deliver methods as and when messages arrive for that
... | 1.803226 | 2.023586 | 0.891104 |
args = AMQPWriter()
if ticket is not None:
args.write_short(ticket)
else:
args.write_short(self.default_ticket)
args.write_shortstr(queue)
args.write_bit(no_ack)
self._send_method((60, 70), args)
return self.wait(allowed_methods=[
... | def basic_get(self, queue='', no_ack=False, ticket=None) | direct access to a queue
This method provides a direct access to the messages in a
queue using a synchronous dialogue that is designed for
specific types of application where synchronous functionality
is more important than performance.
PARAMETERS:
queue: shortstr
... | 3.296292 | 3.860878 | 0.853767 |
args = AMQPWriter()
if ticket is not None:
args.write_short(ticket)
else:
args.write_short(self.default_ticket)
args.write_shortstr(exchange)
args.write_shortstr(routing_key)
args.write_bit(mandatory)
args.write_bit(immediate)
... | def basic_publish(self, msg, exchange='', routing_key='',
mandatory=False, immediate=False, ticket=None) | publish a message
This method publishes a message to a specific exchange. The
message will be routed to queues as defined by the exchange
configuration and distributed to any active consumers when the
transaction, if any, is committed.
PARAMETERS:
exchange: shortstr... | 2.627144 | 3.354253 | 0.783228 |
reply_code = args.read_short()
reply_text = args.read_shortstr()
exchange = args.read_shortstr()
routing_key = args.read_shortstr()
self.returned_messages.put(
(reply_code, reply_text, exchange, routing_key, msg)
) | def _basic_return(self, args, msg) | return a failed message
This method returns an undeliverable message that was
published with the "immediate" flag set, or an unroutable
message published with the "mandatory" flag set. The reply
code and text provide information about the reason that the
message was undeliverabl... | 3.263163 | 3.066049 | 1.064289 |
#
# Check the channel's deferred methods
#
method_queue = self.channels[channel_id].method_queue
for queued_method in method_queue:
method_sig = queued_method[0]
if (allowed_methods is None) \
or (method_sig in allowed_methods) \
... | def _wait_method(self, channel_id, allowed_methods) | Wait for a method from the server destined for
a particular channel. | 3.71828 | 3.743727 | 0.993203 |
if channel_id in self.channels:
return self.channels[channel_id]
return Channel(self, channel_id) | def channel(self, channel_id=None) | Fetch a Channel object identified by the numeric channel_id, or
create that object if it doesn't already exist. | 3.04448 | 3.047786 | 0.998915 |
reply_code = args.read_short()
reply_text = args.read_shortstr()
class_id = args.read_short()
method_id = args.read_short()
self._x_close_ok()
raise AMQPConnectionException(reply_code, reply_text, (class_id, method_id)) | def _close(self, args) | request a connection close
This method indicates that the sender wants to close the
connection. This may be due to internal conditions (e.g. a
forced shut-down) or due to an error handling a specific
method, i.e. an exception. When a close is due to an
exception, the sender pro... | 4.159136 | 3.480223 | 1.195077 |
args = AMQPWriter()
args.write_shortstr(virtual_host)
args.write_shortstr(capabilities)
args.write_bit(insist)
self._send_method((10, 40), args)
return self.wait(allowed_methods=[
(10, 41), # Connection.open_ok
... | def _x_open(self, virtual_host, capabilities='', insist=False) | open connection to virtual host
This method opens a connection to a virtual host, which is a
collection of resources, and acts to separate multiple
application domains within a server.
RULE:
The client MUST open the context before doing any work on
the connecti... | 3.769959 | 4.551548 | 0.828281 |
self.known_hosts = args.read_shortstr()
AMQP_LOGGER.debug('Open OK! known_hosts [%s]' % self.known_hosts)
return None | def _open_ok(self, args) | signal that the connection is ready
This method signals to the client that the connection is ready
for use.
PARAMETERS:
known_hosts: shortstr | 13.128247 | 10.03817 | 1.307833 |
host = args.read_shortstr()
self.known_hosts = args.read_shortstr()
AMQP_LOGGER.debug('Redirected to [%s], known_hosts [%s]' % (host, self.known_hosts))
return host | def _redirect(self, args) | asks the client to use a different server
This method redirects the client to another server, based on
the requested virtual host and/or capabilities.
RULE:
When getting the Connection.Redirect method, the client
SHOULD reconnect to the host specified, and if that host... | 7.623519 | 6.093311 | 1.251129 |
self.version_major = args.read_octet()
self.version_minor = args.read_octet()
self.server_properties = args.read_table()
self.mechanisms = args.read_longstr().split(' ')
self.locales = args.read_longstr().split(' ')
AMQP_LOGGER.debug('Start from server, version:... | def _start(self, args) | start connection negotiation
This method starts the connection negotiation process by
telling the client the protocol version that the server
proposes, along with a list of security mechanisms which the
client can use for authentication.
RULE:
If the client cannot ... | 3.270674 | 2.261049 | 1.446529 |
args = AMQPWriter()
args.write_table(client_properties)
args.write_shortstr(mechanism)
args.write_longstr(response)
args.write_shortstr(locale)
self._send_method((10, 11), args) | def _x_start_ok(self, client_properties, mechanism, response, locale) | select security mechanism and locale
This method selects a SASL security mechanism. ASL uses SASL
(RFC2222) to negotiate authentication and encryption.
PARAMETERS:
client_properties: table
client properties
mechanism: shortstr
selected... | 3.365116 | 3.277719 | 1.026664 |
self.channel_max = args.read_short() or self.channel_max
self.frame_max = args.read_long() or self.frame_max
self.method_writer.frame_max = self.frame_max
self.heartbeat = args.read_short()
self._x_tune_ok(self.channel_max, self.frame_max, 0) | def _tune(self, args) | propose connection tuning parameters
This method proposes a set of connection configuration values
to the client. The client can accept and/or adjust these.
PARAMETERS:
channel_max: short
proposed maximum channels
The maximum total number of chann... | 6.041462 | 4.229765 | 1.428321 |
if isinstance(args, AMQPWriter):
args = args.getvalue()
self.connection.method_writer.write_method(self.channel_id,
method_sig, args, content) | def _send_method(self, method_sig, args=bytes(), content=None) | Send a method for our channel. | 5.352236 | 4.873927 | 1.098136 |
frame_type, channel, size = unpack('>BHI', self._read(7))
payload = self._read(size)
ch = ord(self._read(1))
if ch == 206: # '\xce'
return frame_type, channel, payload
else:
raise Exception('Framing Error, received 0x%02x while expecting 0xce' % c... | def read_frame(self) | Read an AMQP frame. | 5.350781 | 4.797622 | 1.115299 |
size = len(payload)
self._write(pack('>BHI%dsB' % size,
frame_type, channel, size, payload, 0xce)) | def write_frame(self, frame_type, channel, payload) | Write out an AMQP frame. | 5.511827 | 5.349504 | 1.030344 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.