Unnamed: 0
int64 0
10k
| function
stringlengths 79
138k
| label
stringclasses 20
values | info
stringlengths 42
261
|
---|---|---|---|
4,700 | def select(self, node):
try:
return self.dict[node.scanner_key()]
except __HOLE__:
return None | KeyError | dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Scanner/__init__.py/Selector.select |
4,701 | def __del__(self):
"Destroys this DataStructure object."
try:
capi.destroy_ds(self._ptr)
except (AttributeError, __HOLE__):
pass # Some part might already have been garbage collected | TypeError | dataset/ETHPy150Open django/django/django/contrib/gis/gdal/datasource.py/DataSource.__del__ |
4,702 | @login_required
@permission_required("relaydomains.add_service")
@require_http_methods(["POST"])
def scan_for_services(request):
try:
Service.objects.load_from_master_cf()
except __HOLE__ as e:
return render_to_json_response([str(e)], status=500)
return render_to_json_response(
dict((srv.name, srv.id) for srv in Service.objects.all())
) | IOError | dataset/ETHPy150Open tonioo/modoboa/modoboa/relaydomains/views.py/scan_for_services |
4,703 | def _LoadModuleCode(filename):
"""Loads the code of a module, using compiled bytecode if available.
Args:
filename: The Python script filename.
Returns:
A 2-tuple (code, filename) where:
code: A code object contained in the file or None if it does not exist.
filename: The name of the file loaded, either the same as the arg
filename, or the corresponding .pyc file.
"""
compiled_filename = filename + 'c'
if os.path.exists(compiled_filename):
with open(compiled_filename, 'r') as f:
magic_numbers = f.read(8)
if len(magic_numbers) == 8 and magic_numbers[:4] == imp.get_magic():
try:
return _FixCodeFilename(marshal.load(f), filename), compiled_filename
except (EOFError, __HOLE__):
pass
if os.path.exists(filename):
with open(filename, 'r') as f:
code = compile(f.read(), filename, 'exec', 0, True)
return code, filename
else:
return None, filename | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/runtime/cgi.py/_LoadModuleCode |
4,704 | def _GetModuleOrNone(module_name):
"""Returns a module if it exists or None."""
module = None
if module_name:
try:
module = __import__(module_name)
except __HOLE__:
pass
else:
for name in module_name.split('.')[1:]:
module = getattr(module, name)
return module | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/runtime/cgi.py/_GetModuleOrNone |
4,705 | def show(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
if '.' in id:
before_date = datetime.datetime.strptime(str(id),
"%Y-%m-%d %H:%M:%S.%f")
else:
before_date = datetime.datetime.strptime(str(id),
"%Y-%m-%d %H:%M:%S")
except __HOLE__:
msg = _("Invalid timestamp for date %s") % id
raise webob.exc.HTTPBadRequest(explanation=msg)
task_log = self._get_audit_task_logs(context,
before=before_date)
return {'instance_usage_audit_log': task_log} | ValueError | dataset/ETHPy150Open openstack/nova/nova/api/openstack/compute/legacy_v2/contrib/instance_usage_audit_log.py/InstanceUsageAuditLogController.show |
4,706 | def revert(self):
for k,v in self._original_settings.iteritems():
if v == NO_SETTING:
try:
delattr(self._settings, k)
except __HOLE__:
# Django < r11825
delattr(self._settings._wrapped, k)
else:
setattr(self._settings, k, v)
self._original_settings = {} | AttributeError | dataset/ETHPy150Open carljm/django-localeurl/localeurl/tests/test_utils.py/TestSettingsManager.revert |
4,707 | def __init__(self, template_string, name='<Unknown Template>',
libraries=[]):
try:
template_string = encoding.smart_unicode(template_string)
except __HOLE__:
raise template.TemplateEncodingError(
"template content must be unicode or UTF-8 string")
origin = template.StringOrigin(template_string)
self.nodelist = self.my_compile_string(template_string, origin,
libraries)
self.name = name | UnicodeDecodeError | dataset/ETHPy150Open carljm/django-localeurl/localeurl/tests/test_utils.py/TestTemplate.__init__ |
4,708 | def processOne(self, deferred):
if self.stopping:
deferred.callback(self.root)
return
try:
self.remaining=self.iterator.next()
except __HOLE__:
self.stopping=1
except:
deferred.errback(failure.Failure())
if self.remaining%10==0:
reactor.callLater(0, self.updateBar, deferred)
if self.remaining%100==0:
log.msg(self.remaining)
reactor.callLater(0, self.processOne, deferred) | StopIteration | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/scripts/tkunzip.py/Progressor.processOne |
4,709 | def validate(self, values, model_instance):
try:
iter(values)
except __HOLE__:
raise ValidationError("Value of type %r is not iterable." %
type(values)) | TypeError | dataset/ETHPy150Open django-nonrel/djangotoolbox/djangotoolbox/fields.py/AbstractIterableField.validate |
4,710 | def fixdir(lst):
try:
lst.remove('__builtins__')
except __HOLE__:
pass
return lst
# Helper to run a test | ValueError | dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test_pkg.py/fixdir |
4,711 | def runtest(hier, code):
root = tempfile.mkdtemp()
mkhier(root, hier)
savepath = sys.path[:]
fd, fname = tempfile.mkstemp(text=True)
os.write(fd, code)
os.close(fd)
try:
sys.path.insert(0, root)
if verbose: print "sys.path =", sys.path
try:
execfile(fname, globals(), {})
except:
traceback.print_exc(file=sys.stdout)
finally:
sys.path[:] = savepath
os.unlink(fname)
try:
cleanout(root)
except (os.error, __HOLE__):
pass
# Test descriptions | IOError | dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test_pkg.py/runtest |
4,712 | @cached_property
def supports_stddev(self):
"Confirm support for STDDEV and related stats functions"
class StdDevPop(object):
sql_function = 'STDDEV_POP'
try:
self.connection.ops.check_aggregate_support(StdDevPop())
return True
except __HOLE__:
return False | NotImplementedError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/backends/__init__.py/BaseDatabaseFeatures.supports_stddev |
4,713 | def get_function_attributes(func):
'''
Extract the function attributes from a Python function or object with
*py_func* attribute, such as CPUDispatcher.
Returns an instance of FunctionAttributes.
'''
if hasattr(func, 'py_func'):
func = func.py_func # This is a Overload object
name, filename, lineno = DEFAULT_FUNCTION_ATTRIBUTES
try:
name = func.__name__
except AttributeError:
pass # this "function" object isn't really a function
try:
possible_filename = inspect.getsourcefile(func)
# Sometimes getsourcefile returns null
if possible_filename is not None:
filename = possible_filename
except __HOLE__:
pass # built-in function, or other object unsupported by inspect
try:
lines, lineno = inspect.getsourcelines(func)
except (IOError, TypeError):
pass # unable to read source code for function
return FunctionAttributes(name, filename, lineno) | TypeError | dataset/ETHPy150Open numba/numba/numba/compiler.py/get_function_attributes |
4,714 | def _convert_to_integer(self, name, value):
try:
return int(value)
except __HOLE__:
LOGGER.error("Option '--%s' expected integer value but got '%s'. "
"Default value used instead." % (name.lower(), value))
return self._get_default_value(name) | ValueError | dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/conf/settings.py/_BaseSettings._convert_to_integer |
4,715 | def style_language(self, style):
"""Return language corresponding to this style."""
try:
return style.language
except AttributeError:
pass
try:
return self.styles['bodytext'].language
except __HOLE__:
# FIXME: this is pretty arbitrary, and will
# probably not do what you want.
# however, it should only happen if:
# * You specified the language of a style
# * Have no wordaxe installed.
# Since it only affects hyphenation, and wordaxe is
# not installed, t should have no effect whatsoever
return os.environ['LANG'] or 'en' | AttributeError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/createpdf.py/RstToPdf.style_language |
4,716 | def text_for_label(self, label, style):
"""Translate text for label."""
try:
text = self.docutils_languages[
self.style_language(style)].labels[label]
except __HOLE__:
text = label.capitalize()
return text | KeyError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/createpdf.py/RstToPdf.text_for_label |
4,717 | def text_for_bib_field(self, field, style):
"""Translate text for bibliographic fields."""
try:
text = self.docutils_languages[
self.style_language(style)].bibliographic_fields[field]
except __HOLE__:
text = field
return text + ":" | KeyError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/createpdf.py/RstToPdf.text_for_bib_field |
4,718 | def author_separator(self, style):
"""Return separator string for authors."""
try:
sep = self.docutils_languages[
self.style_language(style)].author_separators[0]
except __HOLE__:
sep = ';'
return sep + " " | KeyError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/createpdf.py/RstToPdf.author_separator |
4,719 | def styleToTags(self, style):
'''Takes a style name, returns a pair of opening/closing tags for it, like
"<font face=helvetica size=14 color=red>". Used for inline
nodes (custom interpreted roles)'''
try:
s = self.styles[style]
r1=['<font face="%s" color="#%s" ' %
(s.fontName, s.textColor.hexval()[2:])]
bc = s.backColor
if bc:
r1.append('backColor="#%s"' % bc.hexval()[2:])
if s.trueFontSize:
r1.append('size="%d"'%s.fontSize)
r1.append('>')
r2=['</font>']
if s.strike:
r1.append('<strike>')
r2.insert(0,'</strike>')
if s.underline:
r1.append('<u>')
r2.insert(0,'</u>')
return [''.join(r1), ''.join(r2)]
except __HOLE__:
log.warning('Unknown class %s', style)
return None | KeyError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/createpdf.py/RstToPdf.styleToTags |
4,720 | def styleToFont(self, style):
'''Takes a style name, returns a font tag for it, like
"<font face=helvetica size=14 color=red>". Used for inline
nodes (custom interpreted roles)'''
try:
s = self.styles[style]
r=['<font face="%s" color="#%s" ' %
(s.fontName, s.textColor.hexval()[2:])]
bc = s.backColor
if bc:
r.append('backColor="#%s"' % bc.hexval()[2:])
if s.trueFontSize:
r.append('size="%d"'%s.fontSize)
r.append('>')
return ''.join(r)
except __HOLE__:
log.warning('Unknown class %s', style)
return None | KeyError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/createpdf.py/RstToPdf.styleToFont |
4,721 | def createPdf(self, text=None,
source_path=None,
output=None,
doctree=None,
compressed=False,
# This adds entries to the PDF TOC
# matching the rst source lines
debugLinesPdf=False):
"""Create a PDF from text (ReST input),
or doctree (docutil nodes) and save it in outfile.
If outfile is a string, it's a filename.
If it's something with a write method, (like a StringIO,
or a file object), the data is saved there.
"""
self.decoration = {'header': self.header,
'footer': self.footer,
'endnotes': [],
'extraflowables': []}
self.pending_targets=[]
self.targets=[]
self.debugLinesPdf = debugLinesPdf
if doctree is None:
if text is not None:
if self.language:
settings_overrides={'language_code': self.docutils_language}
else:
settings_overrides={}
settings_overrides['strip_elements_with_classes']=self.strip_elements_with_classes
self.doctree = docutils.core.publish_doctree(text,
source_path=source_path,
settings_overrides=settings_overrides)
#import pdb; pdb.set_trace()
log.debug(self.doctree)
else:
log.error('Error: createPdf needs a text or a doctree')
return
else:
self.doctree = doctree
if self.numbered_links:
# Transform all links to sections so they show numbers
from sectnumlinks import SectNumFolder, SectRefExpander
snf = SectNumFolder(self.doctree)
self.doctree.walk(snf)
srf = SectRefExpander(self.doctree, snf.sectnums)
self.doctree.walk(srf)
if self.strip_elements_with_classes:
from docutils.transforms.universal import StripClassesAndElements
sce = StripClassesAndElements(self.doctree)
sce.apply()
elements = self.gen_elements(self.doctree)
# Find cover template, save it in cover_file
def find_cover(name):
cover_path=[self.basedir, os.path.expanduser('~/.rst2pdf'),
os.path.join(self.PATH,'templates')]
cover_file=None
for d in cover_path:
if os.path.exists(os.path.join(d,name)):
cover_file=os.path.join(d,name)
break
return cover_file
cover_file=find_cover(self.custom_cover)
if cover_file is None:
log.error("Can't find cover template %s, using default"%self.custom_cover)
cover_file=find_cover('cover.tmpl')
# Feed data to the template, get restructured text.
cover_text = renderTemplate(tname=cover_file,
title=self.doc_title,
subtitle=self.doc_subtitle
)
# This crashes sphinx because .. class:: in sphinx is
# something else. Ergo, pdfbuilder does it in its own way.
if not self.sphinx:
elements = self.gen_elements(
publish_secondary_doctree(cover_text, self.doctree, source_path)) + elements
if self.blank_first_page:
elements.insert(0,PageBreak())
# Put the endnotes at the end ;-)
endnotes = self.decoration['endnotes']
if endnotes:
elements.append(MySpacer(1, 2*cm))
elements.append(Separation())
for n in self.decoration['endnotes']:
t_style = TableStyle(self.styles['endnote'].commands)
colWidths = self.styles['endnote'].colWidths
elements.append(DelayedTable([[n[0], n[1]]],
style=t_style, colWidths=colWidths))
if self.floating_images:
#from pudb import set_trace; set_trace()
# Handle images with alignment more like in HTML
new_elem=[]
for i,e in enumerate(elements[::-1]):
if (isinstance (e, MyImage) and e.image.hAlign != 'CENTER'
and new_elem):
# This is an image where flowables should wrap
# around it
popped=new_elem.pop()
new_elem.append(ImageAndFlowables(e,popped,
imageSide=e.image.hAlign.lower()))
else:
new_elem.append(e)
elements = new_elem
elements.reverse()
head = self.decoration['header']
foot = self.decoration['footer']
# So, now, create the FancyPage with the right sizes and elements
FP = FancyPage("fancypage", head, foot, self)
def cleantags(s):
re.sub(r'<[^>]*?>', '',
unicode(s).strip())
pdfdoc = FancyDocTemplate(
output,
pageTemplates=[FP],
showBoundary=0,
pagesize=self.styles.ps,
title=self.doc_title_clean,
author=self.doc_author,
pageCompression=compressed)
pdfdoc.client =self
if getattr(self, 'mustMultiBuild', False):
# Force a multibuild pass
if not isinstance(elements[-1],UnhappyOnce):
log.info ('Forcing second pass so Total pages work')
elements.append(UnhappyOnce())
while True:
try:
log.info("Starting build")
# See if this *must* be multipass
pdfdoc.multiBuild(elements)
# Force a multibuild pass
# FIXME: since mustMultiBuild is set by the
# first pass in the case of ###Total###, then we
# make a new forced two-pass build. This is broken.
# conceptually.
if getattr(self, 'mustMultiBuild', False):
# Force a multibuild pass
if not isinstance(elements[-1],UnhappyOnce):
log.info ('Forcing second pass so Total pages work')
elements.append(UnhappyOnce())
continue
## Rearrange footnotes if needed
if self.real_footnotes:
newStory=[]
fnPile=[]
for e in elements:
if getattr(e,'isFootnote',False):
# Add it to the pile
#if not isinstance (e, MySpacer):
fnPile.append(e)
elif getattr(e, '_atTop', False) or isinstance(
e, (UnhappyOnce, MyPageBreak)):
if fnPile:
fnPile.insert(0, Separation())
newStory.append(Sinker(fnPile))
newStory.append(e)
fnPile=[]
else:
newStory.append(e)
elements = newStory+fnPile
for e in elements:
if hasattr(e, '_postponed'):
delattr(e,'_postponed')
self.real_footnotes = False
continue
break
except __HOLE__, v:
# FIXME: cross-document links come through here, which means
# an extra pass per cross-document reference. Which sucks.
#if v.args and str(v.args[0]).startswith('format not resolved'):
#missing=str(v.args[0]).split(' ')[-1]
#log.error('Adding missing reference to %s and rebuilding. This is slow!'%missing)
#elements.append(Reference(missing))
#for e in elements:
#if hasattr(e,'_postponed'):
#delattr(e,'_postponed')
#else:
#raise
raise
#doc = SimpleDocTemplate("phello.pdf")
#doc.build(elements)
for fn in self.to_unlink:
try:
os.unlink(fn)
except OSError:
pass | ValueError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/createpdf.py/RstToPdf.createPdf |
4,722 | def replaceTokens(self, elems, canv, doc, smarty):
"""Put doc_title/page number/etc in text of header/footer."""
# Make sure page counter is up to date
pnum=setPageCounter()
def replace(text):
if not isinstance(text, unicode):
try:
text = unicode(text, e.encoding)
except AttributeError:
text = unicode(text, 'utf-8')
except __HOLE__:
text = unicode(text, 'utf-8')
text = text.replace(u'###Page###', pnum)
if '###Total###' in text:
text = text.replace(u'###Total###', str(self.totalpages))
self.client.mustMultiBuild=True
text = text.replace(u"###Title###", doc.title)
text = text.replace(u"###Section###",
getattr(canv, 'sectName', ''))
text = text.replace(u"###SectNum###",
getattr(canv, 'sectNum', ''))
text = smartyPants(text, smarty)
return text
for i,e in enumerate(elems):
# TODO: implement a search/replace for arbitrary things
if isinstance(e, Paragraph):
text = replace(e.text)
elems[i] = Paragraph(text, e.style)
elif isinstance(e, DelayedTable):
data=deepcopy(e.data)
for r,row in enumerate(data):
for c,cell in enumerate(row):
if isinstance (cell, list):
data[r][c]=self.replaceTokens(cell, canv, doc, smarty)
else:
row[r]=self.replaceTokens([cell,], canv, doc, smarty)[0]
elems[i]=DelayedTable(data, e._colWidths, e.style)
elif isinstance(e, BoundByWidth):
for index, item in enumerate(e.content):
if isinstance(item, Paragraph):
e.content[index] = Paragraph(replace(item.text), item.style)
elems[i] = e
elif isinstance(e, OddEven):
odd=self.replaceTokens([e.odd,], canv, doc, smarty)[0]
even=self.replaceTokens([e.even,], canv, doc, smarty)[0]
elems[i]=OddEven(odd, even)
return elems | TypeError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/createpdf.py/HeaderOrFooter.replaceTokens |
4,723 | def draw_background(self, which, canv):
''' Draws a background and/or foreground image
on each page which uses the template.
Calculates the image one time, and caches
it for reuse on every page in the template.
How the background is drawn depends on the
--fit-background-mode option.
If desired, we could add code to push it around
on the page, using stylesheets to align and/or
set the offset.
'''
uri=self.template[which]
info = self.image_cache.get(uri)
if info is None:
fname, _, _ = MyImage.split_uri(uri)
if not os.path.exists(fname):
del self.template[which]
log.error("Missing %s image file: %s", which, uri)
return
try:
w, h, kind = MyImage.size_for_node(dict(uri=uri, ), self.client)
except __HOLE__:
# Broken image, return arbitrary stuff
uri=missing
w, h, kind = 100, 100, 'direct'
pw, ph = self.styles.pw, self.styles.ph
if self.client.background_fit_mode == 'center':
scale = min(1.0, 1.0 * pw / w, 1.0 * ph / h)
sw, sh = w * scale, h * scale
x, y = (pw - sw) / 2.0, (ph - sh) / 2.0
elif self.client.background_fit_mode == 'scale':
x, y = 0, 0
sw, sh = pw, ph
else:
log.error('Unknown background fit mode: %s'% self.client.background_fit_mode)
# Do scale anyway
x, y = 0, 0
sw, sh = pw, ph
bg = MyImage(uri, sw, sh, client=self.client)
self.image_cache[uri] = info = bg, x, y
bg, x, y = info
bg.drawOn(canv, x, y) | ValueError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/createpdf.py/FancyPage.draw_background |
4,724 | def main(_args=None):
"""Parse command line and call createPdf with the correct data."""
parser = parse_commandline()
# Fix issue 430: don't overwrite args
# need to parse_args to see i we have a custom config file
options, args = parser.parse_args(copy(_args))
if options.configfile:
# If there is a config file, we need to reparse
# the command line because we have different defaults
config.parseConfig(options.configfile)
parser = parse_commandline()
options, args = parser.parse_args(copy(_args))
if options.version:
from rst2pdf import version
print version
sys.exit(0)
if options.quiet:
log.setLevel(logging.CRITICAL)
if options.verbose:
log.setLevel(logging.INFO)
if options.vverbose:
log.setLevel(logging.DEBUG)
if options.printssheet:
# find base path
if hasattr(sys, 'frozen'):
PATH = abspath(dirname(sys.executable))
else:
PATH = abspath(dirname(__file__))
print open(join(PATH, 'styles', 'styles.style')).read()
sys.exit(0)
filename = False
if len(args) == 0:
args = [ '-', ]
elif len(args) > 2:
log.critical('Usage: %s [ file.txt [ file.pdf ] ]', sys.argv[0])
sys.exit(1)
elif len(args) == 2:
if options.output:
log.critical('You may not give both "-o/--output" and second argument')
sys.exit(1)
options.output = args.pop()
if args[0] == '-':
infile = sys.stdin
options.basedir=os.getcwd()
elif len(args) > 1:
log.critical('Usage: %s file.txt [ -o file.pdf ]', sys.argv[0])
sys.exit(1)
else:
filename = args[0]
options.basedir=os.path.dirname(os.path.abspath(filename))
try:
infile = open(filename)
except __HOLE__, e:
log.error(e)
sys.exit(1)
options.infile = infile
if options.output:
outfile = options.output
if outfile == '-':
outfile = sys.stdout
options.compressed = False
#we must stay quiet
log.setLevel(logging.CRITICAL)
else:
if filename:
if filename.endswith('.txt') or filename.endswith('.rst'):
outfile = filename[:-4] + '.pdf'
else:
outfile = filename + '.pdf'
else:
outfile = sys.stdout
options.compressed = False
#we must stay quiet
log.setLevel(logging.CRITICAL)
#/reportlab/pdfbase/pdfdoc.py output can
#be a callable (stringio, stdout ...)
options.outfile = outfile
ssheet = []
if options.style:
for l in options.style:
ssheet += l.split(',')
else:
ssheet = []
options.style = [x for x in ssheet if x]
fpath = []
if options.fpath:
fpath = options.fpath.split(os.pathsep)
if options.ffolder:
fpath.append(options.ffolder)
options.fpath = fpath
spath = []
if options.stylepath:
spath = options.stylepath.split(os.pathsep)
options.stylepath = spath
if options.real_footnotes:
options.inline_footnotes = True
if reportlab.Version < '2.3':
log.warning('You are using Reportlab version %s.'
' The suggested version is 2.3 or higher' % reportlab.Version)
if options.invariant:
patch_PDFDate()
patch_digester()
add_extensions(options)
RstToPdf(
stylesheets=options.style,
language=options.language,
header=options.header, footer=options.footer,
inlinelinks=options.inlinelinks,
breaklevel=int(options.breaklevel),
baseurl=options.baseurl,
fit_mode=options.fit_mode,
background_fit_mode = options.background_fit_mode,
smarty=str(options.smarty),
font_path=options.fpath,
style_path=options.stylepath,
repeat_table_rows=options.repeattablerows,
footnote_backlinks=options.footnote_backlinks,
inline_footnotes=options.inline_footnotes,
real_footnotes=options.real_footnotes,
def_dpi=int(options.def_dpi),
basedir=options.basedir,
show_frame=options.show_frame,
splittables=options.splittables,
blank_first_page=options.blank_first_page,
first_page_on_right=options.first_page_on_right,
breakside=options.breakside,
custom_cover=options.custom_cover,
floating_images=options.floating_images,
numbered_links=options.numbered_links,
raw_html=options.raw_html,
section_header_depth=int(options.section_header_depth),
strip_elements_with_classes=options.strip_elements_with_classes,
).createPdf(text=options.infile.read(),
source_path=options.infile.name,
output=options.outfile,
compressed=options.compressed)
# Ugly hack that fixes Issue 335 | IOError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/createpdf.py/main |
4,725 | def add_extensions(options):
extensions = []
for ext in options.extensions:
if not ext.startswith('!'):
extensions.append(ext)
continue
ext = ext[1:]
try:
extensions.remove(ext)
except __HOLE__:
log.warning('Could not remove extension %s -- no such extension installed' % ext)
else:
log.info('Removed extension %s' % ext)
options.extensions[:] = extensions
if not extensions:
return
class ModuleProxy(object):
def __init__(self):
self.__dict__ = globals()
createpdf = ModuleProxy()
for modname in options.extensions:
prefix, modname = os.path.split(modname)
path_given = prefix
if modname.endswith('.py'):
modname = modname[:-3]
path_given = True
if not prefix:
prefix = os.path.join(os.path.dirname(__file__), 'extensions')
if prefix not in sys.path:
sys.path.append(prefix)
prefix = os.getcwd()
if prefix not in sys.path:
sys.path.insert(0, prefix)
log.info('Importing extension module %s', repr(modname))
firstname = path_given and modname or (modname + '_r2p')
try:
try:
module = __import__(firstname, globals(), locals())
except ImportError, e:
if firstname != str(e).split()[-1]:
raise
module = __import__(modname, globals(), locals())
except ImportError, e:
if str(e).split()[-1] not in [firstname, modname]:
raise
raise SystemExit('\nError: Could not find module %s '
'in sys.path [\n %s\n]\nExiting...\n' %
(modname, ',\n '.join(sys.path)))
if hasattr(module, 'install'):
module.install(createpdf, options) | ValueError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/createpdf.py/add_extensions |
4,726 | def __dir__(self):
"""Return a list of the StackedObjectProxy's and proxied
object's (if one exists) names.
"""
dir_list = dir(self.__class__) + self.__dict__.keys()
try:
dir_list.extend(dir(self._current_obj()))
except __HOLE__:
pass
dir_list.sort()
return dir_list | TypeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/registry.py/StackedObjectProxy.__dir__ |
4,727 | def __repr__(self):
try:
return repr(self._current_obj())
except (TypeError, __HOLE__):
return '<%s.%s object at 0x%x>' % (self.__class__.__module__,
self.__class__.__name__,
id(self)) | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/registry.py/StackedObjectProxy.__repr__ |
4,728 | def _current_obj(self):
"""Returns the current active object being proxied to
In the event that no object was pushed, the default object if
provided will be used. Otherwise, a TypeError will be raised.
"""
try:
objects = self.____local__.objects
except __HOLE__:
objects = None
if objects:
return objects[-1]
else:
obj = self.__dict__.get('____default_object__', NoDefault)
if obj is not NoDefault:
return obj
else:
raise TypeError(
'No object (name: %s) has been registered for this '
'thread' % self.____name__) | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/registry.py/StackedObjectProxy._current_obj |
4,729 | def _push_object(self, obj):
"""Make ``obj`` the active object for this thread-local.
This should be used like:
.. code-block:: python
obj = yourobject()
module.glob = StackedObjectProxy()
module.glob._push_object(obj)
try:
... do stuff ...
finally:
module.glob._pop_object(conf)
"""
try:
self.____local__.objects.append(obj)
except __HOLE__:
self.____local__.objects = []
self.____local__.objects.append(obj) | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/registry.py/StackedObjectProxy._push_object |
4,730 | def _pop_object(self, obj=None):
"""Remove a thread-local object.
If ``obj`` is given, it is checked against the popped object and an
error is emitted if they don't match.
"""
try:
popped = self.____local__.objects.pop()
if obj and popped is not obj:
raise AssertionError(
'The object popped (%s) is not the same as the object '
'expected (%s)' % (popped, obj))
except __HOLE__:
raise AssertionError('No object has been registered for this thread') | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/registry.py/StackedObjectProxy._pop_object |
4,731 | def _object_stack(self):
"""Returns all of the objects stacked in this container
(Might return [] if there are none)
"""
try:
try:
objs = self.____local__.objects
except __HOLE__:
return []
return objs[:]
except AssertionError:
return []
# The following methods will be swapped for their original versions by
# StackedObjectRestorer when restoration is enabled. The original
# functions (e.g. _current_obj) will be available at _current_obj_orig | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/registry.py/StackedObjectProxy._object_stack |
4,732 | def restoration_end(self):
"""Register a restoration context as finished, if one exists"""
try:
del self.restoration_context_id.request_id
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/registry.py/StackedObjectRestorer.restoration_end |
4,733 | def generate_dict(self, constant_map={}):
"""Returns a dictionary containing all the data associated with the
Shape.
Parameters
==========
constant_map : dictionary
If any of the shape's geometry are defined as SymPy expressions,
then this dictionary should map all SymPy Symbol's found in the
expressions to floats.
"""
data_dict = {}
data_dict['name'] = self.name
data_dict['color'] = self.color
data_dict['material'] = self.material
data_dict['type'] = self.__repr__()
for geom in self.geometry_attrs:
atr = getattr(self, geom)
try:
data_dict[geom] = float(atr.subs(constant_map))
except AttributeError:
# not a SymPy expression
data_dict[geom] = atr
except __HOLE__:
# can't convert expression to float
raise TypeError('{} is an expression, you '.format(atr) +
'must provide a mapping to numerical values.')
return data_dict | TypeError | dataset/ETHPy150Open pydy/pydy/pydy/viz/shapes.py/Shape.generate_dict |
4,734 | def set(self, path, child=False, attribute=False):
""" Accepts a forward slash seperated path of XML elements to traverse and create if non existent.
Optional child and target node attributes can be set. If the `child` attribute is a tuple
it will create X child nodes by reading each tuple as (name, text, 'attribute:value') where value
and attributes are optional for each tuple.
- path: forward slash seperated API element path as string (example: "Order/Authentication/Username")
- child: tuple of child node data or string to create a text node
- attribute: sets the target XML attributes (string format: "Key:Value")
"""
try:
xml_path = path.split('/')
except __HOLE__:
return # because if it's None, then don't worry
xml_doc = self.doc
# traverse full XML element path string `path`
for element_name in xml_path:
# get existing XML element by `element_name`
element = self.doc.getElementsByTagName(element_name)
if element: element = element[0]
# create element if non existing or target element
if not element or element_name == xml_path[-1:][0]:
element = self.doc.createElement(element_name)
xml_doc.appendChild(element)
xml_doc = element
if child:
# create child elements from an tuple with optional text node or attributes
# format: ((name1, text, 'attribute:value'), (name2, text2))
if isinstance(child, tuple):
for obj in child:
child = self.doc.createElement(obj[0])
if len(obj) >= 2:
element = self.doc.createTextNode(str(obj[1]))
child.appendChild(element)
if len(obj) == 3:
a = obj[2].split(':')
child.setAttribute(a[0], a[1])
xml_doc.appendChild(child)
# create a single text child node
else:
element = self.doc.createTextNode(str(child))
xml_doc.appendChild(element)
# target element attributes
if attribute:
#checking to see if we have a list of attributes
if '|' in attribute:
attributes = attribute.split('|')
else:
#if not just put this into a list so we have the same data type no matter what
attributes = [attribute]
# adding attributes for each item
for attribute in attributes:
attribute = attribute.split(':')
xml_doc.setAttribute(attribute[0], attribute[1]) | AttributeError | dataset/ETHPy150Open abunsen/Paython/paython/lib/api.py/XMLGateway.set |
4,735 | def unset(self, key):
"""
Sets up request dict for Get
"""
try:
del self.REQUEST_DICT[key]
except __HOLE__:
raise DataValidationError('The key being unset is non-existent in the request dictionary.') | KeyError | dataset/ETHPy150Open abunsen/Paython/paython/lib/api.py/GetGateway.unset |
4,736 | def __init__(self, context):
self.context = context
self.conn = None
self.cursor = None
self.db_file = None
try:
self.persistence_config = self.context.config['persistence']
self.init_db()
except __HOLE__:
self.context.logger.warn("'persistence' section not found in context configuration") | KeyError | dataset/ETHPy150Open beerfactory/hbmqtt/hbmqtt/plugins/persistence.py/SQLitePlugin.__init__ |
4,737 | def update_ticket(request, ticket_id, public=False):
if not (public or (request.user.is_authenticated() and request.user.is_active and (request.user.is_staff or helpdesk_settings.HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE))):
return HttpResponseRedirect('%s?next=%s' % (reverse('login'), request.path))
ticket = get_object_or_404(Ticket, id=ticket_id)
comment = request.POST.get('comment', '')
new_status = int(request.POST.get('new_status', ticket.status))
title = request.POST.get('title', '')
public = request.POST.get('public', False)
owner = int(request.POST.get('owner', -1))
priority = int(request.POST.get('priority', ticket.priority))
due_date_year = int(request.POST.get('due_date_year', 0))
due_date_month = int(request.POST.get('due_date_month', 0))
due_date_day = int(request.POST.get('due_date_day', 0))
if not (due_date_year and due_date_month and due_date_day):
due_date = ticket.due_date
else:
if ticket.due_date:
due_date = ticket.due_date
else:
due_date = timezone.now()
due_date = due_date.replace(due_date_year, due_date_month, due_date_day)
no_changes = all([
not request.FILES,
not comment,
new_status == ticket.status,
title == ticket.title,
priority == int(ticket.priority),
due_date == ticket.due_date,
(owner == -1) or (not owner and not ticket.assigned_to) or (owner and User.objects.get(id=owner) == ticket.assigned_to),
])
if no_changes:
return return_to_ticket(request.user, helpdesk_settings, ticket)
# We need to allow the 'ticket' and 'queue' contexts to be applied to the
# comment.
from django.template import loader, Context
context = safe_template_context(ticket)
# this line sometimes creates problems if code is sent as a comment.
# if comment contains some django code, like "why does {% if bla %} crash",
# then the following line will give us a crash, since django expects {% if %}
# to be closed with an {% endif %} tag.
# get_template_from_string was removed in Django 1.8 http://django.readthedocs.org/en/1.8.x/ref/templates/upgrading.html
try:
from django.template import engines
template_func = engines['django'].from_string
except __HOLE__: # occurs in django < 1.8
template_func = loader.get_template_from_string
# RemovedInDjango110Warning: render() must be called with a dict, not a Context.
if VERSION < (1, 8):
context = Context(context)
comment = template_func(comment).render(context)
if owner is -1 and ticket.assigned_to:
owner = ticket.assigned_to.id
f = FollowUp(ticket=ticket, date=timezone.now(), comment=comment)
if request.user.is_staff or helpdesk_settings.HELPDESK_ALLOW_NON_STAFF_TICKET_UPDATE:
f.user = request.user
f.public = public
reassigned = False
if owner is not -1:
if owner != 0 and ((ticket.assigned_to and owner != ticket.assigned_to.id) or not ticket.assigned_to):
new_user = User.objects.get(id=owner)
f.title = _('Assigned to %(username)s') % {
'username': new_user.get_username(),
}
ticket.assigned_to = new_user
reassigned = True
# user changed owner to 'unassign'
elif owner == 0 and ticket.assigned_to is not None:
f.title = _('Unassigned')
ticket.assigned_to = None
if new_status != ticket.status:
ticket.status = new_status
ticket.save()
f.new_status = new_status
if f.title:
f.title += ' and %s' % ticket.get_status_display()
else:
f.title = '%s' % ticket.get_status_display()
if not f.title:
if f.comment:
f.title = _('Comment')
else:
f.title = _('Updated')
f.save()
files = []
if request.FILES:
import mimetypes, os
for file in request.FILES.getlist('attachment'):
filename = file.name.encode('ascii', 'ignore')
a = Attachment(
followup=f,
filename=filename,
mime_type=mimetypes.guess_type(filename)[0] or 'application/octet-stream',
size=file.size,
)
a.file.save(filename, file, save=False)
a.save()
if file.size < getattr(settings, 'MAX_EMAIL_ATTACHMENT_SIZE', 512000):
# Only files smaller than 512kb (or as defined in
# settings.MAX_EMAIL_ATTACHMENT_SIZE) are sent via email.
files.append([a.filename, a.file])
if title != ticket.title:
c = TicketChange(
followup=f,
field=_('Title'),
old_value=ticket.title,
new_value=title,
)
c.save()
ticket.title = title
if priority != ticket.priority:
c = TicketChange(
followup=f,
field=_('Priority'),
old_value=ticket.priority,
new_value=priority,
)
c.save()
ticket.priority = priority
if due_date != ticket.due_date:
c = TicketChange(
followup=f,
field=_('Due on'),
old_value=ticket.due_date,
new_value=due_date,
)
c.save()
ticket.due_date = due_date
if new_status in [ Ticket.RESOLVED_STATUS, Ticket.CLOSED_STATUS ]:
if new_status == Ticket.RESOLVED_STATUS or ticket.resolution is None:
ticket.resolution = comment
messages_sent_to = []
# ticket might have changed above, so we re-instantiate context with the
# (possibly) updated ticket.
context = safe_template_context(ticket)
context.update(
resolution=ticket.resolution,
comment=f.comment,
)
if public and (f.comment or (f.new_status in (Ticket.RESOLVED_STATUS, Ticket.CLOSED_STATUS))):
if f.new_status == Ticket.RESOLVED_STATUS:
template = 'resolved_'
elif f.new_status == Ticket.CLOSED_STATUS:
template = 'closed_'
else:
template = 'updated_'
template_suffix = 'submitter'
if ticket.submitter_email:
send_templated_mail(
template + template_suffix,
context,
recipients=ticket.submitter_email,
sender=ticket.queue.from_address,
fail_silently=True,
files=files,
)
messages_sent_to.append(ticket.submitter_email)
template_suffix = 'cc'
for cc in ticket.ticketcc_set.all():
if cc.email_address not in messages_sent_to:
send_templated_mail(
template + template_suffix,
context,
recipients=cc.email_address,
sender=ticket.queue.from_address,
fail_silently=True,
files=files,
)
messages_sent_to.append(cc.email_address)
if ticket.assigned_to and request.user != ticket.assigned_to and ticket.assigned_to.email and ticket.assigned_to.email not in messages_sent_to:
# We only send e-mails to staff members if the ticket is updated by
# another user. The actual template varies, depending on what has been
# changed.
if reassigned:
template_staff = 'assigned_owner'
elif f.new_status == Ticket.RESOLVED_STATUS:
template_staff = 'resolved_owner'
elif f.new_status == Ticket.CLOSED_STATUS:
template_staff = 'closed_owner'
else:
template_staff = 'updated_owner'
if (not reassigned or ( reassigned and ticket.assigned_to.usersettings.settings.get('email_on_ticket_assign', False))) or (not reassigned and ticket.assigned_to.usersettings.settings.get('email_on_ticket_change', False)):
send_templated_mail(
template_staff,
context,
recipients=ticket.assigned_to.email,
sender=ticket.queue.from_address,
fail_silently=True,
files=files,
)
messages_sent_to.append(ticket.assigned_to.email)
if ticket.queue.updated_ticket_cc and ticket.queue.updated_ticket_cc not in messages_sent_to:
if reassigned:
template_cc = 'assigned_cc'
elif f.new_status == Ticket.RESOLVED_STATUS:
template_cc = 'resolved_cc'
elif f.new_status == Ticket.CLOSED_STATUS:
template_cc = 'closed_cc'
else:
template_cc = 'updated_cc'
send_templated_mail(
template_cc,
context,
recipients=ticket.queue.updated_ticket_cc,
sender=ticket.queue.from_address,
fail_silently=True,
files=files,
)
ticket.save()
# auto subscribe user if enabled
if helpdesk_settings.HELPDESK_AUTO_SUBSCRIBE_ON_TICKET_RESPONSE and request.user.is_authenticated():
ticketcc_string, SHOW_SUBSCRIBE = return_ticketccstring_and_show_subscribe(request.user, ticket)
if SHOW_SUBSCRIBE:
subscribe_staff_member_to_ticket(ticket, request.user)
return return_to_ticket(request.user, helpdesk_settings, ticket) | ImportError | dataset/ETHPy150Open rossp/django-helpdesk/helpdesk/views/staff.py/update_ticket |
4,738 | def ticket_list(request):
context = {}
user_queues = _get_user_queues(request.user)
# Prefilter the allowed tickets
base_tickets = Ticket.objects.filter(queue__in=user_queues)
# Query_params will hold a dictionary of parameters relating to
# a query, to be saved if needed:
query_params = {
'filtering': {},
'sorting': None,
'sortreverse': False,
'keyword': None,
'other_filter': None,
}
from_saved_query = False
# If the user is coming from the header/navigation search box, lets' first
# look at their query to see if they have entered a valid ticket number. If
# they have, just redirect to that ticket number. Otherwise, we treat it as
# a keyword search.
if request.GET.get('search_type', None) == 'header':
query = request.GET.get('q')
filter = None
if query.find('-') > 0:
try:
queue, id = query.split('-')
id = int(id)
except ValueError:
id = None
if id:
filter = {'queue__slug': queue, 'id': id }
else:
try:
query = int(query)
except ValueError:
query = None
if query:
filter = {'id': int(query) }
if filter:
try:
ticket = base_tickets.get(**filter)
return HttpResponseRedirect(ticket.staff_url)
except Ticket.DoesNotExist:
# Go on to standard keyword searching
pass
saved_query = None
if request.GET.get('saved_query', None):
from_saved_query = True
try:
saved_query = SavedSearch.objects.get(pk=request.GET.get('saved_query'))
except SavedSearch.DoesNotExist:
return HttpResponseRedirect(reverse('helpdesk_list'))
if not (saved_query.shared or saved_query.user == request.user):
return HttpResponseRedirect(reverse('helpdesk_list'))
try:
import pickle
except ImportError:
import cPickle as pickle
from helpdesk.lib import b64decode
query_params = pickle.loads(b64decode(str(saved_query.query)))
elif not ( 'queue' in request.GET
or 'assigned_to' in request.GET
or 'status' in request.GET
or 'q' in request.GET
or 'sort' in request.GET
or 'sortreverse' in request.GET
):
# Fall-back if no querying is being done, force the list to only
# show open/reopened/resolved (not closed) cases sorted by creation
# date.
query_params = {
'filtering': {'status__in': [1, 2, 3]},
'sorting': 'created',
}
else:
queues = request.GET.getlist('queue')
if queues:
try:
queues = [int(q) for q in queues]
query_params['filtering']['queue__id__in'] = queues
except ValueError:
pass
owners = request.GET.getlist('assigned_to')
if owners:
try:
owners = [int(u) for u in owners]
query_params['filtering']['assigned_to__id__in'] = owners
except ValueError:
pass
statuses = request.GET.getlist('status')
if statuses:
try:
statuses = [int(s) for s in statuses]
query_params['filtering']['status__in'] = statuses
except ValueError:
pass
date_from = request.GET.get('date_from')
if date_from:
query_params['filtering']['created__gte'] = date_from
date_to = request.GET.get('date_to')
if date_to:
query_params['filtering']['created__lte'] = date_to
### KEYWORD SEARCHING
q = request.GET.get('q', None)
if q:
qset = (
Q(title__icontains=q) |
Q(description__icontains=q) |
Q(resolution__icontains=q) |
Q(submitter_email__icontains=q)
)
context = dict(context, query=q)
query_params['other_filter'] = qset
### SORTING
sort = request.GET.get('sort', None)
if sort not in ('status', 'assigned_to', 'created', 'title', 'queue', 'priority'):
sort = 'created'
query_params['sorting'] = sort
sortreverse = request.GET.get('sortreverse', None)
query_params['sortreverse'] = sortreverse
tickets = base_tickets.select_related()
try:
ticket_qs = apply_query(tickets, query_params)
except ValidationError:
# invalid parameters in query, return default query
query_params = {
'filtering': {'status__in': [1, 2, 3]},
'sorting': 'created',
}
ticket_qs = apply_query(tickets, query_params)
ticket_paginator = paginator.Paginator(ticket_qs, request.user.usersettings.settings.get('tickets_per_page') or 20)
try:
page = int(request.GET.get('page', '1'))
except __HOLE__:
page = 1
try:
tickets = ticket_paginator.page(page)
except (paginator.EmptyPage, paginator.InvalidPage):
tickets = ticket_paginator.page(ticket_paginator.num_pages)
search_message = ''
if 'query' in context and settings.DATABASES['default']['ENGINE'].endswith('sqlite'):
search_message = _('<p><strong>Note:</strong> Your keyword search is case sensitive because of your database. This means the search will <strong>not</strong> be accurate. By switching to a different database system you will gain better searching! For more information, read the <a href="http://docs.djangoproject.com/en/dev/ref/databases/#sqlite-string-matching">Django Documentation on string matching in SQLite</a>.')
try:
import pickle
except ImportError:
import cPickle as pickle
from helpdesk.lib import b64encode
urlsafe_query = b64encode(pickle.dumps(query_params))
user_saved_queries = SavedSearch.objects.filter(Q(user=request.user) | Q(shared__exact=True))
querydict = request.GET.copy()
querydict.pop('page', 1)
return render_to_response('helpdesk/ticket_list.html',
RequestContext(request, dict(
context,
query_string=querydict.urlencode(),
tickets=tickets,
user_choices=User.objects.filter(is_active=True,is_staff=True),
queue_choices=user_queues,
status_choices=Ticket.STATUS_CHOICES,
urlsafe_query=urlsafe_query,
user_saved_queries=user_saved_queries,
query_params=query_params,
from_saved_query=from_saved_query,
saved_query=saved_query,
search_message=search_message,
))) | ValueError | dataset/ETHPy150Open rossp/django-helpdesk/helpdesk/views/staff.py/ticket_list |
4,739 | def run_report(request, report):
if Ticket.objects.all().count() == 0 or report not in ('queuemonth', 'usermonth', 'queuestatus', 'queuepriority', 'userstatus', 'userpriority', 'userqueue', 'daysuntilticketclosedbymonth'):
return HttpResponseRedirect(reverse("helpdesk_report_index"))
report_queryset = Ticket.objects.all().select_related().filter(
queue__in=_get_user_queues(request.user)
)
from_saved_query = False
saved_query = None
if request.GET.get('saved_query', None):
from_saved_query = True
try:
saved_query = SavedSearch.objects.get(pk=request.GET.get('saved_query'))
except SavedSearch.DoesNotExist:
return HttpResponseRedirect(reverse('helpdesk_report_index'))
if not (saved_query.shared or saved_query.user == request.user):
return HttpResponseRedirect(reverse('helpdesk_report_index'))
try:
import pickle
except __HOLE__:
import cPickle as pickle
from helpdesk.lib import b64decode
query_params = pickle.loads(b64decode(str(saved_query.query)))
report_queryset = apply_query(report_queryset, query_params)
from collections import defaultdict
summarytable = defaultdict(int)
# a second table for more complex queries
summarytable2 = defaultdict(int)
month_name = lambda m: MONTHS_3[m].title()
first_ticket = Ticket.objects.all().order_by('created')[0]
first_month = first_ticket.created.month
first_year = first_ticket.created.year
last_ticket = Ticket.objects.all().order_by('-created')[0]
last_month = last_ticket.created.month
last_year = last_ticket.created.year
periods = []
year, month = first_year, first_month
working = True
periods.append("%s %s" % (month_name(month), year))
while working:
month += 1
if month > 12:
year += 1
month = 1
if (year > last_year) or (month > last_month and year >= last_year):
working = False
periods.append("%s %s" % (month_name(month), year))
if report == 'userpriority':
title = _('User by Priority')
col1heading = _('User')
possible_options = [t[1].title() for t in Ticket.PRIORITY_CHOICES]
charttype = 'bar'
elif report == 'userqueue':
title = _('User by Queue')
col1heading = _('User')
queue_options = _get_user_queues(request.user)
possible_options = [q.title for q in queue_options]
charttype = 'bar'
elif report == 'userstatus':
title = _('User by Status')
col1heading = _('User')
possible_options = [s[1].title() for s in Ticket.STATUS_CHOICES]
charttype = 'bar'
elif report == 'usermonth':
title = _('User by Month')
col1heading = _('User')
possible_options = periods
charttype = 'date'
elif report == 'queuepriority':
title = _('Queue by Priority')
col1heading = _('Queue')
possible_options = [t[1].title() for t in Ticket.PRIORITY_CHOICES]
charttype = 'bar'
elif report == 'queuestatus':
title = _('Queue by Status')
col1heading = _('Queue')
possible_options = [s[1].title() for s in Ticket.STATUS_CHOICES]
charttype = 'bar'
elif report == 'queuemonth':
title = _('Queue by Month')
col1heading = _('Queue')
possible_options = periods
charttype = 'date'
elif report == 'daysuntilticketclosedbymonth':
title = _('Days until ticket closed by Month')
col1heading = _('Queue')
possible_options = periods
charttype = 'date'
metric3 = False
for ticket in report_queryset:
if report == 'userpriority':
metric1 = u'%s' % ticket.get_assigned_to
metric2 = u'%s' % ticket.get_priority_display()
elif report == 'userqueue':
metric1 = u'%s' % ticket.get_assigned_to
metric2 = u'%s' % ticket.queue.title
elif report == 'userstatus':
metric1 = u'%s' % ticket.get_assigned_to
metric2 = u'%s' % ticket.get_status_display()
elif report == 'usermonth':
metric1 = u'%s' % ticket.get_assigned_to
metric2 = u'%s %s' % (month_name(ticket.created.month), ticket.created.year)
elif report == 'queuepriority':
metric1 = u'%s' % ticket.queue.title
metric2 = u'%s' % ticket.get_priority_display()
elif report == 'queuestatus':
metric1 = u'%s' % ticket.queue.title
metric2 = u'%s' % ticket.get_status_display()
elif report == 'queuemonth':
metric1 = u'%s' % ticket.queue.title
metric2 = u'%s %s' % (month_name(ticket.created.month), ticket.created.year)
elif report == 'daysuntilticketclosedbymonth':
metric1 = u'%s' % ticket.queue.title
metric2 = u'%s %s' % (month_name(ticket.created.month), ticket.created.year)
metric3 = ticket.modified - ticket.created
metric3 = metric3.days
summarytable[metric1, metric2] += 1
if metric3:
if report == 'daysuntilticketclosedbymonth':
summarytable2[metric1, metric2] += metric3
table = []
if report == 'daysuntilticketclosedbymonth':
for key in summarytable2.keys():
summarytable[key] = summarytable2[key] / summarytable[key]
header1 = sorted(set(list(i for i, _ in summarytable.keys())))
column_headings = [col1heading] + possible_options
# Pivot the data so that 'header1' fields are always first column
# in the row, and 'possible_options' are always the 2nd - nth columns.
for item in header1:
data = []
for hdr in possible_options:
data.append(summarytable[item, hdr])
table.append([item] + data)
return render_to_response('helpdesk/report_output.html',
RequestContext(request, {
'title': title,
'charttype': charttype,
'data': table,
'headings': column_headings,
'from_saved_query': from_saved_query,
'saved_query': saved_query,
})) | ImportError | dataset/ETHPy150Open rossp/django-helpdesk/helpdesk/views/staff.py/run_report |
4,740 | def selectLink(self, displayPoint, view):
if not self.enabled():
return False
robotModel, _ = vis.findPickedObject(displayPoint, view)
try:
robotModel.model.getLinkNameForMesh
except __HOLE__:
return False
model = robotModel.model
pickedPoint, _, polyData = vis.pickProp(displayPoint, view)
linkName = model.getLinkNameForMesh(polyData)
if not linkName:
return False
fadeValue = 1.0 if linkName == self.selectedLink else 0.05
for name in model.getLinkNames():
linkColor = model.getLinkColor(name)
linkColor.setAlphaF(fadeValue)
model.setLinkColor(name, linkColor)
if linkName == self.selectedLink:
self.selectedLink = None
vis.hideCaptionWidget()
om.removeFromObjectModel(om.findObjectByName('selected link frame'))
else:
self.selectedLink = linkName
linkColor = model.getLinkColor(self.selectedLink)
linkColor.setAlphaF(1.0)
model.setLinkColor(self.selectedLink, linkColor)
vis.showCaptionWidget(robotModel.getLinkFrame(self.selectedLink).GetPosition(), self.selectedLink, view=view)
vis.updateFrame(robotModel.getLinkFrame(self.selectedLink), 'selected link frame', scale=0.2, parent=robotModel)
return True | AttributeError | dataset/ETHPy150Open RobotLocomotion/director/src/python/director/robotviewbehaviors.py/RobotLinkSelector.selectLink |
4,741 | def getObjectAsPointCloud(obj):
try:
obj = obj.model.polyDataObj
except __HOLE__:
pass
try:
obj.polyData
except AttributeError:
return None
if obj and obj.polyData.GetNumberOfPoints():# and (obj.polyData.GetNumberOfCells() == obj.polyData.GetNumberOfVerts()):
return obj | AttributeError | dataset/ETHPy150Open RobotLocomotion/director/src/python/director/robotviewbehaviors.py/getObjectAsPointCloud |
4,742 | def __contains__(self,n):
"""Return True if n is a node, False otherwise. Use the expression
'n in G'.
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2,3])
>>> 1 in G
True
"""
try:
return n in self.node
except __HOLE__:
return False | TypeError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.__contains__ |
4,743 | def add_node(self, n, attr_dict=None, **attr):
"""Add a single node n and update node attributes.
Parameters
----------
n : node
A node can be any hashable Python object except None.
attr_dict : dictionary, optional (default= no attributes)
Dictionary of node attributes. Key/value pairs will
update existing data associated with the node.
attr : keyword arguments, optional
Set or change attributes using key=value.
See Also
--------
add_nodes_from
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_node(1)
>>> G.add_node('Hello')
>>> K3 = nx.Graph([(0,1),(1,2),(2,0)])
>>> G.add_node(K3)
>>> G.number_of_nodes()
3
Use keywords set/change node attributes:
>>> G.add_node(1,size=10)
>>> G.add_node(3,weight=0.4,UTM=('13S',382871,3972649))
Notes
-----
A hashable object is one that can be used as a key in a Python
dictionary. This includes strings, numbers, tuples of strings
and numbers, etc.
On many platforms hashable items also include mutables such as
NetworkX Graphs, though one should be careful that the hash
doesn't change on mutables.
"""
# set up attribute dict
if attr_dict is None:
attr_dict=attr
else:
try:
attr_dict.update(attr)
except __HOLE__:
raise NetworkXError(\
"The attr_dict argument must be a dictionary.")
if n not in self.node:
self.adj[n] = {}
self.node[n] = attr_dict
else: # update attr even if node already exists
self.node[n].update(attr_dict) | AttributeError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.add_node |
4,744 | def add_nodes_from(self, nodes, **attr):
"""Add multiple nodes.
Parameters
----------
nodes : iterable container
A container of nodes (list, dict, set, etc.).
OR
A container of (node, attribute dict) tuples.
Node attributes are updated using the attribute dict.
attr : keyword arguments, optional (default= no attributes)
Update attributes for all nodes in nodes.
Node attributes specified in nodes as a tuple
take precedence over attributes specified generally.
See Also
--------
add_node
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_nodes_from('Hello')
>>> K3 = nx.Graph([(0,1),(1,2),(2,0)])
>>> G.add_nodes_from(K3)
>>> sorted(G.nodes(),key=str)
[0, 1, 2, 'H', 'e', 'l', 'o']
Use keywords to update specific node attributes for every node.
>>> G.add_nodes_from([1,2], size=10)
>>> G.add_nodes_from([3,4], weight=0.4)
Use (node, attrdict) tuples to update attributes for specific
nodes.
>>> G.add_nodes_from([(1,dict(size=11)), (2,{'color':'blue'})])
>>> G.node[1]['size']
11
>>> H = nx.Graph()
>>> H.add_nodes_from(G.nodes(data=True))
>>> H.node[1]['size']
11
"""
for n in nodes:
try:
newnode=n not in self.node
except __HOLE__:
nn,ndict = n
if nn not in self.node:
self.adj[nn] = {}
newdict = attr.copy()
newdict.update(ndict)
self.node[nn] = newdict
else:
olddict = self.node[nn]
olddict.update(attr)
olddict.update(ndict)
continue
if newnode:
self.adj[n] = {}
self.node[n] = attr.copy()
else:
self.node[n].update(attr) | TypeError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.add_nodes_from |
4,745 | def remove_node(self,n):
"""Remove node n.
Removes the node n and all adjacent edges.
Attempting to remove a non-existent node will raise an exception.
Parameters
----------
n : node
A node in the graph
Raises
-------
NetworkXError
If n is not in the graph.
See Also
--------
remove_nodes_from
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2])
>>> G.edges()
[(0, 1), (1, 2)]
>>> G.remove_node(1)
>>> G.edges()
[]
"""
adj = self.adj
try:
nbrs = list(adj[n].keys()) # keys handles self-loops (allow mutation later)
del self.node[n]
except __HOLE__: # NetworkXError if n not in self
raise NetworkXError("The node %s is not in the graph."%(n,))
for u in nbrs:
del adj[u][n] # remove all edges n-u in graph
del adj[n] # now remove node | KeyError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.remove_node |
4,746 | def remove_nodes_from(self, nodes):
"""Remove multiple nodes.
Parameters
----------
nodes : iterable container
A container of nodes (list, dict, set, etc.). If a node
in the container is not in the graph it is silently
ignored.
See Also
--------
remove_node
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2])
>>> e = G.nodes()
>>> e
[0, 1, 2]
>>> G.remove_nodes_from(e)
>>> G.nodes()
[]
"""
adj = self.adj
for n in nodes:
try:
del self.node[n]
for u in list(adj[n].keys()): # keys() handles self-loops
del adj[u][n] #(allows mutation of dict in loop)
del adj[n]
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.remove_nodes_from |
4,747 | def has_node(self, n):
"""Return True if the graph contains the node n.
Parameters
----------
n : node
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2])
>>> G.has_node(0)
True
It is more readable and simpler to use
>>> 0 in G
True
"""
try:
return n in self.node
except __HOLE__:
return False | TypeError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.has_node |
4,748 | def add_edge(self, u, v, attr_dict=None, **attr):
"""Add an edge between u and v.
The nodes u and v will be automatically added if they are
not already in the graph.
Edge attributes can be specified with keywords or by providing
a dictionary with key/value pairs. See examples below.
Parameters
----------
u,v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
attr_dict : dictionary, optional (default= no attributes)
Dictionary of edge attributes. Key/value pairs will
update existing data associated with the edge.
attr : keyword arguments, optional
Edge data (or labels or objects) can be assigned using
keyword arguments.
See Also
--------
add_edges_from : add a collection of edges
Notes
-----
Adding an edge that already exists updates the edge data.
Many NetworkX algorithms designed for weighted graphs use as
the edge weight a numerical value assigned to a keyword
which by default is 'weight'.
Examples
--------
The following all add the edge e=(1,2) to graph G:
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> e = (1,2)
>>> G.add_edge(1, 2) # explicit two-node form
>>> G.add_edge(*e) # single edge as tuple of two nodes
>>> G.add_edges_from( [(1,2)] ) # add edges from iterable container
Associate data to edges using keywords:
>>> G.add_edge(1, 2, weight=3)
>>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
"""
# set up attribute dictionary
if attr_dict is None:
attr_dict=attr
else:
try:
attr_dict.update(attr)
except __HOLE__:
raise NetworkXError(\
"The attr_dict argument must be a dictionary.")
# add nodes
if u not in self.node:
self.adj[u] = {}
self.node[u] = {}
if v not in self.node:
self.adj[v] = {}
self.node[v] = {}
# add the edge
datadict=self.adj[u].get(v,{})
datadict.update(attr_dict)
self.adj[u][v] = datadict
self.adj[v][u] = datadict | AttributeError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.add_edge |
4,749 | def add_edges_from(self, ebunch, attr_dict=None, **attr):
"""Add all the edges in ebunch.
Parameters
----------
ebunch : container of edges
Each edge given in the container will be added to the
graph. The edges must be given as as 2-tuples (u,v) or
3-tuples (u,v,d) where d is a dictionary containing edge
data.
attr_dict : dictionary, optional (default= no attributes)
Dictionary of edge attributes. Key/value pairs will
update existing data associated with each edge.
attr : keyword arguments, optional
Edge data (or labels or objects) can be assigned using
keyword arguments.
See Also
--------
add_edge : add a single edge
add_weighted_edges_from : convenient way to add weighted edges
Notes
-----
Adding the same edge twice has no effect but any edge data
will be updated when each duplicate edge is added.
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edges_from([(0,1),(1,2)]) # using a list of edge tuples
>>> e = zip(range(0,3),range(1,4))
>>> G.add_edges_from(e) # Add the path graph 0-1-2-3
Associate data to edges
>>> G.add_edges_from([(1,2),(2,3)], weight=3)
>>> G.add_edges_from([(3,4),(1,4)], label='WN2898')
"""
# set up attribute dict
if attr_dict is None:
attr_dict=attr
else:
try:
attr_dict.update(attr)
except __HOLE__:
raise NetworkXError(\
"The attr_dict argument must be a dictionary.")
# process ebunch
for e in ebunch:
ne=len(e)
if ne==3:
u,v,dd = e
elif ne==2:
u,v = e
dd = {}
else:
raise NetworkXError(\
"Edge tuple %s must be a 2-tuple or 3-tuple."%(e,))
if u not in self.node:
self.adj[u] = {}
self.node[u] = {}
if v not in self.node:
self.adj[v] = {}
self.node[v] = {}
datadict=self.adj[u].get(v,{})
datadict.update(attr_dict)
datadict.update(dd)
self.adj[u][v] = datadict
self.adj[v][u] = datadict | AttributeError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.add_edges_from |
4,750 | def remove_edge(self, u, v):
"""Remove the edge between u and v.
Parameters
----------
u,v: nodes
Remove the edge between nodes u and v.
Raises
------
NetworkXError
If there is not an edge between u and v.
See Also
--------
remove_edges_from : remove a collection of edges
Examples
--------
>>> G = nx.Graph() # or DiGraph, etc
>>> G.add_path([0,1,2,3])
>>> G.remove_edge(0,1)
>>> e = (1,2)
>>> G.remove_edge(*e) # unpacks e from an edge tuple
>>> e = (2,3,{'weight':7}) # an edge with attribute data
>>> G.remove_edge(*e[:2]) # select first part of edge tuple
"""
try:
del self.adj[u][v]
if u != v: # self-loop needs only one entry removed
del self.adj[v][u]
except __HOLE__:
raise NetworkXError("The edge %s-%s is not in the graph"%(u,v)) | KeyError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.remove_edge |
4,751 | def has_edge(self, u, v):
"""Return True if the edge (u,v) is in the graph.
Parameters
----------
u,v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
Returns
-------
edge_ind : bool
True if edge is in the graph, False otherwise.
Examples
--------
Can be called either using two nodes u,v or edge tuple (u,v)
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2,3])
>>> G.has_edge(0,1) # using two nodes
True
>>> e = (0,1)
>>> G.has_edge(*e) # e is a 2-tuple (u,v)
True
>>> e = (0,1,{'weight':7})
>>> G.has_edge(*e[:2]) # e is a 3-tuple (u,v,data_dictionary)
True
The following syntax are all equivalent:
>>> G.has_edge(0,1)
True
>>> 1 in G[0] # though this gives KeyError if 0 not in G
True
"""
try:
return v in self.adj[u]
except __HOLE__:
return False | KeyError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.has_edge |
4,752 | def neighbors(self, n):
"""Return a list of the nodes connected to the node n.
Parameters
----------
n : node
A node in the graph
Returns
-------
nlist : list
A list of nodes that are adjacent to n.
Raises
------
NetworkXError
If the node n is not in the graph.
Notes
-----
It is usually more convenient (and faster) to access the
adjacency dictionary as G[n]:
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edge('a','b',weight=7)
>>> G['a']
{'b': {'weight': 7}}
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2,3])
>>> G.neighbors(0)
[1]
"""
try:
return list(self.adj[n])
except __HOLE__:
raise NetworkXError("The node %s is not in the graph."%(n,)) | KeyError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.neighbors |
4,753 | def neighbors_iter(self, n):
"""Return an iterator over all neighbors of node n.
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2,3])
>>> [n for n in G.neighbors_iter(0)]
[1]
Notes
-----
It is faster to use the idiom "in G[0]", e.g.
>>> G = nx.path_graph(4)
>>> [n for n in G[0]]
[1]
"""
try:
return iter(self.adj[n])
except __HOLE__:
raise NetworkXError("The node %s is not in the graph."%(n,)) | KeyError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.neighbors_iter |
4,754 | def get_edge_data(self, u, v, default=None):
"""Return the attribute dictionary associated with edge (u,v).
Parameters
----------
u,v : nodes
default: any Python object (default=None)
Value to return if the edge (u,v) is not found.
Returns
-------
edge_dict : dictionary
The edge attribute dictionary.
Notes
-----
It is faster to use G[u][v].
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2,3])
>>> G[0][1]
{}
Warning: Assigning G[u][v] corrupts the graph data structure.
But it is safe to assign attributes to that dictionary,
>>> G[0][1]['weight'] = 7
>>> G[0][1]['weight']
7
>>> G[1][0]['weight']
7
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2,3])
>>> G.get_edge_data(0,1) # default edge data is {}
{}
>>> e = (0,1)
>>> G.get_edge_data(*e) # tuple form
{}
>>> G.get_edge_data('a','b',default=0) # edge not in graph, return 0
0
"""
try:
return self.adj[u][v]
except __HOLE__:
return default | KeyError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.get_edge_data |
4,755 | def nbunch_iter(self, nbunch=None):
"""Return an iterator of nodes contained in nbunch that are
also in the graph.
The nodes in nbunch are checked for membership in the graph
and if not are silently ignored.
Parameters
----------
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated
through once.
Returns
-------
niter : iterator
An iterator over nodes in nbunch that are also in the graph.
If nbunch is None, iterate over all nodes in the graph.
Raises
------
NetworkXError
If nbunch is not a node or or sequence of nodes.
If a node in nbunch is not hashable.
See Also
--------
Graph.__iter__
Notes
-----
When nbunch is an iterator, the returned iterator yields values
directly from nbunch, becoming exhausted when nbunch is exhausted.
To test whether nbunch is a single node, one can use
"if nbunch in self:", even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator
or None, a NetworkXError is raised. Also, if any object in
nbunch is not hashable, a NetworkXError is raised.
"""
if nbunch is None: # include all nodes via iterator
bunch=iter(self.adj.keys())
elif nbunch in self: # if nbunch is a single node
bunch=iter([nbunch])
else: # if nbunch is a sequence of nodes
def bunch_iter(nlist,adj):
try:
for n in nlist:
if n in adj:
yield n
except __HOLE__ as e:
message=e.args[0]
import sys
sys.stdout.write(message)
# capture error for non-sequence/iterator nbunch.
if 'iter' in message:
raise NetworkXError(\
"nbunch is not a node or a sequence of nodes.")
# capture error for unhashable node.
elif 'hashable' in message:
raise NetworkXError(\
"Node %s in the sequence nbunch is not a valid node."%n)
else:
raise
bunch=bunch_iter(nbunch,self.adj)
return bunch | TypeError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/classes/graph.py/Graph.nbunch_iter |
4,756 | def process_formdata(self, valuelist):
if valuelist:
date_str = u' '.join(valuelist)
if date_str.strip():
for format in self.formats:
try:
timetuple = time.strptime(date_str, format)
self.data = datetime.time(timetuple.tm_hour,
timetuple.tm_min,
timetuple.tm_sec)
return
except __HOLE__:
pass
raise ValueError(gettext('Invalid time format'))
else:
self.data = None | ValueError | dataset/ETHPy150Open flask-admin/flask-admin/flask_admin/form/fields.py/TimeField.process_formdata |
4,757 | def process_data(self, value):
if value is None:
self.data = None
else:
try:
self.data = self.coerce(value)
except (ValueError, __HOLE__):
self.data = None | TypeError | dataset/ETHPy150Open flask-admin/flask-admin/flask_admin/form/fields.py/Select2Field.process_data |
4,758 | def process_formdata(self, valuelist):
if valuelist:
if valuelist[0] == '__None':
self.data = None
else:
try:
self.data = self.coerce(valuelist[0])
except __HOLE__:
raise ValueError(self.gettext(u'Invalid Choice: could not coerce')) | ValueError | dataset/ETHPy150Open flask-admin/flask-admin/flask_admin/form/fields.py/Select2Field.process_formdata |
4,759 | def process_formdata(self, valuelist):
if valuelist:
value = valuelist[0]
# allow saving blank field as None
if not value:
self.data = None
return
try:
self.data = json.loads(valuelist[0])
except __HOLE__:
raise ValueError(self.gettext('Invalid JSON')) | ValueError | dataset/ETHPy150Open flask-admin/flask-admin/flask_admin/form/fields.py/JSONField.process_formdata |
4,760 | def __new__(self, d):
try:
return unicode.__new__(self, d['category']['term'])
except __HOLE__:
return unicode.__new__(self, d) | TypeError | dataset/ETHPy150Open ryszard/python-netflix/netflix/__init__.py/NetflixAvailability.__new__ |
4,761 | def __init__(self, d):
cat = d['category']
super(NetflixAvailability, self).__init__(**cat)
try:
self.available_from = datetime.fromtimestamp(float(d['available_from']))
self.available = False
except KeyError:
self.available_from = None
try:
self.available_until = datetime.fromtimestamp(float(d['available_until']))
except __HOLE__:
self.available_until = None | KeyError | dataset/ETHPy150Open ryszard/python-netflix/netflix/__init__.py/NetflixAvailability.__init__ |
4,762 | def __init__(self, d):
try:
self.links = dict((di['title'], NetflixLink(**di)) for di in d.pop('link'))
except __HOLE__:
pass
for k in d:
setattr(self, k, d[k])
super(FancyObject, self).__init__() | KeyError | dataset/ETHPy150Open ryszard/python-netflix/netflix/__init__.py/FancyObject.__init__ |
4,763 | def __init__(self, d):
title = d.pop('title')
self.title = title['regular']
self.title_short = title['short']
categories = d.pop('category')
self.categories = [NetflixCategory(**di) for di in get_me_a_list_dammit(categories)]
for label in 'estimated_arrival_date', 'shipped_date':
try:
setattr(self, label, datetime.fromtimestamp(float(d.pop(label))))
except __HOLE__:
pass
try:
self.average_rating = float(d.pop('average_rating'))
except KeyError:
pass
super(CatalogTitle, self).__init__(d) | KeyError | dataset/ETHPy150Open ryszard/python-netflix/netflix/__init__.py/CatalogTitle.__init__ |
4,764 | @property
def netflix_id(self):
try:
return self.links[self.title].href
except __HOLE__:
return self.id | KeyError | dataset/ETHPy150Open ryszard/python-netflix/netflix/__init__.py/CatalogTitle.netflix_id |
4,765 | def __eq__(self, other):
try:
return self.netflix_id == other.netflix_id
except __HOLE__:
try:
return self.netflix_id == other.id
except AttributeError:
return False | AttributeError | dataset/ETHPy150Open ryszard/python-netflix/netflix/__init__.py/CatalogTitle.__eq__ |
4,766 | def __init__(self, d):
self.preferred_formats = []
try:
preferred_formats = d.pop('preferred_formats')
except __HOLE__:
preferred_formats = d.pop('preferred_format', [])
for pf in get_me_a_list_dammit(preferred_formats):
for category in get_me_a_list_dammit(pf['category']):
self.preferred_formats.append(NetflixCategory(**category))
super(NetflixUser, self).__init__(d) | KeyError | dataset/ETHPy150Open ryszard/python-netflix/netflix/__init__.py/NetflixUser.__init__ |
4,767 | def __init__(self, d):
try:
items = d.pop(self._items_name)
except __HOLE__:
raise NotImplemened("NetflixCollection subclasses must set _items_name")
except KeyError:
self.items = []
else:
if not isinstance(items, (list, tuple)):
items = [items]
self.items = [self.item_type(dd) for dd in items]
super(NetflixCollection, self).__init__(d)
for lab in 'number_of_results', 'results_per_page', 'start_index':
setattr(self, lab, int(getattr(self, lab))) | AttributeError | dataset/ETHPy150Open ryszard/python-netflix/netflix/__init__.py/NetflixCollection.__init__ |
4,768 | def __contains__(self, item):
if isinstance(item, self.item_type):
return item in self.items
elif isinstance(item, basestring):
return item in [i.netflix_id for i in self]
try:
return item.netflix_id in self
except __HOLE__:
pass
return False | AttributeError | dataset/ETHPy150Open ryszard/python-netflix/netflix/__init__.py/NetflixCollection.__contains__ |
4,769 | def object_hook(self, d):
d = dict((str(k), v) for k, v in d.iteritems())
def isa(label):
return label in d and len(d) == 1
if 'catalog_titles' in d:
try:
catalog_titles = d['catalog_titles']['catalog_title']
if not isinstance(catalog_titles, list):
catalog_titles = [catalog_titles]
return [CatalogTitle(di) for di in catalog_titles]
except (__HOLE__, TypeError):
return d['catalog_titles']
elif isa('catalog_title'):
try:
return CatalogTitle(d['catalog_title'])
except TypeError:
return [CatalogTitle(i) for i in d['catalog_title']]
elif isa('synopsis'):
return d['synopsis']
elif isa('delivery_formats'):
availabilities = d['delivery_formats']['availability']
if not isinstance(availabilities, list):
availabilities = [availabilities]
return [NetflixAvailability(o) for o in availabilities]
elif isa('user'):
return NetflixUser(d['user'])
elif isa('rental_history'):
return RentalHistory(d['rental_history'])
elif isa('at_home'):
return NetflixAtHome(d['at_home'])
elif isa('queue'):
return NetflixQueue(d['queue'])
else:
return d | KeyError | dataset/ETHPy150Open ryszard/python-netflix/netflix/__init__.py/Netflix.object_hook |
4,770 | def analyze_error(self, exc):
error = exc.data
try:
error = json.loads(error)
code = int(error['status']['status_code'])
message = error['status']['message']
except (KeyError, __HOLE__):
code = exc.status
message = error
if code == 401:
if message == "Access Token Validation Failed":
raise AuthError(message)
elif message == 'Invalid Signature':
raise InvalidSignature(message)
elif message == 'Invalid Or Expired Token':
raise InvalidOrExpiredToken(message)
elif code == 403:
if 'Service is over queries per second limit' in message:
raise TooManyRequestsPerSecondError()
elif 'Over queries per day limit' in message:
raise TooManyRequestsPerDayError()
elif code == 404:
raise NotFound(message)
elif code == 400 and message == 'Missing Required Access Token':
raise MissingAccessTokenError(message)
elif code == 412 and message == 'Title is already in queue':
raise TitleAlreadyInQueue()
elif code >= 500:
raise InternalNetflixError(message)
raise NetflixError(code, message) | ValueError | dataset/ETHPy150Open ryszard/python-netflix/netflix/__init__.py/Netflix.analyze_error |
4,771 | @call_interval(0.25)
def request(self, url, token=None, verb='GET', filename=None, **args):
"""`url` may be relative with regard to Netflix. Verb is a
HTTP verb.
"""
if isinstance(url, NetflixObject) and not isinstance(url, basestring):
url = url.id
if not url.startswith('http://'):
url = self.protocol + self.host + url
if 'output' not in args:
args['output'] = 'json'
args['method'] = verb.upper()
# we don't want unicode in the parameters
for k,v in args.iteritems():
try:
args[k] = v.encode('utf-8')
except __HOLE__:
pass
oa_req = OAuthRequest.from_consumer_and_token(self.consumer,
http_url=url,
parameters=args,
token=token)
oa_req.sign_request(self.signature_method,
self.consumer,
token)
if filename is None:
def do_request():
req = self.http.urlopen('GET', oa_req.to_url())
if not str(req.status).startswith('2'):
self.analyze_error(req)
return req
else:
def do_request():
try:
subprocess.check_call(["curl", oa_req.to_url(),
"--location",
"--compressed",
"--output", filename])
sys.stderr.write('\nSaved to: %s\n' % filename)
except OSError:
raise RuntimeError, "You need to have curl installed to use this command"
try:
req = do_request()
except TooManyRequestsPerSecondError:
time.sleep(1)
req = do_request()
if filename:
return
o = json.loads(req.data, object_hook=self.object_hook)
return o | AttributeError | dataset/ETHPy150Open ryszard/python-netflix/netflix/__init__.py/Netflix.request |
4,772 | def loadAll():
"""Loads all DroneD Services that adhere to the Interface Definition
of IDroneDService. The resulting dictionary will return in the form
of {"SERVICENAME": "MODULE", ...}
:Note technically this is a private method, because the server will
hide it from you.
@return (dict)
"""
from kitt.interfaces import IDroneDService
from twisted.python.log import err
from twisted.python.failure import Failure
import warnings
import config
import os
global EXPORTED_SERVICES
my_dir = os.path.dirname(__file__)
for filename in os.listdir(my_dir):
if not filename.endswith('.py'): continue
if filename == '__init__.py': continue
modname = filename[:-3]
mod = None
try:
mod = __import__(__name__ + '.' + modname, {}, {}, [modname])
except:
err(Failure(), 'Exception Caught Importing Service module %s' % \
(modname,))
continue #skip further checks
if not mod: continue #fix for sphinx documentation
#prefer module level interfaces first and foremost
try:
if IDroneDService.providedBy(mod):
EXPORTED_SERVICES[mod.SERVICENAME] = mod
continue #module level interfaces are considered singleton services
except __HOLE__: pass
except:
err(Failure(), 'Exception Caught Validating Module Interface %s' % \
(name,))
#see if any classes implement the desired interfaces
for name,obj in vars(mod).items():
try:
if IDroneDService.implementedBy(obj):
EXPORTED_SERVICES[obj.SERVICENAME] = obj() #instantiate now
warnings.warn('loaded %s' % name)
else:
warnings.warn('%s from %s does not provide ' + \
'IDroneDService Interface' % \
(name,modname))
except TypeError: pass
except:
err(Failure(), 'Exception Caught Validating Interface %s' % \
(name,))
#apply romeo configuration to all services
for name, obj in EXPORTED_SERVICES.items():
try: obj.SERVICECONFIG.wrapped.update(config.SERVICES.get(name, {}))
except:
err(Failure(), 'Exception Caught Setting Configuration %s' % \
(modname,))
return EXPORTED_SERVICES | TypeError | dataset/ETHPy150Open OrbitzWorldwide/droned/droned/services/__init__.py/loadAll |
4,773 | def process(self, key):
if len(self.table1) < key:
raise IndexError('Invalid key for first table!')
try:
_key = self.table2[key]
print_success('Here is the control statement '
'you requested: `{}` => `{}`'.format(key, _key))
return _key
except __HOLE__:
print_error('Could not process key: {}'.format(key))
return None | IndexError | dataset/ETHPy150Open christabor/MoAL/MOAL/data_structures/linear/array/control_table.py/ControlTableNaive.process |
4,774 | def __init__(self, name):
try:
super(EasyTestSuite, self).__init__(
findTestCases(sys.modules[name]))
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open circus-tent/circus/circus/tests/support.py/EasyTestSuite.__init__ |
4,775 | def has_gevent():
try:
import gevent # NOQA
return True
except __HOLE__:
return False | ImportError | dataset/ETHPy150Open circus-tent/circus/circus/tests/support.py/has_gevent |
4,776 | def has_circusweb():
try:
import circusweb # NOQA
return True
except __HOLE__:
return False | ImportError | dataset/ETHPy150Open circus-tent/circus/circus/tests/support.py/has_circusweb |
4,777 | def poll_for_callable(func, *args, **kwargs):
"""Replay to update the status during timeout seconds."""
timeout = 5
if 'timeout' in kwargs:
timeout = kwargs.pop('timeout')
start = time()
last_exception = None
while time() - start < timeout:
try:
func_args = []
for arg in args:
if callable(arg):
func_args.append(arg())
else:
func_args.append(arg)
func(*func_args)
except __HOLE__ as e:
last_exception = e
sleep(0.1)
else:
return True
raise last_exception or AssertionError('No exception triggered yet') | AssertionError | dataset/ETHPy150Open circus-tent/circus/circus/tests/support.py/poll_for_callable |
4,778 | def _convert_definition(self, definition, ref=None):
"""
Converts any object to its troposphere equivalent, if applicable.
This function will recurse into lists and mappings to create
additional objects as necessary.
"""
if isinstance(definition, Mapping):
if 'Type' in definition: # this is an AWS Resource
expected_type = None
try:
expected_type = self.inspect_resources[definition['Type']]
except KeyError:
# if the user uses the custom way to name custom resources,
# we'll dynamically create a new subclass for this use and
# pass that instead of the typical CustomObject resource
try:
expected_type = self._generate_custom_type(
definition['Type'])
except __HOLE__:
assert not expected_type
if expected_type:
args = self._normalize_properties(definition)
return self._create_instance(expected_type, args, ref)
if len(definition) == 1: # This might be a function?
function_type = self._get_function_type(
definition.keys()[0])
if function_type:
return self._create_instance(
function_type, definition.values()[0])
# nothing special here - return as dict
return {k: self._convert_definition(v)
for k, v in definition.iteritems()}
elif (isinstance(definition, Sequence) and
not isinstance(definition, basestring)):
return [self._convert_definition(v) for v in definition]
# anything else is returned as-is
return definition | TypeError | dataset/ETHPy150Open cloudtools/troposphere/troposphere/template_generator.py/TemplateGenerator._convert_definition |
4,779 | def _create_instance(self, cls, args, ref=None):
"""
Returns an instance of `cls` with `args` passed as arguments.
Recursively inspects `args` to create nested objects and functions as
necessary.
`cls` will only be considered only if it's an object we track
(i.e.: troposphere objects).
If `cls` has a `props` attribute, nested properties will be
instanciated as troposphere Property objects as necessary.
If `cls` is a list and contains a single troposphere type, the
returned value will be a list of instances of that type.
"""
if isinstance(cls, Sequence):
if len(cls) == 1:
# a list of 1 type means we must provide a list of such objects
if (isinstance(args, basestring) or
not isinstance(args, Sequence)):
args = [args]
return [self._create_instance(cls[0], v) for v in args]
if isinstance(cls, Sequence) or cls not in self.inspect_members:
# this object doesn't map to any known object. could be a string
# or int, or a Ref... or a list of types such as
# [basestring, FindInMap, Ref] or maybe a
# validator such as `integer` or `port_range`
return self._convert_definition(args)
elif issubclass(cls, AWSHelperFn):
# special handling for functions, we want to handle it before
# entering the other conditions.
if isinstance(args, Sequence) and not isinstance(args, basestring):
return cls(*self._convert_definition(args))
else:
if issubclass(cls, autoscaling.Metadata):
return self._generate_autoscaling_metadata(cls, args)
args = self._convert_definition(args)
if isinstance(args, Ref) and issubclass(cls, Ref):
# watch out for double-refs...
# this can happen if an object's .props has 'Ref'
# as the expected type (which is wrong and should be
# changed to basestring!)
return args
try:
return cls(args)
except __HOLE__ as ex:
if '__init__() takes exactly' not in ex.message:
raise
# special AWSHelperFn typically take lowercased parameters,
# but templates use uppercase. for this reason we cannot
# map to most of them, so we fallback with a generic one.
# this might not work for all types if they do extra
# processing in their init routine...
return GenericHelperFn(args)
elif isinstance(args, Mapping):
# we try to build as many troposphere objects as we can by
# inspecting its type validation metadata
kwargs = {}
kwargs.update(args)
for prop_name in getattr(cls, 'props', []):
if prop_name not in kwargs:
continue # the user did not specify this value; skip it
expected_type = cls.props[prop_name][0]
if (isinstance(expected_type, Sequence) or
expected_type in self.inspect_members):
kwargs[prop_name] = self._create_instance(
expected_type, kwargs[prop_name], prop_name)
else:
kwargs[prop_name] = self._convert_definition(
kwargs[prop_name], prop_name)
args = self._convert_definition(kwargs)
if isinstance(args, Ref):
# use the returned ref instead of creating a new object
return args
assert isinstance(args, Mapping)
return cls(title=ref, **args)
return cls(self._convert_definition(args)) | TypeError | dataset/ETHPy150Open cloudtools/troposphere/troposphere/template_generator.py/TemplateGenerator._create_instance |
4,780 | def query_from_object_id(self, object_id):
""" Obtaining a query from resource id.
Query can be then used to identify a resource in resources or meters
API calls. ID is being built in the Resource initializer, or returned
by Datatable into UpdateRow functionality.
"""
try:
tenant_id, user_id, resource_id = object_id.split("__")
except __HOLE__:
return []
return make_query(tenant_id=tenant_id, user_id=user_id,
resource_id=resource_id) | ValueError | dataset/ETHPy150Open Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/api/ceilometer.py/CeilometerUsage.query_from_object_id |
4,781 | def finder(finder_cls):
"""
View decorator that takes care of everything needed to render a finder on
the rendered page.
"""
def decorator(view_func):
finder = finder_cls()
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
if request.is_ajax() and request.GET.get("finder"):
col_name = request.GET["col"]
return render(
request,
finder.column_template(col_name),
{
"colname": col_name,
"finder": {
"finder": finder,
col_name: finder.objects(
col_name, request.GET["id"])
},
}
)
response = view_func(request, *args, **kwargs)
try:
ctx = response.context_data
except __HOLE__:
return response
top_col = finder.columns[0]
finder_ctx = ctx.setdefault("finder", {})
finder_ctx.update(
{
"finder": finder,
top_col.name: finder.objects(top_col.name)
}
)
return response
return _wrapped_view
return decorator | AttributeError | dataset/ETHPy150Open mozilla/moztrap/moztrap/view/lists/finder.py/finder |
4,782 | def goto_url(self, obj):
"""Given an object, return its "Goto" url, or None."""
try:
col = self.columns_by_model[obj.__class__]
except __HOLE__:
return None
return col.goto_url(obj) | KeyError | dataset/ETHPy150Open mozilla/moztrap/moztrap/view/lists/finder.py/Finder.goto_url |
4,783 | def child_column_for_obj(self, obj):
"""Given an object, return name of its child column, or None."""
try:
col = self.columns_by_model[obj.__class__]
return self.child_columns[col.name].name
except __HOLE__:
return None | KeyError | dataset/ETHPy150Open mozilla/moztrap/moztrap/view/lists/finder.py/Finder.child_column_for_obj |
4,784 | def objects(self, column_name, parent=None):
"""
Given a column name, return the list of objects.
If a parent is given and there is a parent column, filter the list by
that parent.
"""
col = self._get_column_by_name(column_name)
ret = col.objects()
if parent is not None:
try:
parent_col = self.parent_columns[col.name]
except KeyError:
raise ValueError(
"Column {0} has no parent.".format(column_name))
opts = col.model._meta
attr = None
for field in [
f for f in opts.fields if isinstance(f, models.ForeignKey)
] + opts.many_to_many:
if field.rel.to is parent_col.model:
attr = field.name
break
if attr is None:
try:
attr = [
r.get_accessor_name()
for r in opts.get_all_related_many_to_many_objects()
if r.model is parent_col.model
][0]
except __HOLE__:
raise ValueError(
"Cannot find relationship from {0} to {1}".format(
col.model, parent_col.model))
ret = ret.filter(**{attr: parent})
return ret | IndexError | dataset/ETHPy150Open mozilla/moztrap/moztrap/view/lists/finder.py/Finder.objects |
4,785 | def _get_column_by_name(self, column_name):
try:
return self.columns_by_name[column_name]
except __HOLE__:
raise ValueError("Column %r does not exist." % column_name) | KeyError | dataset/ETHPy150Open mozilla/moztrap/moztrap/view/lists/finder.py/Finder._get_column_by_name |
4,786 | def setUp(self):
"""Run before each test method to initialize test environment."""
super(TestCase, self).setUp()
self.context = ironic_context.get_admin_context()
test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
try:
test_timeout = int(test_timeout)
except __HOLE__:
# If timeout value is invalid do not set a timeout.
test_timeout = 0
if test_timeout > 0:
self.useFixture(fixtures.Timeout(test_timeout, gentle=True))
self.useFixture(fixtures.NestedTempfile())
self.useFixture(fixtures.TempHomeDir())
if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or
os.environ.get('OS_STDOUT_CAPTURE') == '1'):
stdout = self.useFixture(fixtures.StringStream('stdout')).stream
self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or
os.environ.get('OS_STDERR_CAPTURE') == '1'):
stderr = self.useFixture(fixtures.StringStream('stderr')).stream
self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
self.log_fixture = self.useFixture(fixtures.FakeLogger())
self._set_config()
# NOTE(danms): Make sure to reset us back to non-remote objects
# for each test to avoid interactions. Also, backup the object
# registry
objects_base.IronicObject.indirection_api = None
self._base_test_obj_backup = copy.copy(
objects_base.IronicObjectRegistry.obj_classes())
self.addCleanup(self._restore_obj_registry)
self.addCleanup(self._clear_attrs)
self.addCleanup(hash_ring.HashRingManager().reset)
self.useFixture(fixtures.EnvironmentVariable('http_proxy'))
self.policy = self.useFixture(policy_fixture.PolicyFixture()) | ValueError | dataset/ETHPy150Open openstack/ironic/ironic/tests/base.py/TestCase.setUp |
4,787 | def register(model, feed_attr='feed'):
"""
Gives the model class a feed for each object.
"""
try:
from functools import wraps
except __HOLE__:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback
from django.db.models import signals as model_signals
from django.db.models import FieldDoesNotExist, ForeignKey
from django.utils.translation import ugettext as _
from django.template.defaultfilters import slugify
from django.contrib.contenttypes.models import ContentType
from object_feeds import models
from object_feeds.signals import pre_save, post_save
if model in registry:
raise AlreadyRegistered(
_('The model %s has already been registered.') % model.__name__)
registry.append(model)
# Add the feed to the model's Options
opts = model._meta
opts.feed_attr = feed_attr
# Add the feed field since it probably doesn't exist
for attr in [feed_attr]:
try:
opts.get_field(attr)
except FieldDoesNotExist:
ForeignKey(models.Feed, unique=True, null=True).contribute_to_class(model, attr)
# Add feed object methods for model instances
setattr(model, 'register_action', models.register_action)
setattr(model, 'is_user_following', models.is_user_following)
# Set up signal receiver to manage the tree when instances of the
# model are about to be saved.
model_signals.pre_save.connect(pre_save, sender=model)
model_signals.post_save.connect(post_save, sender=model) | ImportError | dataset/ETHPy150Open caseywstark/colab/colab/apps/object_feeds/__init__.py/register |
4,788 | def get_ips(init_host, compute_host, ssh_user):
runner = remote_runner.RemoteRunner(host=compute_host, user=ssh_user,
gateway=init_host)
cmd = ("ifconfig | awk -F \"[: ]+\" \'/inet addr:/ "
"{ if ($4 != \"127.0.0.1\") print $4 }\'")
out = runner.run(cmd)
list_ips = []
for info in out.split():
try:
ipaddr.IPAddress(info)
except __HOLE__:
continue
list_ips.append(info)
return list_ips | ValueError | dataset/ETHPy150Open MirantisWorkloadMobility/CloudFerry/cloudferry/lib/utils/node_ip.py/get_ips |
4,789 | def __init__(self, body = None, cself = None):
if cself != None:
for header_name in [x + '_header' for x in self.all_headers]:
try:
setattr(self, header_name, getattr(cself, header_name).getCopy())
except __HOLE__:
pass
self.a_headers = [x for x in cself.a_headers]
self.sections = [x.getCopy() for x in cself.sections]
return
self.a_headers = []
self.sections = []
if body == None:
return
avpairs = [x.split('=', 1) for x in body.strip().splitlines() if len(x.strip()) > 0]
current_snum = 0
c_header = None
for name, v in avpairs:
name = name.lower()
if name == 'm':
current_snum += 1
self.sections.append(SdpMediaDescription())
if current_snum == 0:
if name == 'c':
c_header = v
elif name == 'a':
self.a_headers.append(v)
else:
setattr(self, name + '_header', f_types[name](v))
else:
self.sections[-1].addHeader(name, v)
if c_header != None:
for section in self.sections:
if section.c_header == None:
section.addHeader('c', c_header)
if len(self.sections) == 0:
self.addHeader('c', c_header) | AttributeError | dataset/ETHPy150Open sippy/b2bua/sippy/SdpBody.py/SdpBody.__init__ |
4,790 | def write_file(content, filename, mode='wt', encoding=None):
"""
Write ``content`` to disk at ``filename``. Files with appropriate extensions
are compressed with gzip or bz2 automatically. Any intermediate folders
not found on disk are automatically created.
"""
_make_dirs(filename)
_open = gzip.open if filename.endswith('.gz') \
else bzip_open if filename.endswith('.bz2') \
else io.open
try:
with _open(filename, mode=mode, encoding=encoding) as f:
f.write(content)
except __HOLE__: # Py2's bz2.BZ2File doesn't accept `encoding` ...
with _open(filename, mode=mode) as f:
f.write(content) | TypeError | dataset/ETHPy150Open chartbeat-labs/textacy/textacy/fileio/write.py/write_file |
4,791 | def write_file_lines(lines, filename, mode='wt', encoding=None):
"""
Write the content in ``lines`` to disk at ``filename``, line by line. Files
with appropriate extensions are compressed with gzip or bz2 automatically.
Any intermediate folders not found on disk are automatically created.
"""
_make_dirs(filename)
_open = gzip.open if filename.endswith('.gz') \
else bzip_open if filename.endswith('.bz2') \
else io.open
try:
with _open(filename, mode=mode, encoding=encoding) as f:
for line in lines:
f.write(line +'\n')
except __HOLE__: # Py2's bz2.BZ2File doesn't accept `encoding` ...
with _open(filename, mode=mode) as f:
for line in lines:
f.write(line +'\n') | TypeError | dataset/ETHPy150Open chartbeat-labs/textacy/textacy/fileio/write.py/write_file_lines |
4,792 | def wrap_tmpl_func(render_str):
def render_tmpl(tmplsrc,
from_str=False,
to_str=False,
context=None,
tmplpath=None,
**kws):
if context is None:
context = {}
# Alias cmd.run to cmd.shell to make python_shell=True the default for
# templated calls
if 'salt' in kws:
kws['salt'] = AliasedLoader(kws['salt'])
# We want explicit context to overwrite the **kws
kws.update(context)
context = kws
assert 'opts' in context
assert 'saltenv' in context
if 'sls' in context:
slspath = context['sls'].replace('.', '/')
if tmplpath is not None:
context['tplpath'] = tmplpath
if not tmplpath.lower().replace('\\', '/').endswith('/init.sls'):
slspath = os.path.dirname(slspath)
template = tmplpath.replace('\\', '/')
i = template.rfind(slspath.replace('.', '/'))
if i != -1:
template = template[i:]
tpldir = os.path.dirname(template).replace('\\', '/')
tpldata = {
'tplfile': template,
'tpldir': '.' if tpldir == '' else tpldir,
'tpldot': tpldir.replace('/', '.'),
}
context.update(tpldata)
context['slsdotpath'] = slspath.replace('/', '.')
context['slscolonpath'] = slspath.replace('/', ':')
context['sls_path'] = slspath.replace('/', '_')
context['slspath'] = slspath
if isinstance(tmplsrc, string_types):
if from_str:
tmplstr = tmplsrc
else:
try:
if tmplpath is not None:
tmplsrc = os.path.join(tmplpath, tmplsrc)
with codecs.open(tmplsrc, 'r', SLS_ENCODING) as _tmplsrc:
tmplstr = _tmplsrc.read()
except (UnicodeDecodeError,
ValueError,
__HOLE__,
IOError) as exc:
if salt.utils.is_bin_file(tmplsrc):
# Template is a bin file, return the raw file
return dict(result=True, data=tmplsrc)
log.error(
'Exception occurred while reading file '
'{0}: {1}'.format(tmplsrc, exc),
# Show full traceback if debug logging is enabled
exc_info_on_loglevel=logging.DEBUG
)
raise exc
else: # assume tmplsrc is file-like.
tmplstr = tmplsrc.read()
tmplsrc.close()
try:
output = render_str(tmplstr, context, tmplpath)
if salt.utils.is_windows():
# Write out with Windows newlines
output = os.linesep.join(output.splitlines())
except SaltRenderError as exc:
log.error("Rendering exception occurred: {0}".format(exc))
#return dict(result=False, data=str(exc))
raise
except Exception:
return dict(result=False, data=traceback.format_exc())
else:
if to_str: # then render as string
return dict(result=True, data=output)
with tempfile.NamedTemporaryFile('wb', delete=False) as outf:
outf.write(SLS_ENCODER(output)[0])
# Note: If nothing is replaced or added by the rendering
# function, then the contents of the output file will
# be exactly the same as the input.
return dict(result=True, data=outf.name)
render_tmpl.render_str = render_str
return render_tmpl | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/templates.py/wrap_tmpl_func |
4,793 | def _get_jinja_error_slug(tb_data):
'''
Return the line number where the template error was found
'''
try:
return [
x
for x in tb_data if x[2] in ('top-level template code',
'template')
][-1]
except __HOLE__:
pass | IndexError | dataset/ETHPy150Open saltstack/salt/salt/utils/templates.py/_get_jinja_error_slug |
4,794 | def _get_jinja_error_message(tb_data):
'''
Return an understandable message from jinja error output
'''
try:
line = _get_jinja_error_slug(tb_data)
return u'{0}({1}):\n{3}'.format(*line)
except __HOLE__:
pass
return None | IndexError | dataset/ETHPy150Open saltstack/salt/salt/utils/templates.py/_get_jinja_error_message |
4,795 | def _get_jinja_error_line(tb_data):
'''
Return the line number where the template error was found
'''
try:
return _get_jinja_error_slug(tb_data)[1]
except __HOLE__:
pass
return None | IndexError | dataset/ETHPy150Open saltstack/salt/salt/utils/templates.py/_get_jinja_error_line |
4,796 | def handle(self, *args, **options):
MindmapWebSocketRouter = SockJSRouter(handlers.MindmapWebSocketHandler, '/ws')
app_kwargs = {}
if settings.ENVIRONMENT.IS_FOR_DEVELOPMENT:
app_kwargs['debug'] = True
app = web.Application(MindmapWebSocketRouter.urls, **app_kwargs)
app.listen(settings.MINDMAPTORNADO_BIND_PORT)
try:
ioloop.IOLoop.instance().start()
except __HOLE__:
ioloop.IOLoop.instance().stop() | KeyboardInterrupt | dataset/ETHPy150Open ierror/BeautifulMind.io/beautifulmind/mindmaptornado/management/commands/mindmaptornado_run.py/Command.handle |
4,797 | def is_valid_in_template(var, attr):
"""
Given a variable and one of its attributes, determine if the attribute is
accessible inside of a Django template and return True or False accordingly
"""
# Remove private variables or methods
if attr.startswith('_'):
return False
# Remove any attributes that raise an acception when read
try:
value = getattr(var, attr)
except:
return False
if isroutine(value):
# Remove any routines that are flagged with 'alters_data'
if getattr(value, 'alters_data', False):
return False
else:
# Remove any routines that require arguments
try:
argspec = getargspec(value)
num_args = len(argspec.args) if argspec.args else 0
num_defaults = len(argspec.defaults) if argspec.defaults else 0
if num_args - num_defaults > 1:
return False
except __HOLE__:
# C extension callables are routines, but getargspec fails with
# a TypeError when these are passed.
pass
return True | TypeError | dataset/ETHPy150Open calebsmith/django-template-debug/template_debug/utils.py/is_valid_in_template |
4,798 | def _post_data(self, context, traceback=None):
"""POST data to the the Exceptional API. If DEBUG is True then data is
sent to ``EXCEPTIONAL_DEBUG_URL`` if it has been defined. If TESTING is
true, error data is stored in the global ``flask.g.exceptional``
variable.
:param context: The current application or application context.
:param traceback: Default ``None``. The exception stack trace.
"""
if context:
if isinstance(context, Flask):
app = context
context = None
else:
app = context.app
else:
app = stack.top.app
application_data = self.__get_application_data(app)
client_data = {
"name": "flask-exceptional",
"version": self.__version__,
"protocol_version": self.__protocol_version
}
if context:
request_data = self.__get_request_data(app, context.request,
context.session)
context_data = getattr(context, "exceptional_context", None)
else:
request_data = None
context_data = None
traceback = traceback or tbtools.get_current_traceback()
exception_data = self.__get_exception_data(traceback)
encode_basestring = json.encoder.encode_basestring
def _encode_basestring(value):
if isinstance(value, str) and \
json.encoder.HAS_UTF8.search(value) is not None:
value = value.decode("utf-8",
"replace") # ensure the decode succeeds.
replace = lambda match: json.encoder.ESCAPE_DCT[match.group(0)]
return u'"%s"' % json.encoder.ESCAPE.sub(replace, value)
try:
json.encoder.encode_basestring = _encode_basestring
ret_val = json.dumps({
"application_environment": application_data,
"client": client_data,
"request": request_data,
"exception": exception_data,
"context": context_data
}, ensure_ascii=False).encode("utf-8")
finally:
json.encoder.encode_basestring = encode_basestring
if context and app.testing:
g.exceptional = ret_val
if self.url:
request = Request(self.url)
request.add_header("Content-Type", "application/json")
if app.debug:
data = ret_val
else:
request.add_header("Content-Encoding", "deflate")
data = compress(ret_val, 1)
try:
try:
urlopen(request, data)
except __HOLE__, e:
if e.code >= 400:
raise
except URLError:
message = "Unable to connect to %s. See http://status.exceptional.io for details. Error data:\n%s" # NOQA
app.logger.warning(message, self.url, ret_val,
exc_info=True)
except BadStatusLine:
pass
return ret_val | HTTPError | dataset/ETHPy150Open jzempel/flask-exceptional/flask_exceptional.py/Exceptional._post_data |
4,799 | def load_databag(filename):
try:
if filename.endswith('.json'):
with open(filename, 'r') as f:
return json.load(f, object_pairs_hook=OrderedDict)
elif filename.endswith('.ini'):
return decode_flat_data(IniFile(filename).items(),
dict_cls=OrderedDict)
except (OSError, __HOLE__) as e:
if e.errno != errno.ENOENT:
raise | IOError | dataset/ETHPy150Open lektor/lektor-archive/lektor/databags.py/load_databag |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.