本文整理汇总了Python中util.plural函数的典型用法代码示例。如果您正苦于以下问题:Python plural函数的具体用法?Python plural怎么用?Python plural使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了plural函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: run_merge
def run_merge(filenames):
"""Merges all Skype databases to a new database."""
dbs = [skypedata.SkypeDatabase(f) for f in filenames]
db_base = dbs.pop()
counts = collections.defaultdict(lambda: collections.defaultdict(int))
postbacks = Queue.Queue()
postfunc = lambda r: postbacks.put(r)
worker = workers.MergeThread(postfunc)
name, ext = os.path.splitext(os.path.split(db_base.filename)[-1])
now = datetime.datetime.now().strftime("%Y%m%d")
filename_final = util.unique_path("%s.merged.%s%s" % (name, now, ext))
print("Creating %s, using %s as base." % (filename_final, db_base))
shutil.copyfile(db_base.filename, filename_final)
db2 = skypedata.SkypeDatabase(filename_final)
chats2 = db2.get_conversations()
db2.get_conversations_stats(chats2)
for db1 in dbs:
chats = db1.get_conversations()
db1.get_conversations_stats(chats)
bar_total = sum(c["message_count"] for c in chats)
bar_text = " Processing %.*s.." % (30, db1)
bar = ProgressBar(max=bar_total, afterword=bar_text)
bar.start()
args = {"db1": db1, "db2": db2, "chats": chats,
"type": "diff_merge_left"}
worker.work(args)
while True:
result = postbacks.get()
if "error" in result:
print("Error merging %s:\n\n%s" % (db1, result["error"]))
worker = None # Signal for global break
break # break while True
if "done" in result:
break # break while True
if "diff" in result:
counts[db1]["chats"] += 1
counts[db1]["msgs"] += len(result["diff"]["messages"])
msgcounts = sum(c["message_count"] for c in result["chats"])
bar.update(bar.value + msgcounts)
if result["output"]:
log(result["output"])
if not worker:
break # break for db1 in dbs
bar.stop()
bar.afterword = " Processed %s." % db1
bar.update(bar_total)
print
if not counts:
print("Nothing new to merge.")
db2.close()
os.unlink(filename_final)
else:
for db1 in dbs:
print("Merged %s in %s from %s." %
(util.plural("message", counts[db1]["msgs"]),
util.plural("chat", counts[db1]["chats"]), db1))
print("Merge into %s complete." % db2)
开发者ID:barneycarroll,项目名称:Skyperious,代码行数:60,代码来源:main.py
示例2: work_diff_left
def work_diff_left(self, params):
"""
Worker branch that compares all chats on the left side for differences,
posting results back to application.
"""
# {"output": "html result for db1, db2",
# "index": currently processed chat index,
# "chats": [differing chats in db1]}
result = {"output": "", "chats": [],
"params": params, "index": 0, "type": "diff_left"}
db1, db2 = params["db1"], params["db2"]
chats1 = params.get("chats") or db1.get_conversations()
chats2 = db2.get_conversations()
c1map = dict((c["identity"], c) for c in chats1)
c2map = dict((c["identity"], c) for c in chats2)
compared = []
for c1 in chats1:
c2 = c2map.get(c1["identity"])
c = c1.copy()
c["messages1"] = c1["message_count"] or 0
c["messages2"] = c2["message_count"] or 0 if c2 else 0
c["c1"], c["c2"] = c1, c2
compared.append(c)
compared.sort(key=lambda x: x["title"].lower())
info_template = step.Template(templates.DIFF_RESULT_ITEM)
for index, chat in enumerate(compared):
diff = self.get_chat_diff_left(chat, db1, db2)
if self._stop_work:
break # break for index, chat in enumerate(compared)
if diff["messages"] \
or (chat["message_count"] and diff["participants"]):
new_chat = not chat["c2"]
newstr = "" if new_chat else "new "
info = info_template.expand(chat=chat)
if new_chat:
info += " - new chat"
if diff["messages"]:
info += ", %s" % util.plural("%smessage" % newstr,
diff["messages"])
else:
info += ", no messages"
if diff["participants"] and not new_chat:
info += ", %s" % (
util.plural("%sparticipant" % newstr,
diff["participants"]))
info += ".<br />"
result["output"] += info
result["chats"].append({"chat": chat, "diff": diff})
result["index"] = index
if not self._drop_results:
if index < len(compared) - 1:
result["status"] = ("Scanning %s." %
compared[index + 1]["title_long_lc"])
self.postback(result)
result = {"output": "", "chats": [], "index": index,
"params": params, "type": "diff_left"}
if not self._drop_results:
result["done"] = True
self.postback(result)
开发者ID:sidtechnical,项目名称:Skyperious,代码行数:60,代码来源:workers.py
示例3: check_status_lines
def check_status_lines(cs):
check_lines = [" " + cs.name, " " + "-" * len(cs.name)]
if cs.init_failed_error:
check_lines.append(
" - initialize check class [%s]: %s" % (style(STATUS_ERROR, "red"), repr(cs.init_failed_error))
)
if cs.init_failed_traceback:
check_lines.extend(" " + line for line in cs.init_failed_traceback.split("\n"))
else:
for s in cs.instance_statuses:
c = "green"
if s.has_warnings():
c = "yellow"
if s.has_error():
c = "red"
line = " - instance #%s [%s]" % (s.instance_id, style(s.status, c))
if s.has_error():
line += u": %s" % s.error
if s.metric_count is not None:
line += " collected %s metrics" % s.metric_count
if s.instance_check_stats is not None:
line += " Last run duration: %s" % s.instance_check_stats.get("run_time")
check_lines.append(line)
if s.has_warnings():
for warning in s.warnings:
warn = warning.split("\n")
if not len(warn):
continue
check_lines.append(u" %s: %s" % (style("Warning", "yellow"), warn[0]))
check_lines.extend(u" %s" % l for l in warn[1:])
if s.traceback is not None:
check_lines.extend(" " + line for line in s.traceback.split("\n"))
check_lines += [
" - Collected %s metric%s, %s event%s & %s service check%s"
% (
cs.metric_count,
plural(cs.metric_count),
cs.event_count,
plural(cs.event_count),
cs.service_check_count,
plural(cs.service_check_count),
)
]
if cs.check_stats is not None:
check_lines += [" - Stats: %s" % pretty_statistics(cs.check_stats)]
if cs.library_versions is not None:
check_lines += [" - Dependencies:"]
for library, version in cs.library_versions.iteritems():
check_lines += [" - %s: %s" % (library, version)]
check_lines += [""]
return check_lines
开发者ID:dadicool,项目名称:dd-agent,代码行数:57,代码来源:check_status.py
示例4: work_merge
def work_merge(self, params):
"""
Worker branch that merges differences given in params, posting progress
back to application.
"""
error, e = None, None
db1, db2, info = params["db1"], params["db2"], params["info"]
chats, contacts = params["chats"], params["contacts"]
source, contactgroups = params["source"], params["contactgroups"]
count_messages = 0
count_participants = 0
try:
if contacts:
content = util.plural("contact", contacts)
self.postback({"type": "merge", "gauge": 0,
"message": "Merging %s." % content})
db2.insert_contacts(contacts, db1)
self.postback({"type": "merge", "gauge": 100,
"message": "Merged %s." % content})
if contactgroups:
content = util.plural("contact group", contactgroups)
self.postback({"type": "merge", "gauge": 0,
"message": "Merging %s." % content})
db2.replace_contactgroups(contactgroups, db1)
self.postback({"type": "merge", "gauge": 100,
"message": "Merged %s." % content})
for index, chat_data in enumerate(chats):
if self._stop_work:
break # break for i, chat_data in enumerate(chats)
chat1 = chat_data["chat"]["c2" if source else "c1"]
chat2 = chat_data["chat"]["c1" if source else "c2"]
step = -1 if source else 1
messages1, messages2 = chat_data["diff"]["messages"][::step]
participants, participants2 = \
chat_data["diff"]["participants"][::step]
if not chat2:
chat2 = chat1.copy()
chat_data["chat"]["c1" if source else "c2"] = chat2
chat2["id"] = db2.insert_chat(chat2, db1)
if participants:
db2.insert_participants(chat2, participants, db1)
count_participants += len(participants)
if messages1:
db2.insert_messages(chat2, messages1, db1, chat1,
self.yield_ui, self.REFRESH_COUNT)
count_messages += len(messages1)
self.postback({"type": "merge", "index": index,
"params": params})
except Exception, e:
error = traceback.format_exc()
开发者ID:alb-i986,项目名称:Skyperious,代码行数:50,代码来源:workers.py
示例5: run_diff
def run_diff(filename1, filename2):
"""Compares the first database for changes with the second."""
if os.path.realpath(filename1) == os.path.realpath(filename2):
output("Error: cannot compare %s with itself." % filename1)
return
db1, db2 = map(skypedata.SkypeDatabase, [filename1, filename2])
counts = collections.defaultdict(lambda: collections.defaultdict(int))
postbacks = Queue.Queue()
bar_text = "%.*s.." % (50, " Scanning %s vs %s" % (db1, db2))
bar = ProgressBar(afterword=bar_text)
bar.start()
chats1, chats2 = db1.get_conversations(), db2.get_conversations()
db1.get_conversations_stats(chats1), db2.get_conversations_stats(chats2)
args = {"db1": db1, "db2": db2, "chats": chats1, "type": "diff_left"}
worker = workers.MergeThread(postbacks.put)
try:
worker.work(args)
while True:
result = postbacks.get()
if "error" in result:
output("Error scanning %s and %s:\n\n%s" %
(db1, db2, result["error"]))
break # break while True
if "done" in result:
break # break while True
if "chats" in result and result["chats"]:
counts[db1]["chats"] += 1
msgs = len(result["chats"][0]["diff"]["messages"])
msgs_text = util.plural("new message", msgs)
contacts_text = util.plural("new participant",
result["chats"][0]["diff"]["participants"])
text = ", ".join(filter(None, [msgs_text, contacts_text]))
bar.afterword = (" %s, %s." % (result["chats"][0]["chat"]["title"],
text))
counts[db1]["msgs"] += msgs
if "index" in result:
bar.max = result["count"]
bar.update(result["index"])
if result.get("output"):
log(result["output"])
finally:
worker and (worker.stop(), worker.join())
bar.stop()
bar.afterword = " Scanned %s and %s." % (db1, db2)
bar.update(bar.max)
output()
开发者ID:Avatarchik,项目名称:Skyperious,代码行数:49,代码来源:main.py
示例6: tr_error
def tr_error(self, tr):
self._running_flushes -= 1
self._finished_flushes += 1
tr.inc_error_count()
tr.compute_next_flush(self._MAX_WAIT_FOR_REPLAY)
log.warn("Transaction %d in error (%s error%s), it will be replayed after %s",
tr.get_id(),
tr.get_error_count(),
plural(tr.get_error_count()),
tr.get_next_flush())
self._endpoints_errors[tr._endpoint] = self._endpoints_errors.get(tr._endpoint, 0) + 1
# Endpoint failed too many times, it's probably an enpoint issue
# Let's avoid blocking on it
if self._endpoints_errors[tr._endpoint] == self._MAX_ENDPOINT_ERRORS:
new_trs_to_flush = []
for transaction in self._trs_to_flush:
if transaction._endpoint != tr._endpoint:
new_trs_to_flush.append(transaction)
else:
transaction.compute_next_flush(self._MAX_WAIT_FOR_REPLAY)
log.debug('Endpoint %s seems down, removed %s transaction from current flush',
tr._endpoint,
len(self._trs_to_flush) - len(new_trs_to_flush))
self._trs_to_flush = new_trs_to_flush
开发者ID:alq666,项目名称:dd-agent,代码行数:25,代码来源:transaction.py
示例7: run_hooks_for
def run_hooks_for(trigger):
from sys import exit
from os.path import sep
from subprocess import call
global _triggers
if trigger not in _triggers:
raise ValueError("unknown trigger: '" + str(trigger) + "'")
hooks = list(set(_hooks[trigger]) - set(_hooks_done[trigger]))
num_done = 0
if len(hooks) > 0:
util.info("running hooks for trigger '" + str(trigger) + "'")
for fname in hooks:
rv = call(config.hooks_dir + sep + fname, env=_create_env())
_hooks_done[trigger].append(fname)
num_done += 1
if rv != 0:
util.error("hook '" + str(fname) + "' exited abnormally")
util.exit(util.ERR_ABNORMAL_HOOK_EXIT)
util.info("successfully ran " + str(num_done) + " " + \
util.plural('hook', num_done))
开发者ID:abreen,项目名称:socrates.py,代码行数:26,代码来源:hooks.py
示例8: tr_error
def tr_error(self, tr):
tr.inc_error_count()
tr.compute_next_flush(self._MAX_WAIT_FOR_REPLAY)
log.warn(
"Transaction %d in error (%s error%s), it will be replayed after %s"
% (tr.get_id(), tr.get_error_count(), plural(tr.get_error_count()), tr.get_next_flush())
)
开发者ID:ermandoser,项目名称:dd-agent,代码行数:7,代码来源:transaction.py
示例9: flush
def flush(self):
if self._trs_to_flush is not None:
log.debug("A flush is already in progress, not doing anything")
return
to_flush = []
# Do we have something to do ?
now = datetime.now()
for tr in self._transactions:
if tr.time_to_flush(now):
to_flush.append(tr)
count = len(to_flush)
should_log = (
self._flush_count + 1 <= FLUSH_LOGGING_INITIAL or (self._flush_count + 1) % FLUSH_LOGGING_PERIOD == 0
)
if count > 0:
if should_log:
log.info(
"Flushing %s transaction%s during flush #%s" % (count, plural(count), str(self._flush_count + 1))
)
else:
log.debug(
"Flushing %s transaction%s during flush #%s" % (count, plural(count), str(self._flush_count + 1))
)
self._trs_to_flush = to_flush
self.flush_next()
else:
if should_log:
log.info("No transaction to flush during flush #%s" % str(self._flush_count + 1))
else:
log.debug("No transaction to flush during flush #%s" % str(self._flush_count + 1))
if self._flush_count + 1 == FLUSH_LOGGING_INITIAL:
log.info("First flushes done, next flushes will be logged every %s flushes." % FLUSH_LOGGING_PERIOD)
self._flush_count += 1
ForwarderStatus(
queue_length=self._total_count,
queue_size=self._total_size,
flush_count=self._flush_count,
transactions_received=self._transactions_received,
transactions_flushed=self._transactions_flushed,
).persist()
开发者ID:ermandoser,项目名称:dd-agent,代码行数:47,代码来源:transaction.py
示例10: export_chats
def export_chats(chats, path, format, db, messages=None, skip=True, progress=None):
"""
Exports the specified chats from the database under path.
@param chats list of chat dicts, as returned from SkypeDatabase
@param path full path of directory where to save
@param format export format (html|txt|xlsx|csv|filename.ext).
If format is filename.ext, a single file is created:
for single chat exports and multi chat XLSX exports
(for multi-file exports, filenames are named by chats).
@param db SkypeDatabase instance
@param messages list messages to export if a single chat
@param skip whether to skip chats with no messages
@param progress function called before exporting each chat, with the
number of messages exported so far
@return (list of exported filenames, number of chats exported)
"""
files, count = [], 0
def make_filename(chat):
if len(format) > 4: # Filename already given in format
filename = os.path.join(path, format)
else:
args = collections.defaultdict(str); args.update(chat)
filename = "%s.%s" % (conf.ExportChatTemplate % args, format)
filename = os.path.join(path, util.safe_filename(filename))
filename = util.unique_path(filename)
return filename
main.logstatus("Exporting %s from %s %sto %s.",
util.plural("chat", chats), db.filename,
"" if len(format) > 4 else "as %s " % format.upper(),
format if len(format) > 4 else path)
if format.lower().endswith(".xlsx"):
filename = make_filename(chats[0])
count = export_chats_xlsx(chats, filename, db, messages, skip, progress)
files.append(filename)
else:
if not os.path.exists(path):
os.makedirs(path)
export_func = (export_chats_xlsx if format.lower().endswith("xlsx")
else export_chat_csv if format.lower().endswith("csv")
else export_chat_template)
message_count = 0
for chat in chats:
if skip and not messages and not chat["message_count"]:
main.log("Skipping exporting %s: no messages.",
chat["title_long_lc"])
if progress: progress(message_count)
continue # continue for chat in chats
main.status("Exporting %s.", chat["title_long_lc"])
if progress: progress(message_count)
filename = make_filename(chat)
msgs = messages or db.get_messages(chat)
chatarg = [chat] if "xlsx" == format.lower() else chat
export_func(chatarg, filename, db, msgs)
message_count += chat["message_count"]
files.append(filename)
count = len(files)
return (files, count)
开发者ID:B00StER,项目名称:Skyperious,代码行数:59,代码来源:export.py
示例11: run_diff
def run_diff(filename1, filename2):
"""Compares the first database for changes with the second."""
if os.path.realpath(filename1) == os.path.realpath(filename2):
print("Error: cannot compare %s with itself." % filename1)
return
db1, db2 = map(skypedata.SkypeDatabase, [filename1, filename2])
counts = collections.defaultdict(lambda: collections.defaultdict(int))
postbacks = Queue.Queue()
postfunc = lambda r: postbacks.put(r)
worker = workers.MergeThread(postfunc)
chats1, chats2 = db1.get_conversations(), db2.get_conversations()
db1.get_conversations_stats(chats1), db2.get_conversations_stats(chats2)
for db in [db1, db2]:
db.get_conversations_stats(db.get_conversations())
bar_total = sum(c["message_count"] for c in chats1)
bar_text = "%.*s.." % (50, " Scanning %s vs %s" % (db1, db2))
bar = ProgressBar(max=bar_total, afterword=bar_text)
bar.start()
args = {"db1": db1, "db2": db2, "chats": chats1, "type": "diff_left"}
worker.work(args)
while True:
result = postbacks.get()
if "error" in result:
print("Error scanning %s and %s:\n\n%s" %
(db1, db2, result["error"]))
worker = None # Signal for global break
break # break while True
if "done" in result:
break # break while True
if "chats" in result and result["chats"]:
counts[db1]["chats"] += 1
msgs = len(result["chats"][0]["diff"]["messages"])
msgs_text = util.plural("new message", msgs)
contacts_text = util.plural("new participant",
result["chats"][0]["diff"]["participants"])
text = ", ".join(filter(None, [msgs_text, contacts_text]))
print("%s, %s." % (result["chats"][0]["chat"]["title_long"], text))
counts[db1]["msgs"] += msgs
bar.update(bar.value + result["chats"][0]["chat"]["message_count"])
if result["output"]:
log(result["output"])
bar.stop()
bar.afterword = " Scanned %s and %s." % (db1, db2)
bar.update(bar_total)
print
开发者ID:barneycarroll,项目名称:Skyperious,代码行数:46,代码来源:main.py
示例12: flush
def flush(self):
if self._trs_to_flush is not None:
log.debug("A flush is already in progress, not doing anything")
return
to_flush = []
# Do we have something to do ?
now = datetime.utcnow()
for tr in self._transactions:
if tr.time_to_flush(now):
to_flush.append(tr)
count = len(to_flush)
should_log = self._flush_count + 1 <= FLUSH_LOGGING_INITIAL or (self._flush_count + 1) % FLUSH_LOGGING_PERIOD == 0
if count > 0:
if should_log:
log.info("Flushing %s transaction%s during flush #%s" % (count,plural(count), str(self._flush_count + 1)))
else:
log.debug("Flushing %s transaction%s during flush #%s" % (count,plural(count), str(self._flush_count + 1)))
self._endpoints_errors = {}
self._finished_flushes = 0
# We sort LIFO-style, taking into account errors
self._trs_to_flush = sorted(to_flush, key=lambda tr: (- tr._error_count, tr._id))
self._flush_time = datetime.utcnow()
self.flush_next()
else:
if should_log:
log.info("No transaction to flush during flush #%s" % str(self._flush_count + 1))
else:
log.debug("No transaction to flush during flush #%s" % str(self._flush_count + 1))
if self._flush_count + 1 == FLUSH_LOGGING_INITIAL:
log.info("First flushes done, next flushes will be logged every %s flushes." % FLUSH_LOGGING_PERIOD)
self._flush_count += 1
ForwarderStatus(
queue_length=self._total_count,
queue_size=self._total_size,
flush_count=self._flush_count,
transactions_received=self._transactions_received,
transactions_flushed=self._transactions_flushed,
transactions_rejected=self._transactions_rejected).persist()
开发者ID:alq666,项目名称:dd-agent,代码行数:46,代码来源:transaction.py
示例13: chooseTracks
def chooseTracks(self, number, exclude, completion, traceCallback=None,
tags=None):
self._logger.debug("Selecting " + str(number) + " track" +
util.plural(number) + ".")
mycompletion = (lambda thisCallback, trackIDs, completion=completion:
self._chooseTracksCompletion(trackIDs, completion,
thisCallback))
self._chooseTrackIDs(
number, exclude, mycompletion, traceCallback, tags)
开发者ID:erbridge,项目名称:NQr,代码行数:9,代码来源:randomizer.py
示例14: to_templated_secular_display
def to_templated_secular_display(self,fp,group,type= 'lecture'):
gt = GroupTemplate(None)
gt.add_patterns(fp)
gt.calculate_reduction(True)
out = []
for (_,_,(pattern,mult)) in gt.get_patterns_raw(False):
if pattern is None:
# just multiplier, should be just "x lectures"
row = "%d %s, %s" % (mult,util.plural(type),gt.template) # XXX proper plurals
elif mult is None:
# traditional pattern, expand codes sensibly
row = "%s %s" % (util.plural(type),self.atoms_to_secular(fp.patterns(),True))
else:
# start date and multiplier
pp = copy.deepcopy(gt.template)
pp.setAllYear()
row = "%s %s, starting on %s, %s" % (mult,util.plural(type),self.atoms_to_secular([pattern],False),pp)
out.append(row)
prefix = ''
if group is not None:
prefix = "%s term, " % term_names[group.term]
return prefix+", ".join(out)
开发者ID:ieb,项目名称:timetables,代码行数:22,代码来源:year.py
示例15: run_export
def run_export(filenames, format):
"""Exports the specified databases in specified format."""
dbs = [skypedata.SkypeDatabase(f) for f in filenames]
is_xlsx_single = ("xlsx_single" == format)
for db in dbs:
formatargs = collections.defaultdict(str)
formatargs["skypename"] = os.path.basename(db.filename)
formatargs.update(db.account or {})
basename = util.safe_filename(conf.ExportDbTemplate % formatargs)
dbstr = "from %s " % db if len(dbs) != 1 else ""
if is_xlsx_single:
export_dir = os.getcwd()
filename = util.unique_path("%s.xlsx" % basename)
else:
export_dir = util.unique_path(os.path.join(os.getcwd(), basename))
filename = format
target = filename if is_xlsx_single else export_dir
try:
print("Exporting as %s %sto %s." %
(format[:4].upper(), dbstr, target))
chats = sorted(db.get_conversations(),
key=lambda x: x["title"].lower())
db.get_conversations_stats(chats)
bar_total = sum(c["message_count"] for c in chats)
bartext = " Exporting %.*s.." % (30, db.filename) # Enforce width
bar = ProgressBar(max=bar_total, afterword=bartext)
bar.start()
result = export.export_chats(chats, export_dir, filename, db,
progress=bar.update)
files, count = result
bar.stop()
if count:
bar.afterword = " Exported %s to %s. " % (db, target)
bar.update(bar_total)
print()
log("Exported %s %sto %s as %s.", util.plural("chat", count),
dbstr, target, format)
else:
print("\nNo messages to export%s." %
("" if len(dbs) == 1 else " from %s" % db))
os.unlink(filename) if is_xlsx_single else os.rmdir(export_dir)
except Exception as e:
print("Error exporting chats: %s\n\n%s" %
(e, traceback.format_exc()))
开发者ID:B00StER,项目名称:Skyperious,代码行数:45,代码来源:main.py
示例16: run
def run(self, path, print_file=True):
from functools import reduce
import prompt
if print_file and self.print_file:
_print_file(path)
util.info("description: " + self.description)
if type(self.deduction) is int:
choices = ["do not take this deduction",
"take this deduction (-{} points)".format(
self.deduction)]
got = prompt.prompt(choices, '1')
if got == [1]:
return {'deduction': self.deduction,
'description': self.description}
else:
util.info("taking no points")
return None
elif type(self.deduction) is list:
choices = ["{} (-{} {})".format(y, x, util.plural("point", x)) for
x, y in self.deduction]
got = prompt.prompt(choices, self.deduction_mode)
total_deducted = sum(map(lambda x: self.deduction[x][0], got))
if total_deducted > 0:
deductions = []
for s in got:
if self.deduction[s][0] > 0:
d = {'deduction': self.deduction[s][0],
'description': self.deduction[s][1]}
deductions.append(d)
return {'description': self.description + ':',
'subresults': deductions}
else:
util.info("taking no points")
return None
开发者ID:abreen,项目名称:socrates.py,代码行数:42,代码来源:plainfile.py
示例17: __should_fail
def __should_fail(self, result):
"""Called before an eval test is about to be failed, but the criteria
specifies that a human should confirm the failure before taking
any points. If this method returns True, the points are ultimately
taken.
"""
import sys
from grader import write_results
from prompt import prompt
util.warning("about to fail a test")
write_results(sys.stdout, [result])
points = result['deduction']
s = util.plural("point", points)
fail_msg = "fail this test (-{} {})".format(points, s)
choices = [fail_msg, "do not fail this test"]
return prompt(choices, '1') == [0]
开发者ID:abreen,项目名称:socrates.py,代码行数:20,代码来源:pythonfile.py
示例18: run
def run(self, path):
import os
from functools import reduce
import prompt
_print_file(path)
sprint("reviewing '{}' (in directory '{}')".format(
path, os.getcwd()))
sprint("description: " + self.description)
if type(self.deduction) is int:
choices = ["do not take this deduction",
"take this deduction (-{} points)".format(
self.deduction)]
got = prompt.prompt(choices, '1')
if got == [1]:
return {'deduction': self.deduction,
'description': self.description}
else:
sprint("taking no points")
return None
elif type(self.deduction) is list:
choices = ["{} (-{} {})".format(y, x, plural("point", x)) for
x, y in self.deduction]
got = prompt.prompt(choices, self.deduction_mode)
if sum(map(lambda x: self.deduction[x][0], got)) > 0:
deductions = []
for s in got:
if self.deduction[s][0] > 0:
d = {'deduction': self.deduction[s][0],
'description': self.deduction[s][1]}
deductions.append(d)
return deductions
else:
sprint("taking no points")
return None
开发者ID:asafer,项目名称:socrates,代码行数:41,代码来源:plainfile.py
示例19: _relation_repr
def _relation_repr(cls, rel):
target = rel.argument
if target and inspect.isfunction(target):
target = target()
if isinstance(target, Mapper):
target = target.class_
target = target.__name__
primaryjoin = ''
lookup = mtl()
foo = rel.key
if rel.primaryjoin is not None and hasattr(rel.primaryjoin, 'right'):
right_lookup = lookup.get(rel.primaryjoin.right.table.name, '%s.c' % rel.primaryjoin.right.table.name)
left_lookup = lookup.get(rel.primaryjoin.left.table.name, '%s.c' % rel.primaryjoin.left.table.name)
primaryjoin = ", primaryjoin='%s.%s==%s.%s'" % (left_lookup,
rel.primaryjoin.left.name,
right_lookup,
rel.primaryjoin.right.name)
elif hasattr(rel, '_as_string'):
primaryjoin = ', primaryjoin="%s"' % rel._as_string
secondary = ''
secondaryjoin = ''
if rel.secondary is not None:
"""
**HACK**: If there is a secondary relationship like between Venue, Event, and Event_Type, then I'm only
going show a primary relationship.
"Events = relationship('Event', primaryjoin='Venue.id==Event.venue_id')" and not
"Event_Types = relation('EventType', primaryjoin='Venue.id==Event.venue_id', secondary=Event, secondaryjoin='Event.event_type_id==EventType.id')"
"""
if rel.secondary.name in self.table_model_dict:
target = self.table_model_dict[rel.secondary.name]
else:
target = self.find_new_name(singular(name2label(rel.secondary.name)), []) # **HACK**
secondary = ''
secondaryjoin = ''
foo = plural(rel.secondary.name)
backref = ''
# if rel.backref:
# backref=", backref='%s'"%rel.backref.key
return "%s = relationship('%s'%s%s%s%s)" % (foo, target, primaryjoin, secondary, secondaryjoin, backref)
开发者ID:LonghuaWan,项目名称:sqlautocode,代码行数:41,代码来源:declarative.py
|
请发表评论