本文整理汇总了Python中utils.format_error函数的典型用法代码示例。如果您正苦于以下问题:Python format_error函数的具体用法?Python format_error怎么用?Python format_error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了format_error函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: error_handler
def error_handler(self, e, request, meth, em_format):
"""
Override this method to add handling of errors customized for your
needs
"""
if isinstance(e, FormValidationError):
return self.form_validation_response(e, self.determine_emitter(request))
elif isinstance(e, TypeError):
result = rc.BAD_REQUEST
msg = "Method signature does not match.\n\n"
try:
hm = HandlerMethod(meth)
sig = hm.signature
except TypeError:
msg += "Signature could not be determined"
else:
if sig:
msg += "Signature should be: %s" % sig
else:
msg += "Resource does not expect any parameters."
if self.display_errors:
msg += "\n\nException was: %s" % str(e)
result.content = format_error(msg)
return result
elif isinstance(e, Http404):
return rc.NOT_FOUND
elif isinstance(e, HttpStatusCode):
return e.response
else:
"""
On errors (like code errors), we'd like to be able to
give crash reports to both admins and also the calling
user. There's two setting parameters for this:
Parameters::
- `PISTON_EMAIL_ERRORS`: Will send a Django formatted
error email to people in `settings.ADMINS`.
- `PISTON_DISPLAY_ERRORS`: Will return a simple traceback
to the caller, so he can tell you what error they got.
If `PISTON_DISPLAY_ERRORS` is not enabled, the caller will
receive a basic "500 Internal Server Error" message.
"""
exc_type, exc_value, tb = sys.exc_info()
rep = ExceptionReporter(request, exc_type, exc_value, tb.tb_next)
if self.email_errors:
self.email_exception(rep)
if self.display_errors:
return HttpResponseServerError(format_error("\n".join(rep.format_exception())))
else:
raise
示例2: msg
def msg(self, to, *args):
""" Sends a message to other nodes
- to The identifier of the point of the ring that gets the
message. Note that may or not be the same that the identifier of
the node that manages that segment of the ring.
- *args A list of arguments to pass to the other node ('the
message'). Binary arguments must be wrapped in a xmlprclib.Binary
object, and decoded in the destinity """
logger.info('%s: new application message'%self.id)
if self.manage(to):
# it is for me
if not self.listener: return None
try:
return self.listener.message(to, *args)
except:
return "ERROR: "%utils.format_error()
else:
# it is not for me: inform to the listeners
# and answers if there is a response
r=None
try:
if self.listener:
r=self.listener.routing(to, *args)
except:
logger.warn('Routing app: ' + utils.format_error())
if r:
return r
else:
return self.__next(to).msg(to, *args)
示例3: __del__
def __del__(self):
""" Closes the file when there is no further reference """
try:
self.close()
except:
logger.warn('Error closing file %s'%self.uri.get_readable())
utils.format_error()
示例4: leave
def leave(self):
""" Leaves the network """
try:
logger.debug('%s: leaving the network'%self.id)
if self.joined and self.next:
na = self.contacted[self.next]
if self.prev: self.__next(self.prev).leave_msg(self.id, self.next, na[0], na[1])
if self.listener: self.listener.left(None)
self.joined = False
logger.info('%s: left the network'%self.id)
else:
logger.info('%s: I was alone in the network'%self.id)
except:
utils.format_error()
self.server.shutdown()
示例5: draw_toyMC
def draw_toyMC(hist,title,xlabel="",ylabel="",exponent=None, box="tl"):
fit = root.TF1("gauss","gaus")
textbox = r"\begin{align*}\mu&=%s\\\sigma&=%s\end{align*}"
fig, a = utils.get_plotaxes((4,3.2))
hist.Fit(fit,"LQ")
r2mpl.plot(hist,axes=a, errors=True, color="k", zorder=1)
r2mpl.plot(fit,axes=a, color="r", zorder=0)
utils.text_box(a, box, textbox % (
utils.format_error(fit.GetParameter(1), fit.GetParError(1), exponent=exponent),
utils.format_error(fit.GetParameter(2), fit.GetParError(2), exponent=exponent)))
a.set_title(title)
a.set_xlabel(xlabel)
a.set_ylabel(ylabel)
return a, (fit.GetParameter(1), fit.GetParError(1)), (fit.GetParameter(2), fit.GetParError(2))
示例6: calc_eff
def calc_eff(efficiency, errors, n=7, scale=1.0):
total_eff=0
total_err=0
for i in range(n):
for j in range(n):
n1 = all_channels[i]
n2 = all_channels[j]
total_eff += br_Ds[n1] * br_Ds[n2] * br[n1] * br[n2] * efficiency[i,j]
total_err += (br_Ds[n1] * br_Ds[n2] * br[n1] * br[n2] * errors[i,j])**2
return utils.format_error(total_eff*scale,total_err**.5*scale,exponent=-5)
示例7: message
def message(self,to,*args):
""" Receives a message from the ring """
try:
if args[0]=='GET':
return self.__get(to,args[1])
elif args[0]=='PUT':
return self.__put(to,args[1],args[2])
else:
return 'No such method: %s'%args[0]
except:
return utils.format_error()
示例8: parse_options
def parse_options():
_root = os.path.join(os.path.dirname(os.path.dirname(__file__)),"")
_settings = os.path.join(_root, "settings.py")
try:
parse_config_file(_settings)
logging.info("Using settings.py as default settings.")
print "Using settings.py as default settings."
except Exception as e:
import traceback
print (utils.format_error())
logging.error("No any default settings, are you sure? Exception: %s" % e)
parse_command_line()
示例9: _complete_read
def _complete_read(self):
""" Reads the contents of the file."""
s = []
try:
# read and return the whole file
for p in self.parts:
logger.info('Reading part ' + p)
uri = uri_from_string(p)
d = dfs.dht.get(uri.get_hd(),uri.nick)
# TODO: do not decrypt now, but in the actual read
if self.crypter: d = self.crypter.decrypt(d)
s.append(d)
s=''.join(s)
self.eof = True
# TODO: check the file hashing before returning
return s[0:self.filelength]
except:
raise IOError('Cannot read: %s'%utils.format_error())
示例10: __next
def __next(self,to):
""" route a message to the point 'to' """
try:
if type(to)==tuple:
p=xmlrpclib.ServerProxy("http://%s:%d"%to)
else:
# TODO: improve the routing. This one just circle the
# message in the ring
if self.contacted.has_key(to):
na=self.contacted[to]
else:
na=self.contacted[self.next]
p=xmlrpclib.ServerProxy('http://%s:%d'%(na[0],na[1]))
return p
except:
if type(to)==str:
st=to
else:
st='%s:%d'%(to[0],to[1])
logger.warn("%s: error routing message to %s"%(self.id,st))
raise IOError(utils.format_error())
示例11: error_handler
def error_handler(self, e, request, meth, em_format):
"""
Override this method to add handling of errors customized for your
needs
"""
if isinstance(e, FormValidationError):
return self.form_validation_response(e)
elif isinstance(e, Http404):
return rc.NOT_FOUND
elif isinstance(e, HttpStatusCode):
return e.response
else:
"""
On errors (like code errors), we'd like to be able to
give crash reports to both admins and also the calling
user. There's two setting parameters for this:
Parameters::
- `PISTON_EMAIL_ERRORS`: Will send a Django formatted
error email to people in `settings.ADMINS`.
- `PISTON_DISPLAY_ERRORS`: Will return a simple traceback
to the caller, so he can tell you what error they got.
If `PISTON_DISPLAY_ERRORS` is not enabled, the caller will
receive a basic "500 Internal Server Error" message.
"""
exc_type, exc_value, tb = sys.exc_info()
rep = ExceptionReporter(request, exc_type, exc_value, tb.tb_next)
if self.email_errors:
self.email_exception(rep)
if self.display_errors:
return HttpResponseServerError(
format_error('\n'.join(rep.format_exception())))
else:
raise
示例12: f_Y
],
"SVD2": [
("signal_corr_svd2_Mbc_mean", "\Delta\mu(\mbc)"),
("signal_corr_svd2_Mbc_sigma", "\delta\sigma(\mbc)"),
("signal_corr_svd2_dE_mean", "\Delta\mu(\de)"),
("signal_corr_svd2_dE_sigma", "\delta\sigma(\de)"),
("signal_corr_svd2_rbin1", "\delta f_Y(rbin0)"),
("signal_corr_svd2_rbin2", "\delta f_Y(rbin1)"),
("signal_corr_svd2_rbin3", "\delta f_Y(rbin2)"),
("signal_corr_svd2_rbin4", "\delta f_Y(rbin3)"),
("signal_corr_svd2_rbin5", "\delta f_Y(rbin4)"),
("signal_corr_svd2_rbin6", "\delta f_Y(rbin5)"),
]
}
params = dspdsmks.Parameters()
params.load(sys.argv[1])
for svd, names in sorted(fields.items()):
print r"""\begin{tabular}{LRCL}
\toprule
Name&Value\\
\midrule"""
for p,t in names:
print r" {0} & {1}\\" .format(t, utils.format_error(params(p).value, params(p).error, align=True))
print r""" \bottomrule
\end{tabular}"""
示例13: run_jobs
cpv_result = [jc_result, js1_result, js2_result, bl_result, bbar_svd1_result, bbar_svd2_result]
cpv_pull = [root.TH1D(e.GetName()+"_pull","",100,-5,5) for e in cpv_result]
cpv_params = ["signal_dt_Jc", "signal_dt_Js1", "signal_dt_Js2", "signal_dt_blifetime", "yield_bbar_svd1", "yield_bbar_svd2"]
cpv_input = [params(e).value for e in cpv_params]
for parfile in run_jobs(False, True):
if not os.path.exists(parfile): continue
params.load(parfile)
br = params("yield_signal_br").value
br_error = params("yield_signal_br").error
br_result.Fill(br)
br_pull.Fill((br-utils.br)/br_error)
for i,p in enumerate([params(e) for e in cpv_params]):
cpv_result[i].Fill(p.value)
cpv_pull[i].Fill((p.value-cpv_input[i])/p.error)
a,m,s = draw_toyMC(br_result, r"fit results, input=$%s$" % utils.format_error(utils.br, precision=1), "$\mathcal{B}(\ddk)$", exponent=-3, ylabel=r"Entries / \num{%s}" % br_result.GetBinWidth(1))
a.set_ylim(0, br_result.GetMaximum()*1.5)
draw_toyMC(br_pull,"pull distribution", xlabel=r"Pull($\mathcal{B}(\ddk)$)", ylabel="Entries / %s" % br_pull.GetBinWidth(1))
names = [r"$J_C/J_0$", r"$(2J_{s1}/J_0) \sin(2\phi_1)$", r"$(2J_{s2}/J_0) \cos(2\phi_1)$",r"$\tau / ps$","m1","m2"]
for i,name in enumerate(names):
hist = cpv_result[i]
pull = cpv_pull[i]
draw_toyMC(hist, r"fit results, input=$%.3g$" % cpv_input[i], xlabel=name, ylabel="Entries / %s" % hist.GetBinWidth(1))
draw_toyMC(pull, r"pull distribution", xlabel="Pull(%s)" % name, ylabel="Entries / %s" % pull.GetBinWidth(1))
r2mpl.save_all("toymc/toymc-%s" % toyname, png=False, single_pdf=True)
示例14: HandlerMethod
except TypeError, e:
result = rc.BAD_REQUEST
hm = HandlerMethod(meth)
sig = hm.get_signature()
msg = 'Method signature does not match.\n\n'
if sig:
msg += 'Signature should be: %s' % sig
else:
msg += 'Resource does not expect any parameters.'
if self.display_errors:
msg += '\n\nException was: %s' % str(e)
result.content = format_error(msg)
except HttpStatusCode, e:
#result = e ## why is this being passed on and not just dealt with now?
return e.response
except Exception, e:
"""
On errors (like code errors), we'd like to be able to
give crash reports to both admins and also the calling
user. There's two setting parameters for this:
Parameters::
- `PISTON_EMAIL_ERRORS`: Will send a Django formatted
error email to people in `settings.ADMINS`.
- `PISTON_DISPLAY_ERRORS`: Will return a simple traceback
to the caller, so he can tell you what error they got.
示例15: ExceptionReporter
error email to people in `settings.ADMINS`.
- `FULCRUM_DISPLAY_ERRORS`: Will return a simple traceback
to the caller, so he can tell you what error they got.
If `FULCRUM_DISPLAY_ERRORS` is not enabled, the caller will
receive a basic "500 Internal Server Error" message.
"""
exc_type, exc_value, tb = sys.exc_info()
rep = ExceptionReporter(request, exc_type, exc_value, tb.tb_next)
if self.email_errors:
self.email_exception(rep)
if self.display_errors:
return HttpResponseServerError(
format_error('\n'.join(rep.format_exception())))
else:
raise
# Return serialized data
emitter, ct = Emitter.get(em_format)
srl = emitter(result, recurse_level, typemapper, handler, handler.fields, anonymous)
try:
"""
Decide whether or not we want a generator here,
or we just want to buffer up the entire result
before sending it to the client. Won't matter for
smaller datasets, but larger will have an impact.
"""
if self.stream: stream = srl.stream_render(request)