rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
name, '", "'.join(choices), arg))
name, '", "'.join([repr(choice) for choice in choices]), arg))
def get_choice(request, arg, name=None, choices=[None]): """ For use with values returned from parse_quoted_separated or given as macro parameters, return a unicode string that must be in the choices given. None is a valid input and yields first of the valid choices. @param request: A request instance @param arg: The argument, may be None or a unicode string @param name: Name of the argument, for error messages @param choices: the possible choices @rtype: unicode or None @returns: the unicode string (or default value) """ assert isinstance(choices, (tuple, list)) if arg is None: return choices[0] elif not isinstance(arg, unicode): raise TypeError('Argument must be None or unicode') elif not arg in choices: _ = request.getText if name: raise ValueError( _('Argument "%s" must be one of "%s", not "%s"') % ( name, '", "'.join(choices), arg)) else: raise ValueError( _('Argument must be one of "%s", not "%s"') % ( '", "'.join(choices), arg)) return arg
'", "'.join(choices), arg))
'", "'.join([repr(choice) for choice in choices]), arg))
def get_choice(request, arg, name=None, choices=[None]): """ For use with values returned from parse_quoted_separated or given as macro parameters, return a unicode string that must be in the choices given. None is a valid input and yields first of the valid choices. @param request: A request instance @param arg: The argument, may be None or a unicode string @param name: Name of the argument, for error messages @param choices: the possible choices @rtype: unicode or None @returns: the unicode string (or default value) """ assert isinstance(choices, (tuple, list)) if arg is None: return choices[0] elif not isinstance(arg, unicode): raise TypeError('Argument must be None or unicode') elif not arg in choices: _ = request.getText if name: raise ValueError( _('Argument "%s" must be one of "%s", not "%s"') % ( name, '", "'.join(choices), arg)) else: raise ValueError( _('Argument must be one of "%s", not "%s"') % ( '", "'.join(choices), arg)) return arg
choices = [None] + list(default.argtype) return get_choice(request, value, name, choices)
return get_choice(request, value, name, list(default.argtype), default_none=True)
def _convert_arg(request, value, default, name=None): """ Using the get_* functions, convert argument to the type of the default if that is any of bool, int, long, float or unicode; if the default is the type itself then convert to that type (keeps None) or if the default is a list require one of the list items.
vector += "I:" + i[0] + "/"
vector += "I:" + inv[0] + "/"
def buildVector(base_metas): vector = "" avset = set(['Local', 'Network', 'Adjacent Network']) acset = set(['High', 'Medium', 'Low']) auset = set(['Multiple', 'Single', 'None']) ciaset = set(['None', 'Partial', 'Complete']) av = base_metas["Access Vector"][:1] avs = set(av) if len(avs) > 0 and avs <= avset: avv = av.pop() vector += "AV:" + avv[0] + "/" else: return None ac = base_metas["Access Complexity"][:1] acs = set(ac) if len(acs) > 0 and acs <= acset: acv = ac.pop() vector += "AC:" + acv[0] + "/" else: return None au = base_metas["Authentication"][:1] aus = set(au) if len(aus) > 0 and aus <= auset: auv = au.pop() vector += "Au:" + auv[0] + "/" else: return None c = base_metas["Confidentiality"][:1] cs = set(c) if len(cs) > 0 and cs <= ciaset: cv = c.pop() vector += "C:" + cv[0] + "/" else: vector += "C:C/" i = base_metas["Integrity"][:1] ins = set(c) if len(ins) > 0 and ins <= ciaset: inv = i.pop() vector += "I:" + i[0] + "/" else: vector += "I:C/" a = base_metas["Availability"][:1] avas = set(a) if len(avas) > 0 and avas <= ciaset: avav = a.pop() vector += "A:" + a[0] else: vector += "A:C" return vector
vector += "A:" + a[0]
vector += "A:" + avav[0]
def buildVector(base_metas): vector = "" avset = set(['Local', 'Network', 'Adjacent Network']) acset = set(['High', 'Medium', 'Low']) auset = set(['Multiple', 'Single', 'None']) ciaset = set(['None', 'Partial', 'Complete']) av = base_metas["Access Vector"][:1] avs = set(av) if len(avs) > 0 and avs <= avset: avv = av.pop() vector += "AV:" + avv[0] + "/" else: return None ac = base_metas["Access Complexity"][:1] acs = set(ac) if len(acs) > 0 and acs <= acset: acv = ac.pop() vector += "AC:" + acv[0] + "/" else: return None au = base_metas["Authentication"][:1] aus = set(au) if len(aus) > 0 and aus <= auset: auv = au.pop() vector += "Au:" + auv[0] + "/" else: return None c = base_metas["Confidentiality"][:1] cs = set(c) if len(cs) > 0 and cs <= ciaset: cv = c.pop() vector += "C:" + cv[0] + "/" else: vector += "C:C/" i = base_metas["Integrity"][:1] ins = set(c) if len(ins) > 0 and ins <= ciaset: inv = i.pop() vector += "I:" + i[0] + "/" else: vector += "I:C/" a = base_metas["Availability"][:1] avas = set(a) if len(avas) > 0 and avas <= ciaset: avav = a.pop() vector += "A:" + a[0] else: vector += "A:C" return vector
info('Lookig for pages in %s' % wikiname)
info('Looking for pages in %s' % wikiname)
def checking_loop(wiki): wikiname = wiki.host + ''.join(wiki.path.rsplit('?')[:-1]) while True: #Get all new history pages with pending status info('Lookig for pages in %s' % wikiname) picked_pages = wiki.getMeta('CategoryHistory, overallvalue=pending') info('Found %d pages' % len(picked_pages)) if not picked_pages: info('Sleeping') time.sleep(10) continue #go thgrough all new pages for page in picked_pages: info('%s: picked %s' % (wikiname, page)) tempdir = tempfile.mkdtemp() info("Created tempdir %s" % tempdir) os.chdir(tempdir) #change the status to picked wiki.setMeta(page, {'overallvalue' : ['picked']}, True) metas = picked_pages[page] user = metas['user'].single().strip('[]') # get the attachment filename from the file meta info('Writing files') codes = dict() for filename in metas['file']: attachment_file = removeLink(filename) #get the source code info("Fetching sourcode from %s" % attachment_file) try: code = wiki.getAttachment(page, attachment_file) except opencollab.wiki.WikiFault, e: if 'There was an error in the wiki side (Nonexisting attachment' in e.args[0]: code = '' else: raise # get rid of the _rev<number> in filenames codes[re.sub('(_rev\d+)', '', removeLink(filename))] = code revision = re.search('_rev(\d+)', removeLink(filename)).group(1) #if there is wrong amount of question page linksd, leave #the returned assignment as picked so that other #assignments can be checked. if len(metas['question']) != 1: error('Invalid meta data in %s! There we %d values!\n' % (page, len(metas['question']))) continue #get the question pagenmae question = metas['question'].single(None) if not question: error('NO QUESTION PAGE IN HISTORY %s!' % page) continue question = question.strip('[]') #find associataed answerpages answer_pages = wiki.getMeta(question +'/options').values()[0]['answer'] info("Found %d answer pages" % len(answer_pages)) regex = re.compile('{{{\s*(.*)\s?}}}', re.DOTALL) wrong = list() right = list() outputs = list() for answer_page in [x.strip('[]') for x in answer_pages]: info('getting answers from %s' % answer_page) answer_meta = wiki.getMeta(answer_page).values()[0] testname = answer_meta['testname'].single() outputpage = None inputpage = None if 'output' in answer_meta: outputpage = answer_meta['output'].single().strip('[]') outfilesatt = wiki.listAttachments if 'input' in answer_meta: inputpage = answer_meta['input'].single().strip('[]') try: args = answer_meta['parameters'].single() except ValueError: error('No params!') continue input = '' input_files = dict() if inputpage: content = wiki.getPage(inputpage) input = regex.search(content).group(1) input_meta = wiki.getMeta(inputpage) filelist = input_meta[inputpage]['file'] for attachment in filelist: filename = removeLink(attachment) try: content = wiki.getAttachment(inputpage, filename) except opencollab.wiki.WikiFault, error_message: if "There was an error in the wiki side (Nonexisting attachment:" in error_message: content = '' else: raise input_files[filename] = content output = '' if outputpage: content = wiki.getPage(outputpage) output = regex.search(content).group(1) output_meta = wiki.getMeta(outputpage) # get output files output_files = dict() filelist = output_meta[outputpage]['file'] for attachment in filelist: filename = removeLink(attachment) content = wiki.getAttachment(outputpage, filename) output_files[filename] = content info('Running test') stu_output, stu_error, timeout, stu_files = run_test(codes, args, input, input_files, tempdir) #FIXME. Must check that editors in raippa do not add #newlines in output. If not. These lines can be removed stu_output = stu_error + stu_output if timeout: stu_output = stu_output + "\n***** TIMEOUT *****\nYOUR PROGRAM TIMED OUT!\n\n" if len(stu_output) > 1024*100: stu_output = "***** Your program produced more than 100kB of output data *****\n(Meaning that your program failed)\nPlease check your code before returning it\n" info('Excess output!') passed = True if stu_output.rstrip('\n') != output.rstip('\n'): passed = False # compare output files for filename, content in output_files.items(): if filename not in stu_files: info("%s is missing" % filename) passed = False break if content != stu_files[filename]: info("Output file does not match") passed = False break if passed: info("Test %s succeeded" % testname) right.append(testname) else: info("Test %s failed" % testname) wrong.append(testname) #put user output to wiki. stu_outputpage = user + '/' + outputpage outputs.append('[[%s]]' % stu_outputpage) try: wiki.putPage(stu_outputpage, outputtemplate % (esc(stu_output), testname)) #clean old attachments before adding new ones for old_attachment in wiki.listAttachments(stu_outputpage): wiki.deleteAttachment(stu_outputpage, old_attachment) for ofilename, ocontent in stu_files.items(): wiki.putAttachment(stu_outputpage, ofilename, esc(ocontent), True) except opencollab.wiki.WikiFault, error_message: # It's ok if the comment does not change if 'There was an error in the wiki side (You did not change the page content, not saved!)' in error_message: pass elif 'There was an error in the wiki side (Attachment not saved, file exists)' in error_message: pass else: raise # put output file metas to output page wiki.setMeta(stu_outputpage, {'file' : ['[[attachment:%s]]' % esc(x) for x in stu_files.keys()]}) info('Removing ' + tempdir) shutil.rmtree(tempdir) metas = dict() #clear old info info('Clearing old metas') wiki.setMeta(page, {'wrong': [], 'right': []}, True) if len(wrong) == 0: metas['overallvalue'] = ['success'] else: metas['overallvalue'] = ['failure'] if outputs: metas['output'] = outputs if wrong: metas['wrong'] = wrong if right: metas['right'] = right info('Setting new metas') #add metas wiki.setMeta(page, metas, True) info('Done')
if stu_output.rstrip('\n') != output.rstip('\n'):
if stu_output.rstrip('\n') != output.rstrip('\n'):
def checking_loop(wiki): wikiname = wiki.host + ''.join(wiki.path.rsplit('?')[:-1]) while True: #Get all new history pages with pending status info('Lookig for pages in %s' % wikiname) picked_pages = wiki.getMeta('CategoryHistory, overallvalue=pending') info('Found %d pages' % len(picked_pages)) if not picked_pages: info('Sleeping') time.sleep(10) continue #go thgrough all new pages for page in picked_pages: info('%s: picked %s' % (wikiname, page)) tempdir = tempfile.mkdtemp() info("Created tempdir %s" % tempdir) os.chdir(tempdir) #change the status to picked wiki.setMeta(page, {'overallvalue' : ['picked']}, True) metas = picked_pages[page] user = metas['user'].single().strip('[]') # get the attachment filename from the file meta info('Writing files') codes = dict() for filename in metas['file']: attachment_file = removeLink(filename) #get the source code info("Fetching sourcode from %s" % attachment_file) try: code = wiki.getAttachment(page, attachment_file) except opencollab.wiki.WikiFault, e: if 'There was an error in the wiki side (Nonexisting attachment' in e.args[0]: code = '' else: raise # get rid of the _rev<number> in filenames codes[re.sub('(_rev\d+)', '', removeLink(filename))] = code revision = re.search('_rev(\d+)', removeLink(filename)).group(1) #if there is wrong amount of question page linksd, leave #the returned assignment as picked so that other #assignments can be checked. if len(metas['question']) != 1: error('Invalid meta data in %s! There we %d values!\n' % (page, len(metas['question']))) continue #get the question pagenmae question = metas['question'].single(None) if not question: error('NO QUESTION PAGE IN HISTORY %s!' % page) continue question = question.strip('[]') #find associataed answerpages answer_pages = wiki.getMeta(question +'/options').values()[0]['answer'] info("Found %d answer pages" % len(answer_pages)) regex = re.compile('{{{\s*(.*)\s?}}}', re.DOTALL) wrong = list() right = list() outputs = list() for answer_page in [x.strip('[]') for x in answer_pages]: info('getting answers from %s' % answer_page) answer_meta = wiki.getMeta(answer_page).values()[0] testname = answer_meta['testname'].single() outputpage = None inputpage = None if 'output' in answer_meta: outputpage = answer_meta['output'].single().strip('[]') outfilesatt = wiki.listAttachments if 'input' in answer_meta: inputpage = answer_meta['input'].single().strip('[]') try: args = answer_meta['parameters'].single() except ValueError: error('No params!') continue input = '' input_files = dict() if inputpage: content = wiki.getPage(inputpage) input = regex.search(content).group(1) input_meta = wiki.getMeta(inputpage) filelist = input_meta[inputpage]['file'] for attachment in filelist: filename = removeLink(attachment) try: content = wiki.getAttachment(inputpage, filename) except opencollab.wiki.WikiFault, error_message: if "There was an error in the wiki side (Nonexisting attachment:" in error_message: content = '' else: raise input_files[filename] = content output = '' if outputpage: content = wiki.getPage(outputpage) output = regex.search(content).group(1) output_meta = wiki.getMeta(outputpage) # get output files output_files = dict() filelist = output_meta[outputpage]['file'] for attachment in filelist: filename = removeLink(attachment) content = wiki.getAttachment(outputpage, filename) output_files[filename] = content info('Running test') stu_output, stu_error, timeout, stu_files = run_test(codes, args, input, input_files, tempdir) #FIXME. Must check that editors in raippa do not add #newlines in output. If not. These lines can be removed stu_output = stu_error + stu_output if timeout: stu_output = stu_output + "\n***** TIMEOUT *****\nYOUR PROGRAM TIMED OUT!\n\n" if len(stu_output) > 1024*100: stu_output = "***** Your program produced more than 100kB of output data *****\n(Meaning that your program failed)\nPlease check your code before returning it\n" info('Excess output!') passed = True if stu_output.rstrip('\n') != output.rstip('\n'): passed = False # compare output files for filename, content in output_files.items(): if filename not in stu_files: info("%s is missing" % filename) passed = False break if content != stu_files[filename]: info("Output file does not match") passed = False break if passed: info("Test %s succeeded" % testname) right.append(testname) else: info("Test %s failed" % testname) wrong.append(testname) #put user output to wiki. stu_outputpage = user + '/' + outputpage outputs.append('[[%s]]' % stu_outputpage) try: wiki.putPage(stu_outputpage, outputtemplate % (esc(stu_output), testname)) #clean old attachments before adding new ones for old_attachment in wiki.listAttachments(stu_outputpage): wiki.deleteAttachment(stu_outputpage, old_attachment) for ofilename, ocontent in stu_files.items(): wiki.putAttachment(stu_outputpage, ofilename, esc(ocontent), True) except opencollab.wiki.WikiFault, error_message: # It's ok if the comment does not change if 'There was an error in the wiki side (You did not change the page content, not saved!)' in error_message: pass elif 'There was an error in the wiki side (Attachment not saved, file exists)' in error_message: pass else: raise # put output file metas to output page wiki.setMeta(stu_outputpage, {'file' : ['[[attachment:%s]]' % esc(x) for x in stu_files.keys()]}) info('Removing ' + tempdir) shutil.rmtree(tempdir) metas = dict() #clear old info info('Clearing old metas') wiki.setMeta(page, {'wrong': [], 'right': []}, True) if len(wrong) == 0: metas['overallvalue'] = ['success'] else: metas['overallvalue'] = ['failure'] if outputs: metas['output'] = outputs if wrong: metas['wrong'] = wrong if right: metas['right'] = right info('Setting new metas') #add metas wiki.setMeta(page, metas, True) info('Done')
wiki = opencollab.wiki.CLIWiki(options.url, uname, passwd) except socket.error, e: error(e) time.sleep(10) else: break if not wiki.token: sys.stderr.write('Auhtentication failure\n') sys.exit(1) checking_loop(wiki)
while True: try: wiki = opencollab.wiki.CLIWiki(options.url, uname, passwd) except socket.error, e: error(e) time.sleep(10) else: break if not wiki.token: sys.stderr.write('Auhtentication failure\n') sys.exit(1) checking_loop(wiki) except Exception: error('PROBLEMS?') traceback.print_exc() time.sleep(60)
def main(): #parse commandline parameters parser = OptionParser() parser.add_option("-u", "--url-to-wiki", dest="url", help="connect to URL", metavar="URL", default = None) parser.add_option("-f", "--config-file", dest="file", help="read credentials from FILE", metavar="FILE") (options, args) = parser.parse_args() if args: sys.stderr.write('Invalid arguments! Use -h for help\n') sys.exit(1) if not options.url: sys.stderr.write('You must specify a wiki to connect!\n') sys.exit(1) url = options.url if not options.file: try: wiki = opencollab.wiki.CLIWiki(options.url) except socket.error, e: sys.stderr.write(e + '\n') sys.exit(1) else: config = ConfigParser.RawConfigParser() config.read(options.file) uname = config.get('creds', 'username') passwd = config.get('creds', 'password') while True: try: wiki = opencollab.wiki.CLIWiki(options.url, uname, passwd) except socket.error, e: error(e) time.sleep(10) else: break if not wiki.token: sys.stderr.write('Auhtentication failure\n') sys.exit(1) checking_loop(wiki)
except Exception: error('PROBLEMS?') traceback.print_exc() time.sleep(60)
def main(): #parse commandline parameters parser = OptionParser() parser.add_option("-u", "--url-to-wiki", dest="url", help="connect to URL", metavar="URL", default = None) parser.add_option("-f", "--config-file", dest="file", help="read credentials from FILE", metavar="FILE") (options, args) = parser.parse_args() if args: sys.stderr.write('Invalid arguments! Use -h for help\n') sys.exit(1) if not options.url: sys.stderr.write('You must specify a wiki to connect!\n') sys.exit(1) url = options.url if not options.file: try: wiki = opencollab.wiki.CLIWiki(options.url) except socket.error, e: sys.stderr.write(e + '\n') sys.exit(1) else: config = ConfigParser.RawConfigParser() config.read(options.file) uname = config.get('creds', 'username') passwd = config.get('creds', 'password') while True: try: wiki = opencollab.wiki.CLIWiki(options.url, uname, passwd) except socket.error, e: error(e) time.sleep(10) else: break if not wiki.token: sys.stderr.write('Auhtentication failure\n') sys.exit(1) checking_loop(wiki)
if (confirm('Discard changes and close question editor?')) { this.close(); }
this.els.fireEvent('close'); var changed = false; this.els.each(function(el){ if(el.hasClass('edited')) changed=true; }); if (!changed || confirm('Discard changes and close question editor?')) { this.close(); }
def draw_teacherui(macro, user, question): request = macro.request f = macro.formatter res = list() res.append(f.div(1,id="teacherUiBox")) prefix = request.cfg.url_prefix_static res.append(f.rawHTML(''' <script type="text/javascript" src="%s/raippajs/question_edit.js"></script> <script type="text/javascript" src="%s/raippajs/stats.js"></script> <script type="text/javascript" src="%s/raippajs/raphael.js"></script> <script type="text/javascript">
md5 = hashlib.md5()
md5 = hash_md5()
def unix_md5_crypt(pw, salt, magic=None): if magic==None: magic = MAGIC # Take care of the magic string if present if salt[:len(magic)] == magic: salt = salt[len(magic):] # salt can have up to 8 characters: import string salt = string.split(salt, '$', 1)[0] salt = salt[:8] ctx = pw + magic + salt md5 = hashlib.md5() md5.update(pw + salt + pw) final = md5.digest() for pl in range(len(pw),0,-16): if pl > 16: ctx = ctx + final[:16] else: ctx = ctx + final[:pl] # Now the 'weird' xform (??) i = len(pw) while i: if i & 1: ctx = ctx + chr(0) #if ($i & 1) { $ctx->add(pack("C", 0)); } else: ctx = ctx + pw[0] i = i >> 1 md5 = hashlib.md5() md5.update(ctx) final = md5.digest() # The following is supposed to make # things run slower. # my question: WTF??? for i in range(1000): ctx1 = '' if i & 1: ctx1 = ctx1 + pw else: ctx1 = ctx1 + final[:16] if i % 3: ctx1 = ctx1 + salt if i % 7: ctx1 = ctx1 + pw if i & 1: ctx1 = ctx1 + final[:16] else: ctx1 = ctx1 + pw md5 = hashlib.md5() md5.update(ctx1) final = md5.digest() # Final xform passwd = '' passwd = passwd + to64((int(ord(final[0])) << 16) |(int(ord(final[6])) << 8) |(int(ord(final[12]))),4) passwd = passwd + to64((int(ord(final[1])) << 16) |(int(ord(final[7])) << 8) |(int(ord(final[13]))), 4) passwd = passwd + to64((int(ord(final[2])) << 16) |(int(ord(final[8])) << 8) |(int(ord(final[14]))), 4) passwd = passwd + to64((int(ord(final[3])) << 16) |(int(ord(final[9])) << 8) |(int(ord(final[15]))), 4) passwd = passwd + to64((int(ord(final[4])) << 16) |(int(ord(final[10])) << 8) |(int(ord(final[5]))), 4) passwd = passwd + to64((int(ord(final[11]))), 2) return magic + salt + '$' + passwd
wiki.deleteAttachment(stu_outputpageold_attachment)
wiki.deleteAttachment(stu_outputpage, old_attachment)
def checking_loop(wiki): wikiname = wiki.host + ''.join(wiki.path.rsplit('?')[:-1]) while True: #Get all new history pages with pending status info('Lookig for pages in %s' % wikiname) picked_pages = wiki.getMeta('CategoryHistory, overallvalue=pending') info('Found %d pages' % len(picked_pages)) if not picked_pages: info('Sleeping') time.sleep(10) continue #go thgrough all new pages for page in picked_pages: info('%s: picked %s' % (wikiname, page)) tempdir = tempfile.mkdtemp() info("Created tempdir %s" % tempdir) os.chdir(tempdir) #change the status to picked wiki.setMeta(page, {'overallvalue' : ['picked']}, True) metas = picked_pages[page] user = metas['user'].single().strip('[]') # get the attachment filename from the file meta info('Writing files') codes = dict() for filename in metas['file']: attachment_file = removeLink(filename) #get the source code info("Fetching sourcode from %s" % attachment_file) try: code = wiki.getAttachment(page, attachment_file) except opencollab.wiki.WikiFault, e: if 'There was an error in the wiki side (Nonexisting attachment' in e.args[0]: code = '' else: raise # get rid of the _rev<number> in filenames codes[re.sub('(_rev\d+)', '', removeLink(filename))] = code revision = re.search('_rev(\d+)', removeLink(filename)).group(1) #if there is wrong amount of question page linksd, leave #the returned assignment as picked so that other #assignments can be checked. if len(metas['question']) != 1: error('Invalid meta data in %s! There we %d values!\n' % (page, len(metas['question']))) continue #get the question pagenmae question = metas['question'].single(None) if not question: error('NO QUESTION PAGE IN HISTORY %s!' % page) continue question = question.strip('[]') #find associataed answerpages answer_pages = wiki.getMeta(question +'/options').values()[0]['answer'] info("Found %d answer pages" % len(answer_pages)) regex = re.compile('{{{\s*(.*)\s?}}}', re.DOTALL) wrong = list() right = list() outputs = list() for answer_page in [x.strip('[]') for x in answer_pages]: info('getting answers from %s' % answer_page) answer_meta = wiki.getMeta(answer_page).values()[0] testname = answer_meta['testname'].single() outputpage = None inputpage = None if 'output' in answer_meta: outputpage = answer_meta['output'].single().strip('[]') outfilesatt = wiki.listAttachments if 'input' in answer_meta: inputpage = answer_meta['input'].single().strip('[]') try: args = answer_meta['parameters'].single() except ValueError: error('No params!') continue input = '' input_files = dict() if inputpage: content = wiki.getPage(inputpage) input = regex.search(content).group(1) input_meta = wiki.getMeta(inputpage) filelist = input_meta[inputpage]['file'] for attachment in filelist: filename = removeLink(attachment) content = wiki.getAttachment(inputpage, filename) input_files[filename] = content output = '' if outputpage: content = wiki.getPage(outputpage) output = regex.search(content).group(1) output_meta = wiki.getMeta(outputpage) # get output files output_files = dict() filelist = output_meta[outputpage]['file'] for attachment in filelist: filename = removeLink(attachment) content = wiki.getAttachment(outputpage, filename) output_files[filename] = content info('Running test') stu_output, stu_error, timeout, stu_files = run_test(codes, args, input, input_files, tempdir) #FIXME. Must check that editors in raippa do not add #newlines in output. If not. These lines can be removed stu_output = stu_output.strip('\n') output = output.strip('\n') stu_output = stu_error + stu_output if timeout: stu_output = stu_output + "\n***** TIMEOUT *****\nYOUR PROGRAM TIMED OUT!\n\n" if len(stu_output) > 1024*100: stu_output = "***** Your program produced more than 100kB of output data *****\n(Meaning that your program failed)\nPlease check your code before returning it\n" info('Excess output!') passed = True if stu_output != output: passed = False # compare output files for filename, content in output_files.items(): if filename not in stu_files: info("%s is missing" % filename) passed = False break if content != stu_files[filename]: info("Output file does not match") passed = False break if passed: info("Test %s succeeded" % testname) right.append(testname) else: info("Test %s failed" % testname) wrong.append(testname) #put user output to wiki. stu_outputpage = user + '/' + outputpage outputs.append('[[%s]]' % stu_outputpage) try: wiki.putPage(stu_outputpage, outputtemplate % (esc(stu_output), testname)) #clean old attachments before adding new ones for old_attachment in wiki.listAttachments(stu_outputpage): wiki.deleteAttachment(stu_outputpageold_attachment) for ofilename, ocontent in stu_files.items(): wiki.putAttachment(stu_outputpage, ofilename, ocontent, True) except opencollab.wiki.WikiFault, error_message: # It's ok if the comment does not change if 'There was an error in the wiki side (You did not change the page content, not saved!)' in error_message: pass elif 'There was an error in the wiki side (Attachment not saved, file exists)' in error_message: pass else: raise # put output file metas to output page wiki.setMeta(stu_outputpage, {'file' : ['[[attachment:%s]]' % x for x in stu_files.keys()]}) info('Removing ' + tempdir) shutil.rmtree(tempdir) metas = dict() #clear old info info('Clearing old metas') wiki.setMeta(page, {'wrong': [], 'right': []}, True) if len(wrong) == 0: metas['overallvalue'] = ['success'] else: metas['overallvalue'] = ['failure'] if outputs: metas['output'] = outputs if wrong: metas['wrong'] = wrong if right: metas['right'] = right info('Setting new metas') #add metas wiki.setMeta(page, metas, True) info('Done') time.sleep(10)
timed_out = (self.stdout and self.stdout_thread.isAlive() or self.stderr and self.stderr_thread.isAlive())
timed_out = (self.stdout and stdout_thread.isAlive() or self.stderr and stderr_thread.isAlive())
def _communicate(self, input): stdout = None # Return stderr = None # Return
gtlib.gt_encseq_encoder_encode.argtypes = [c_void_p, StrArray, Str, Error]
gtlib.gt_encseq_encoder_encode.argtypes = [c_void_p, StrArray, \ c_char_p, Error]
def register(cls, gtlib): gtlib.gt_encseq_encoder_encode.argtypes = [c_void_p, StrArray, Str, Error]
gtlib.gt_encseq_builder_add_cstr.argtypes = [c_void_p, c_char_p, c_ulong, c_char_p]
gtlib.gt_encseq_builder_add_cstr.argtypes = [c_void_p, c_char_p, \ c_ulong, c_char_p]
def register(cls, gtlib): gtlib.gt_encseq_builder_new.argtypes = [Alphabet] gtlib.gt_encseq_builder_add_cstr.argtypes = [c_void_p, c_char_p, c_ulong, c_char_p]
return gtlib.gt_error_set(self.error, errmsg)
return gtlib.gt_error_set_nonvariadic(self.error, str(errmsg))
def set(self, errmsg): return gtlib.gt_error_set(self.error, errmsg)
gtlib.gt_error_set.argtypes = [c_void_p, c_char_p]
gtlib.gt_error_set_nonvariadic.argtypes = [c_void_p, c_char_p]
def register(cls, gtlib): from ctypes import c_void_p, c_char_p, c_int gtlib.gt_error_new.restype = c_void_p gtlib.gt_error_get.restype = c_char_p gtlib.gt_error_is_set.restype = c_int gtlib.gt_error_get.argtypes = [c_void_p] gtlib.gt_error_set.argtypes = [c_void_p, c_char_p] gtlib.gt_error_is_set.argtypes = [c_void_p] gtlib.gt_error_unset.argtypes = [c_void_p]
@property def start(self):
def _get_start(self):
def __init__(self, start = 0, end = 0): if start > end or start < 0 or end < 0: gterror("range error: start > end!") super(Range, self).__init__(start, end)
@start.setter def start(self, val):
def _set_start(self, val):
def start(self): return self.w_start
@property def end(self):
def _get_end(self):
def start(self, val): if val > self.end or not val >= 0: gterror("Invalid range start component: %d" % val) self.w_start = val
@end.setter def end(self, val):
def _set_end(self, val):
def end(self): return self.w_end
aPos = chr('xdwsbcfy'.index(element[0].lower()) + ord('0'))
group = element[0].lower() aPos = chr('xdwsbcfy'.index(group) + ord('0'))
def elementKey(element): """to be used in sort() and sorted() as key=. Sort by tile type, value, case""" aPos = chr('xdwsbcfy'.index(element[0].lower()) + ord('0')) bPos = element[1].lower() if bPos in 'wfs': bPos = chr('eswn'.index(bPos) + ord('0')) # add element: upper/lowercase should have a defined order too return aPos + bPos + element
if bPos in 'wfs':
if group in 'wfy' and bPos in 'eswn':
def elementKey(element): """to be used in sort() and sorted() as key=. Sort by tile type, value, case""" aPos = chr('xdwsbcfy'.index(element[0].lower()) + ord('0')) bPos = element[1].lower() if bPos in 'wfs': bPos = chr('eswn'.index(bPos) + ord('0')) # add element: upper/lowercase should have a defined order too return aPos + bPos + element
class KMessageBox(object): """dummy for server, just show on stdout""" @staticmethod def sorry(dummy, *args): """just output to stdout""" print ' '.join(args)
if common.InternalParameters.app: from PyKDE4.kdeui import KMessageBox else: try: from PyKDE4.kdeui import KMessageBox except ImportError: class KMessageBox(object): """dummy for server, just show on stdout""" @staticmethod def sorry(dummy, *args): """just output to stdout""" print ' '.join(args) try: from PyKDE4.kdecore import KGlobal
def i18nc(dummyContext, englishIn, *args): """dummy for server""" return i18n(englishIn, *args)
path = os.path.expanduser('~/.kde/share/apps/kajongg/')
return os.path.dirname(str(KGlobal.dirs().locateLocal("appdata", "kajongg.db"))) + '/' except ImportError: def appdataDir(): """the per user directory with kajongg application information like the database""" kdehome = os.environ.get('KDEHOME', '~/.kde') path = os.path.expanduser(kdehome + '/share/apps/kajongg/')
def appdataDir(): """the per user directory with kajongg application information like the database""" path = os.path.expanduser('~/.kde/share/apps/kajongg/') if not os.path.exists(path): os.makedirs(path) return path
newUpperMelds = sorted(self.player.exposedMelds, key=meldKey) if self.player.concealedMelds: newLowerMelds = sorted(self.player.concealedMelds) else: tileStr = ''.join(self.player.concealedTileNames) content = HandContent.cached(self.player.game.ruleset, tileStr) newLowerMelds = list(Meld(x) for x in content.sortedMelds.split()) if not self.player.game.isScoringGame():
newUpperMelds = self.player.exposedMelds[:] if self.player.game.isScoringGame(): newLowerMelds = self.player.concealedMelds[:] else: if self.player.concealedMelds: newLowerMelds = sorted(self.player.concealedMelds) else: tileStr = ''.join(self.player.concealedTileNames) content = HandContent.cached(self.player.game.ruleset, tileStr) newLowerMelds = list(Meld(x) for x in content.sortedMelds.split())
def newTilePositions(self): """returns list(TileAttr). The tiles are not associated to any board.""" result = list() newUpperMelds = sorted(self.player.exposedMelds, key=meldKey) if self.player.concealedMelds: newLowerMelds = sorted(self.player.concealedMelds) else: tileStr = ''.join(self.player.concealedTileNames) content = HandContent.cached(self.player.game.ruleset, tileStr) newLowerMelds = list(Meld(x) for x in content.sortedMelds.split()) if not self.player.game.isScoringGame(): if self.rearrangeMelds: if newLowerMelds[0].pairs[0] == 'Xy': newLowerMelds = sorted(newLowerMelds, key=lambda x: len(x), reverse=True) else: # generate one meld with all sorted tiles newLowerMelds = [Meld(sorted(sum((x.pairs for x in newLowerMelds), []), key=elementKey))] for yPos, melds in ((0, newUpperMelds), (self.lowerY, newLowerMelds)): meldDistance = self.concealedMeldDistance if yPos else self.exposedMeldDistance meldX = 0 meldY = yPos for meld in melds: for idx, tileName in enumerate(meld.pairs): newTile = TileAttr(tileName, meldX, meldY) newTile.dark = meld.pairs[idx].istitle() and (yPos== 0 or self.player.game.isScoringGame()) if self.player.game.isScoringGame(): newTile.focusable = idx == 0 else: newTile.focusable = (tileName[0] not in 'fy' and tileName != 'Xy' and self.player == self.player.game.activePlayer and (meld.state == CONCEALED and (len(meld) < 4 or meld.meldType == REST))) result.append(newTile) meldX += 1 meldX += meldDistance self.newBonusPositions(result) return sorted(result, key=lambda x: x.yoffset * 100 + x.xoffset)
newLowerMelds = sorted(newLowerMelds, key=lambda x: len(x), reverse=True)
newLowerMelds = sorted(newLowerMelds, key=len, reverse=True)
def newTilePositions(self): """returns list(TileAttr). The tiles are not associated to any board.""" result = list() newUpperMelds = sorted(self.player.exposedMelds, key=meldKey) if self.player.concealedMelds: newLowerMelds = sorted(self.player.concealedMelds) else: tileStr = ''.join(self.player.concealedTileNames) content = HandContent.cached(self.player.game.ruleset, tileStr) newLowerMelds = list(Meld(x) for x in content.sortedMelds.split()) if not self.player.game.isScoringGame(): if self.rearrangeMelds: if newLowerMelds[0].pairs[0] == 'Xy': newLowerMelds = sorted(newLowerMelds, key=lambda x: len(x), reverse=True) else: # generate one meld with all sorted tiles newLowerMelds = [Meld(sorted(sum((x.pairs for x in newLowerMelds), []), key=elementKey))] for yPos, melds in ((0, newUpperMelds), (self.lowerY, newLowerMelds)): meldDistance = self.concealedMeldDistance if yPos else self.exposedMeldDistance meldX = 0 meldY = yPos for meld in melds: for idx, tileName in enumerate(meld.pairs): newTile = TileAttr(tileName, meldX, meldY) newTile.dark = meld.pairs[idx].istitle() and (yPos== 0 or self.player.game.isScoringGame()) if self.player.game.isScoringGame(): newTile.focusable = idx == 0 else: newTile.focusable = (tileName[0] not in 'fy' and tileName != 'Xy' and self.player == self.player.game.activePlayer and (meld.state == CONCEALED and (len(meld) < 4 or meld.meldType == REST))) result.append(newTile) meldX += 1 meldX += meldDistance self.newBonusPositions(result) return sorted(result, key=lambda x: x.yoffset * 100 + x.xoffset)
meldX = 0 meldY = yPos
meldX, meldY = 0, yPos
def newTilePositions(self): """returns list(TileAttr). The tiles are not associated to any board.""" result = list() newUpperMelds = sorted(self.player.exposedMelds, key=meldKey) if self.player.concealedMelds: newLowerMelds = sorted(self.player.concealedMelds) else: tileStr = ''.join(self.player.concealedTileNames) content = HandContent.cached(self.player.game.ruleset, tileStr) newLowerMelds = list(Meld(x) for x in content.sortedMelds.split()) if not self.player.game.isScoringGame(): if self.rearrangeMelds: if newLowerMelds[0].pairs[0] == 'Xy': newLowerMelds = sorted(newLowerMelds, key=lambda x: len(x), reverse=True) else: # generate one meld with all sorted tiles newLowerMelds = [Meld(sorted(sum((x.pairs for x in newLowerMelds), []), key=elementKey))] for yPos, melds in ((0, newUpperMelds), (self.lowerY, newLowerMelds)): meldDistance = self.concealedMeldDistance if yPos else self.exposedMeldDistance meldX = 0 meldY = yPos for meld in melds: for idx, tileName in enumerate(meld.pairs): newTile = TileAttr(tileName, meldX, meldY) newTile.dark = meld.pairs[idx].istitle() and (yPos== 0 or self.player.game.isScoringGame()) if self.player.game.isScoringGame(): newTile.focusable = idx == 0 else: newTile.focusable = (tileName[0] not in 'fy' and tileName != 'Xy' and self.player == self.player.game.activePlayer and (meld.state == CONCEALED and (len(meld) < 4 or meld.meldType == REST))) result.append(newTile) meldX += 1 meldX += meldDistance self.newBonusPositions(result) return sorted(result, key=lambda x: x.yoffset * 100 + x.xoffset)
newTile.dark = meld.pairs[idx].istitle() and (yPos== 0 or self.player.game.isScoringGame())
def newTilePositions(self): """returns list(TileAttr). The tiles are not associated to any board.""" result = list() newUpperMelds = sorted(self.player.exposedMelds, key=meldKey) if self.player.concealedMelds: newLowerMelds = sorted(self.player.concealedMelds) else: tileStr = ''.join(self.player.concealedTileNames) content = HandContent.cached(self.player.game.ruleset, tileStr) newLowerMelds = list(Meld(x) for x in content.sortedMelds.split()) if not self.player.game.isScoringGame(): if self.rearrangeMelds: if newLowerMelds[0].pairs[0] == 'Xy': newLowerMelds = sorted(newLowerMelds, key=lambda x: len(x), reverse=True) else: # generate one meld with all sorted tiles newLowerMelds = [Meld(sorted(sum((x.pairs for x in newLowerMelds), []), key=elementKey))] for yPos, melds in ((0, newUpperMelds), (self.lowerY, newLowerMelds)): meldDistance = self.concealedMeldDistance if yPos else self.exposedMeldDistance meldX = 0 meldY = yPos for meld in melds: for idx, tileName in enumerate(meld.pairs): newTile = TileAttr(tileName, meldX, meldY) newTile.dark = meld.pairs[idx].istitle() and (yPos== 0 or self.player.game.isScoringGame()) if self.player.game.isScoringGame(): newTile.focusable = idx == 0 else: newTile.focusable = (tileName[0] not in 'fy' and tileName != 'Xy' and self.player == self.player.game.activePlayer and (meld.state == CONCEALED and (len(meld) < 4 or meld.meldType == REST))) result.append(newTile) meldX += 1 meldX += meldDistance self.newBonusPositions(result) return sorted(result, key=lambda x: x.yoffset * 100 + x.xoffset)
print 'setRuleData, col 2:', content.score.unit, value.toInt()[0]
def __setRuleData(column, content, value): """change rule data in the model""" # pylint: disable-msg=R0912 # allow more than 12 branches dirty = False if column == 0: name = str(value.toString()) if content.name != english(name): dirty = True content.name = english(name) elif column == 1: if content.parType: if content.parType is int: if content.parameter != value.toInt()[0]: dirty = True content.parameter = value.toInt()[0] elif content.parType is bool: return False elif content.parType is str: if content.parameter != str(value.toString()): dirty = True content.parameter = str(value.toString()) else: newval = value.toInt()[0] if content.parameter != str(value.toString()): dirty = True content.parameter = str(value.toString()) else: newval = value.toInt()[0] if content.score.value != newval: content.score.value = newval dirty = True elif column == 2: if content.score.unit != value.toInt()[0]: dirty = True print 'setRuleData, col 2:', content.score.unit, value.toInt()[0] content.score.unit = value.toInt()[0] elif column == 3: if content.definition != str(value.toString()): dirty = True content.definition = str(value.toString()) return dirty
print 'setData:', column, content, value
def setData(self, index, value, role=Qt.EditRole): """change data in the model""" # pylint: disable-msg=R0912 # allow more than 12 branches if not index.isValid(): return False try: dirty = False column = index.column() item = index.internalPointer() ruleset = item.ruleset() content = item.rawContent print 'setData:', column, content, value if role == Qt.EditRole: if isinstance(content, Ruleset) and column == 0: name = str(value.toString()) oldName = content.name content.rename(english(name)) dirty |= oldName != content.name elif isinstance(content, Ruleset) and column == 3: if content.description != unicode(value.toString()): dirty = True content.description = unicode(value.toString()) elif isinstance(content, Rule): if column >= 4: logException('rule column %d not implemented' % column) return False dirty = self.__setRuleData(column, content, value) else: return False elif role == Qt.CheckStateRole: if isinstance(content, Rule) and column ==1: if not isinstance(ruleset, PredefinedRuleset): if content.parType is bool: newValue = value == Qt.Checked if content.parameter != newValue: dirty = True content.parameter = newValue else: return False if dirty: ruleset.dirty = True self.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) return True except BaseException: return False
print 'setModelData:', index.column()
def setModelData(self, editor, model, index): """move changes into model""" print 'setModelData:', index.column() column = index.column() if column == 2: item = index.internalPointer() rule = item.rawContent assert isinstance(rule, Rule) print 'unit:', rule.score.unit, editor.currentIndex() if rule.score.unit != editor.currentIndex(): rule.score.unit = editor.currentIndex() print 'score neu:', rule.score, rule.score.unit item.ruleset().dirty = True model.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) return QItemDelegate.setModelData(self, editor, model, index)
print 'unit:', rule.score.unit, editor.currentIndex()
def setModelData(self, editor, model, index): """move changes into model""" print 'setModelData:', index.column() column = index.column() if column == 2: item = index.internalPointer() rule = item.rawContent assert isinstance(rule, Rule) print 'unit:', rule.score.unit, editor.currentIndex() if rule.score.unit != editor.currentIndex(): rule.score.unit = editor.currentIndex() print 'score neu:', rule.score, rule.score.unit item.ruleset().dirty = True model.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) return QItemDelegate.setModelData(self, editor, model, index)
print 'score neu:', rule.score, rule.score.unit
def setModelData(self, editor, model, index): """move changes into model""" print 'setModelData:', index.column() column = index.column() if column == 2: item = index.internalPointer() rule = item.rawContent assert isinstance(rule, Rule) print 'unit:', rule.score.unit, editor.currentIndex() if rule.score.unit != editor.currentIndex(): rule.score.unit = editor.currentIndex() print 'score neu:', rule.score, rule.score.unit item.ruleset().dirty = True model.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) return QItemDelegate.setModelData(self, editor, model, index)
try: if isinstance(englishText, unicode): englishText = englishText.encode('utf-8') result = unicode(i18n(englishText, *args)) if not args: if result != englishText: ENGLISHDICT[result] = englishText return result except Exception, excObj: if args: raise excObj return englishText
if isinstance(englishText, unicode): englishText = englishText.encode('utf-8') result = unicode(i18n(englishText, *args)) if not args: ENGLISHDICT[result] = englishText return result
def m18n(englishText, *args): """wrapper around i18n converting QString into a Python unicode string""" try: if isinstance(englishText, unicode): englishText = englishText.encode('utf-8') result = unicode(i18n(englishText, *args)) if not args: if result != englishText: ENGLISHDICT[result] = englishText return result except Exception, excObj: # pylint: disable-msg=W0703 if args: raise excObj # m18n might be called for a ruleset description. This could be standard # english text or indigene text. return englishText
raise Exception('has invalid melds: ' + ','.join(meld.str for meld in self.invalidMelds))
raise Exception('has invalid melds: ' + ','.join(meld.content for meld in self.invalidMelds))
def __init__(self, ruleset, string, rules=None): """evaluate string using ruleset. rules are to be applied in any case.""" self.ruleset = ruleset self.string = string self.rules = [] for rule in rules or []: if not isinstance(rule, Rule): rule = ruleset.findManualRuleByName(rule) self.rules.append(rule) self.original = None self.won = False self.ownWind = None self.roundWind = None tileStrings = [] mjStrings = [] splits = string.split() for part in splits: partId = part[0] if partId in 'Mm': self.ownWind = part[1] self.roundWind = part[2] mjStrings.append(part) self.won = partId == 'M' elif partId == 'L': if len(part[1:]) > 8: raise Exception('last tile cannot complete a kang:'+string) mjStrings.append(part) else: tileStrings.append(part)
print '************animations timeout', id(self), 'remaining:', self.pending
def timeout(self): """we should not need this...""" print '************animations timeout', id(self), 'remaining:', self.pending self.pending = 1 self.animationFinished()
if int(input) % self.parties != 0:
if int(inputData) % self.parties != 0:
def validate(self, inputData, pos): result, newPos = QSpinBox.validate(self, inputData, pos) if result == QValidator.Acceptable: if int(input) % self.parties != 0: result = QValidator.Intermediate return (result, newPos)
self.__pairs[3].toUpper()
self.__pairs.toUpper(3)
def fset(self, state): if state == EXPOSED: self.__pairs.toLower() if self.meldType == CLAIMEDKONG: self.__pairs[3].toUpper() elif state == CONCEALED: self.__pairs.toUpper() if len(self.__pairs) == 4: self.__pairs.toLower(0) self.__pairs.toLower(3) else: raise Exception('meld.setState: illegal state %d' % state) for idx, tile in enumerate(self.tiles): tile.element = self.__pairs[idx]
self.addBool('Network', 'autoMode', False)
def __init__(self): if util.PREF: logException(Exception('PREF is not None')) util.PREF = self KConfigSkeleton.__init__(self) self.addString('General', 'tilesetName', 'default') self.addString('General', 'windTilesetName', 'traditional') self.addString('General', 'backgroundName', 'default') self.addBool('Network', 'autoMode', False) self.addInteger('Network', 'serverPort', 8149) self.addBool('Network', 'debugTraffic', False)
self.addBool('Network', 'debugTraffic', False)
self.__dict__['autoMode'] = False self.__dict__['debugTraffic'] = False
def __init__(self): if util.PREF: logException(Exception('PREF is not None')) util.PREF = self KConfigSkeleton.__init__(self) self.addString('General', 'tilesetName', 'default') self.addString('General', 'windTilesetName', 'traditional') self.addString('General', 'backgroundName', 'default') self.addBool('Network', 'autoMode', False) self.addInteger('Network', 'serverPort', 8149) self.addBool('Network', 'debugTraffic', False)
return result
def __getattr__(self, name): """undefined attributes might be parameters""" if not name in Preferences._Parameters: raise AttributeError par = Preferences._Parameters[name] return par.itemValue() return result
lastMelds = [x for x in self.hiddenMelds if lastTile in x.pairs] if not lastMelds: if not self.hiddenMelds: raise Exception('lastMeld: no hidden melds') raise Exception('lastTile %s not in any hidden meld %s' % \ (lastTile, ' '.join(x.joined for x in self.hiddenMelds)))
if lastTile[0].isupper(): checkMelds = self.hiddenMelds else: checkMelds = self.declaredMelds checkMelds = [x for x in checkMelds if len(x) < 4] lastMelds = [x for x in checkMelds if lastTile in x.pairs] assert lastMelds
def computeLastMeld(self, lastTile): """returns the best last meld for lastTile""" lastMelds = [x for x in self.hiddenMelds if lastTile in x.pairs] if not lastMelds: if not self.hiddenMelds: raise Exception('lastMeld: no hidden melds') raise Exception('lastTile %s not in any hidden meld %s' % \ (lastTile, ' '.join(x.joined for x in self.hiddenMelds))) lastMeld = lastMelds[0] # default: the first possible last meld if len(lastMelds) > 0: for meld in lastMelds: if meld.isPair(): # completing pairs gives more points. lastMeld = meld break return lastMeld
self.readyForGameStart()
self.readyForGameStart(self.owner)
def addUser(self, user): """add user to this table""" if user.name in list(x.name for x in self.users): raise srvError(pb.Error, m18nE('You already joined this table')) if len(self.users) == 4: raise srvError(pb.Error, m18nE('All seats are already taken')) self.users.append(user) if len(self.users) == 4: self.readyForGameStart()
self.addBool('General', 'demoMode', True)
self.addBool('General', 'demoMode', False)
def __init__(self): if util.PREF: logException(Exception('PREF is not None')) util.PREF = self KConfigSkeleton.__init__(self) self.addString('General', 'tilesetName', 'default') self.addString('General', 'windTilesetName', 'traditional') self.addString('General', 'backgroundName', 'default') self.addBool('General', 'demoMode', True) self.addInteger('Network', 'serverPort', 8149) self.addBool('Network', 'debugTraffic', True)
self.addBool('Network', 'debugTraffic', True)
self.addBool('Network', 'debugTraffic', False)
def __init__(self): if util.PREF: logException(Exception('PREF is not None')) util.PREF = self KConfigSkeleton.__init__(self) self.addString('General', 'tilesetName', 'default') self.addString('General', 'windTilesetName', 'traditional') self.addString('General', 'backgroundName', 'default') self.addBool('General', 'demoMode', True) self.addInteger('Network', 'serverPort', 8149) self.addBool('Network', 'debugTraffic', True)
answers = ','.join(str(self.answers)) return '%s: answers:%s' % (self.player, answers)
answers = ','.join(str(x) for x in self.answers) if self.answers else 'has no answers`' return '%s: %s' % (self.player, answers)
def __str__(self): answers = ','.join(str(self.answers)) return '%s: answers:%s' % (self.player, answers)
return '%s answers: %s: %s' % (self.player, self.answer, self.args)
return '%s: %s: %s' % (self.player, self.answer, self.args)
def __str__(self): return '%s answers: %s: %s' % (self.player, self.answer, self.args)
debugMessage('SERVER to %s about %s: %s %s' % (receiver, about, command, kwargs))
debugMessage('%d -> %s about %s: %s %s' % (self.table.tableid, receiver, about, command, kwargs))
def tell(self, about, receivers, command, **kwargs): """send info about player 'about' to players 'receivers'""" if not isinstance(receivers, list): receivers = list([receivers]) for receiver in receivers: if command != Message.PopupMsg: self.table.lastMove = Move(about, command, kwargs) if InternalParameters.showTraffic: if not isinstance(receiver.remote, Client): debugMessage('SERVER to %s about %s: %s %s' % (receiver, about, command, kwargs)) if isinstance(receiver.remote, Client): defer = Deferred() defer.addCallback(receiver.remote.remote_move, command, **kwargs) defer.callback(about.name) else: defer = self.table.server.callRemote(receiver.remote, 'move', about.name, command.name, **kwargs) if defer: # the remote player might already be disconnected, defer would be None then self.add(defer, receiver)
return [x[0].explain() for x in self.usedRules]
result = [x[0].explain() for x in self.usedRules] if any(x[0].debug for x in self.usedRules): result.append(str(self)) return result
def explain(self): return [x[0].explain() for x in self.usedRules]
str2, self.rule.name, self.rule.definition))
str2, self.rule.name, self.definition))
def appliesToHand(self, hand, melds, debug=False): """does this regex match?""" meldStr = melds if melds else '' if isinstance(self, RegexIgnoringCase): checkStr = meldStr.lower() + ' ' + hand.mjStr else: checkStr = meldStr + ' ' + hand.mjStr str2 = ' ,,, '.join((checkStr, checkStr)) if InternalParameters.profileRegex: self.timeSum += Timer(stmt='x.search("%s")'%str2, setup="""import re
args = ' '.join([ '--showtraffic' if InternalParameters.showTraffic else '', '--socket=%s' % socketName() if useSocket else '']).lstrip()
def startLocalServer(useSocket): """start a local server""" try: args = ' '.join([ '--showtraffic' if InternalParameters.showTraffic else '', '--socket=%s' % socketName() if useSocket else '']).lstrip() cmd = './kajonggserver.py' if not os.path.exists(cmd): cmd = 'kajonggserver' if args: process = subprocess.Popen([cmd, args]) else: process = subprocess.Popen([cmd]) syslogMessage(m18n('started the local kajongg server: pid=<numid>%1</numid> %2', process.pid, args)) if useSocket: HumanClient.socketServerProcess = process else: HumanClient.serverProcess = process except OSError, exc: logException(exc)
if args: process = subprocess.Popen([cmd, args]) else: process = subprocess.Popen([cmd])
args = [cmd] if InternalParameters.showTraffic: args.append('--showtraffic') if useSocket: args.append('--socket=%s' % socketName()) process = subprocess.Popen(args)
def startLocalServer(useSocket): """start a local server""" try: args = ' '.join([ '--showtraffic' if InternalParameters.showTraffic else '', '--socket=%s' % socketName() if useSocket else '']).lstrip() cmd = './kajonggserver.py' if not os.path.exists(cmd): cmd = 'kajonggserver' if args: process = subprocess.Popen([cmd, args]) else: process = subprocess.Popen([cmd]) syslogMessage(m18n('started the local kajongg server: pid=<numid>%1</numid> %2', process.pid, args)) if useSocket: HumanClient.socketServerProcess = process else: HumanClient.serverProcess = process except OSError, exc: logException(exc)
process.pid, args))
process.pid, ' '.join(args)))
def startLocalServer(useSocket): """start a local server""" try: args = ' '.join([ '--showtraffic' if InternalParameters.showTraffic else '', '--socket=%s' % socketName() if useSocket else '']).lstrip() cmd = './kajonggserver.py' if not os.path.exists(cmd): cmd = 'kajonggserver' if args: process = subprocess.Popen([cmd, args]) else: process = subprocess.Popen([cmd]) syslogMessage(m18n('started the local kajongg server: pid=<numid>%1</numid> %2', process.pid, args)) if useSocket: HumanClient.socketServerProcess = process else: HumanClient.serverProcess = process except OSError, exc: logException(exc)
if data.parType is int: if data.parameter != value.toInt()[0]: dirty = True data.parameter = value.toInt()[0] elif data.parType is bool: return False elif data.parType is str: if data.parameter != str(value.toString()): dirty = True data.parameter = str(value.toString())
if data.parType: if data.parType is int: if data.parameter != value.toInt()[0]: dirty = True data.parameter = value.toInt()[0] elif data.parType is bool: return False elif data.parType is str: if data.parameter != str(value.toString()): dirty = True data.parameter = str(value.toString()) else: newval = value.toInt()[0] if data.parameter != str(value.toString()): dirty = True data.parameter = str(value.toString())
def setData(self, index, value, role=Qt.EditRole): """change data in the model""" if not index.isValid(): return False try: dirty = False column = index.column() item = index.internalPointer() data = item.content if role == Qt.EditRole: if isinstance(data, Ruleset) and column == 0: name = str(value.toString()) oldName = data.name data.rename(english.get(name, name)) dirty |= oldName!= data.name elif isinstance(data, Ruleset) and column == 3: if data.description != unicode(value.toString()): dirty = True data.description = unicode(value.toString()) elif isinstance(data, Rule): ruleset = item.ruleset() if column == 0: name = str(value.toString()) if data.name != english.get(name, name): dirty = True data.name = english.get(name, name) elif column == 1: if data.parType is int: if data.parameter != value.toInt()[0]: dirty = True data.parameter = value.toInt()[0] elif data.parType is bool: return False elif data.parType is str: if data.parameter != str(value.toString()): dirty = True data.parameter = str(value.toString()) else: newval = value.toInt()[0] if data.parameter != str(value.toString()): dirty = True data.parameter = str(value.toString()) elif column == 2: if data.score.unit != value.toInt()[0]: dirty = True data.score.unit = value.toInt()[0] elif column == 3: if data.definition != str(value.toString()): dirty = True data.definition = str(value.toString()) else: logException('rule column %d not implemented' % column) return False else: return False elif role == Qt.CheckStateRole: if isinstance(data, Rule) and column ==1: if data.parType is bool: newValue = value == Qt.Checked if data.parameter != newValue: dirty = True data.parameter = newValue else: return False if dirty: self.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) return True except BaseException: return False
if data.parameter != str(value.toString()):
if data.score.value != newval: data.score.value = newval
def setData(self, index, value, role=Qt.EditRole): """change data in the model""" if not index.isValid(): return False try: dirty = False column = index.column() item = index.internalPointer() data = item.content if role == Qt.EditRole: if isinstance(data, Ruleset) and column == 0: name = str(value.toString()) oldName = data.name data.rename(english.get(name, name)) dirty |= oldName!= data.name elif isinstance(data, Ruleset) and column == 3: if data.description != unicode(value.toString()): dirty = True data.description = unicode(value.toString()) elif isinstance(data, Rule): ruleset = item.ruleset() if column == 0: name = str(value.toString()) if data.name != english.get(name, name): dirty = True data.name = english.get(name, name) elif column == 1: if data.parType is int: if data.parameter != value.toInt()[0]: dirty = True data.parameter = value.toInt()[0] elif data.parType is bool: return False elif data.parType is str: if data.parameter != str(value.toString()): dirty = True data.parameter = str(value.toString()) else: newval = value.toInt()[0] if data.parameter != str(value.toString()): dirty = True data.parameter = str(value.toString()) elif column == 2: if data.score.unit != value.toInt()[0]: dirty = True data.score.unit = value.toInt()[0] elif column == 3: if data.definition != str(value.toString()): dirty = True data.definition = str(value.toString()) else: logException('rule column %d not implemented' % column) return False else: return False elif role == Qt.CheckStateRole: if isinstance(data, Rule) and column ==1: if data.parType is bool: newValue = value == Qt.Checked if data.parameter != newValue: dirty = True data.parameter = newValue else: return False if dirty: self.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) return True except BaseException: return False
data.parameter = str(value.toString())
def setData(self, index, value, role=Qt.EditRole): """change data in the model""" if not index.isValid(): return False try: dirty = False column = index.column() item = index.internalPointer() data = item.content if role == Qt.EditRole: if isinstance(data, Ruleset) and column == 0: name = str(value.toString()) oldName = data.name data.rename(english.get(name, name)) dirty |= oldName!= data.name elif isinstance(data, Ruleset) and column == 3: if data.description != unicode(value.toString()): dirty = True data.description = unicode(value.toString()) elif isinstance(data, Rule): ruleset = item.ruleset() if column == 0: name = str(value.toString()) if data.name != english.get(name, name): dirty = True data.name = english.get(name, name) elif column == 1: if data.parType is int: if data.parameter != value.toInt()[0]: dirty = True data.parameter = value.toInt()[0] elif data.parType is bool: return False elif data.parType is str: if data.parameter != str(value.toString()): dirty = True data.parameter = str(value.toString()) else: newval = value.toInt()[0] if data.parameter != str(value.toString()): dirty = True data.parameter = str(value.toString()) elif column == 2: if data.score.unit != value.toInt()[0]: dirty = True data.score.unit = value.toInt()[0] elif column == 3: if data.definition != str(value.toString()): dirty = True data.definition = str(value.toString()) else: logException('rule column %d not implemented' % column) return False else: return False elif role == Qt.CheckStateRole: if isinstance(data, Rule) and column ==1: if data.parType is bool: newValue = value == Qt.Checked if data.parameter != newValue: dirty = True data.parameter = newValue else: return False if dirty: self.emit(SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index) return True except BaseException: return False
if len(self.concealedMelds) and len(self.concealedTiles): print 'player.hand:', self, 'exposedMelds:', for meld in self.exposedMelds: print meld.joined, print print 'player.hand:', self, 'concealedMelds:', for meld in self.concealedMelds: print meld.joined, print print 'player.hand:', self, 'concealed tiles:', self.concealedTiles
assert not (self.concealedMelds and self.concealedTiles)
def computeHandContent(self, withTile=None): if len(self.concealedMelds) and len(self.concealedTiles): print 'player.hand:', self, 'exposedMelds:', for meld in self.exposedMelds: print meld.joined, print print 'player.hand:', self, 'concealedMelds:', for meld in self.concealedMelds: print meld.joined, print print 'player.hand:', self, 'concealed tiles:', self.concealedTiles prevLastTile = self.lastTile if withTile: self.lastTile = withTile try: melds = [''.join(self.concealedTiles)] if withTile: melds[0] += withTile melds.extend(x.joined for x in self.exposedMelds) melds.extend(x.joined for x in self.concealedMelds) melds.extend(self.bonusTiles) melds.append(self.__mjString()) melds.append(self.__lastString()) finally: self.lastTile = prevLastTile if self.game.eastMJCount == 8 and self == self.game.winner and self.wind == 'E': # eastMJCount will only be inced later, in saveHand rules = [self.game.ruleset.findManualRule('XXXE9')] else: rules = None return HandContent.cached(self.game.ruleset, ' '.join(melds), computedRules=rules)
Query('delete from player where id=%d' % id, dbHandle=dbhandle)
Query('delete from player where id=%d' % nameId, dbHandle=dbhandle)
def cleanPlayerTable(dbhandle): """remove now unneeded columns host, password and make names unique""" playerCounts = IntDict() names = {} keep = {} for nameId, name in Query('select id,name from player', dbHandle=dbhandle).records: playerCounts[name] += 1 names[int(nameId)] = name for name, counter in defaultdict.items(playerCounts): nameIds = [x[0] for x in names.items() if x[1] == name] keepId = nameIds[0] keep[keepId] = name if counter > 1: for nameId in nameIds[1:]: Query('update score set player=%d where player=%d' % (keepId, nameId), dbHandle=dbhandle) Query('update game set p0=%d where p0=%d' % (keepId, nameId), dbHandle=dbhandle) Query('update game set p1=%d where p1=%d' % (keepId, nameId), dbHandle=dbhandle) Query('update game set p2=%d where p2=%d' % (keepId, nameId), dbHandle=dbhandle) Query('update game set p3=%d where p3=%d' % (keepId, nameId), dbHandle=dbhandle) Query('delete from player where id=%d' % id, dbHandle=dbhandle) Query('drop table player', dbHandle=dbhandle) Query.createTable(dbhandle, 'player') for nameId, name in keep.items(): Query('insert into player(id,name) values(?,?)', list([nameId, name]), dbHandle=dbhandle)
self.parameterRules.append(Rule('Minimum number of rounds in game', 'intminRounds||AMandatory', parameter=1))
self.parameterRules.append(Rule('Minimum number of rounds in game', 'intminRounds||AMandatory', parameter=4))
def __addParameterRules(self): """as the name says""" self.parameterRules.append(Rule('Points Needed for Mah Jongg', 'intminMJPoints||Amandatory', parameter=0)) self.parameterRules.append(Rule('Points for a Limit Hand', 'intlimit||Amandatory', parameter=500)) self.parameterRules.append(Rule('Claim Timeout', 'intclaimTimeout||Amandatory', parameter=10)) self.parameterRules.append(Rule('Size of Kong Box', 'intkongBoxSize||Amandatory', parameter=16)) self.parameterRules.append(Rule('Play with Bonus Tiles', 'boolwithBonusTiles||AMandatory', parameter=True)) self.parameterRules.append(Rule('Minimum number of rounds in game', 'intminRounds||AMandatory', parameter=1))
self.connect(res, SIGNAL('toggled(bool)'), self.toggleWidget)
self.connect(res, SIGNAL('toggled(bool)'), self.__toggleWidget)
def kajonggToggleAction(self, name, icon, shortcut=None, actionData=None): """a checkable action""" res = self.kajonggAction(name, icon, shortcut=shortcut, actionData=actionData) res.setCheckable(True) self.connect(res, SIGNAL('toggled(bool)'), self.toggleWidget) return res
def toggleWidget(self, checked):
def __toggleWidget(self, checked):
def toggleWidget(self, checked): """user has toggled widget visibility with an action""" action = self.sender() actionData = action.data().toPyObject() if checked: if isinstance(actionData, type): actionData = actionData(self.game) action.setData(QVariant(actionData)) if isinstance(actionData, ScoringDialog): self.scoringDialog = actionData self.connect(actionData.btnSave, SIGNAL('clicked(bool)'), self.nextHand) self.connect(actionData, SIGNAL('scoringClosed()'), self.scoringClosed) elif isinstance(actionData, ExplainView): self.explainView = actionData elif isinstance(actionData, ScoreTable): self.scoreTable = actionData actionData.show() actionData.raise_() else: assert actionData actionData.hide()
def askSwap(self, swappers):
@staticmethod def askSwap(swappers):
def askSwap(self, swappers): # TODO: make this a class """ask the user if two players should change seats""" # do not make this a staticmethod because we do not want # to import PlayField in game.py mbox = QMessageBox() mbox.setWindowTitle(m18n("Swap Seats") + ' - Kajongg') mbox.setText("By the rules, %s and %s should now exchange their seats. " % \ (swappers[0].name, swappers[1].name)) yesAnswer = QPushButton("&Exchange") mbox.addButton(yesAnswer, QMessageBox.YesRole) noAnswer = QPushButton("&Keep seat") mbox.addButton(noAnswer, QMessageBox.NoRole) mbox.exec_() return mbox.clickedButton() == yesAnswer
r'I^(db){1,2} (dg){1,2} (dr){1,2} (we){1,2} (wn){1,2} (ws){1,2} (ww){1,2} '
r'I^(db){1,2} (dg){1,2} (dr){1,2} (we){1,2} (ws){1,2} (ww){1,2} (wn){1,2} '
def loadRules(self): """define the rules""" self.__addPenaltyRules() self.__addHandRules() self.__addManualRules() self.__addParameterRules() self.winnerRules.append(Rule('Last Tile Completes Pair of 2..8', r' L(.[2-8])\1\1\b', points=2)) self.winnerRules.append(Rule('Last Tile Completes Pair of Terminals or Honors', r' L((.[19])|([dwDW].))\1\1\b', points=4)) self.winnerRules.append(Rule('Last Tile is Only Possible Tile', r' L((?#match if last meld is pair)(.{4,6})|' \ r'((?#or match if last meld is in middle of a chow)(..)..\4(?!\4)..))\b', points=4)) self.winnerRules.append(Rule('Won with Last Tile Taken from Wall', r' L[A-Z]', points=2))
debugMessage('sound.speak:' + what)
def speak(what): """this is what the user of this module will call.""" debugMessage('sound.speak:' + what) if not Sound.enabled: return if Sound.__hasogg123 is None: if not which('ogg123'): Sound.enabled = False # checks again at next reenable logWarning(m18n('No sound because the program ogg123 is missing')) return Sound.__hasogg123 = True if Sound.__process: Sound.__queue.append(what) else: Sound.__play(what)
print 'extracting', archiveName
def __extractArchive(self): """if we have an unextracted archive, extract it""" if self.voiceDirectory.startswith('MD5'): archiveDirectory = self.archiveDirectory() archiveName = self.archiveName() if not os.path.exists(archiveDirectory) and os.path.exists(archiveName): print 'extracting', archiveName tarFile = tarfile.open(archiveName) os.mkdir(archiveDirectory) tarFile.extractall(path=archiveDirectory)
print 'voice.speak:', text
def speak(self, text): """text must be a sound filename without extension""" print 'voice.speak:', text if not self.voiceDirectory.startswith('MD5') \ and not self.voiceDirectory.startswith('ROBOT'): # we have not been able to convert the player name into a voice archive return self.__extractArchive() Sound.speak(self.localTextName(text))
assert self.belongsToGamesServer()
assert self.belongsToGameServer()
def __exchangeSeats(self): """execute seat exchanges according to the rules""" windPairs = self.shiftRules.split(',')[self.roundsFinished-1] while len(windPairs): windPair = windPairs[0:2] windPairs = windPairs[2:] swappers = list(self.players[windPair[x]] for x in (0, 1)) if self.belongsToPlayer(): # we are a client in a remote game, the server swaps and tells us the new places shouldSwap = False elif self.isScoringGame(): # we play a manual game and do only the scoring shouldSwap = self.field.askSwap(swappers) else: # we are the game server. Always swap in remote games. assert self.belongsToGamesServer() shouldSwap = True if shouldSwap: swappers[0].wind, swappers[1].wind = swappers[1].wind, swappers[0].wind self.sortPlayers()
fnCount = self.livingWall.count('fn') + self.kongBox.count('fn') assert fnCount ==1, '%s %s'% (self.livingWall, self.kongBox)
def deal(self): """every player gets 13 tiles (including east)""" self.throwDices() fnCount = self.livingWall.count('fn') + self.kongBox.count('fn') assert fnCount ==1, '%s %s'% (self.livingWall, self.kongBox) for player in self.players: player.clearHand() while len(player.concealedTiles) != 13: self.dealTile(player) player.syncHandBoard()
self.field.setWindowTitle('kajongg')
self.field.setWindowTitle('Kajongg')
def clientLoggedOut(self, result=None): """logged off from server, clean up""" for player in self.players: player.clearHand() if player.handBoard: player.handBoard.hide() player.handBoard = None if self.field: self.field.setWindowTitle('kajongg') self.removeWall() self.field.game = None self.field.refresh()
self.speak(client, move.player.name, move.tile)
def clientAction(self, client, move): if move.tile != move.player.lastTile: client.invalidateOriginalCall(move.player) client.game.hasDiscarded(move.player, move.tile) if not client.thatWasMe(move.player): if client.game.IAmNext(): client.ask(move, [Message.NoClaim, Message.Chow, Message.Pung, Message.Kong, Message.MahJongg]) else: client.ask(move, [Message.NoClaim, Message.Pung, Message.Kong, Message.MahJongg]) self.speak(client, move.player.name, move.tile)
parts = [''.join(x.element for x in self.concealedTiles)]
parts = [''.join(self.concealedTiles)]
def scoringString(self): """helper for HandBoard.__str__""" if self.concealedMelds: parts = [x.joined for x in self.concealedMelds + self.exposedMelds] else: parts = [''.join(x.element for x in self.concealedTiles)] parts.extend([x.joined for x in self.exposedMelds]) parts.extend(self.bonusTiles) return ' '.join(parts)
debugMessage('%s %s' % (cmd, dataSet))
debugMessage('%s:%s %s' % (scFlag, cmd, dataSet))
def __init__(self, cmdList, args=None, dbHandle=None): """we take a list of sql statements. Only the last one is allowed to be a select statement. Do prepared queries by passing a single query statement in cmdList and the parameters in args. If args is a list of lists, execute the prepared query for every sublist. If dbHandle is passed, use that for db access. Else if the default dbHandle (Query.dbhandle) is defined, use it.""" self.dbHandle = dbHandle or Query.dbhandle preparedQuery = not isinstance(cmdList, list) and bool(args) self.query = QSqlQuery(self.dbHandle) self.msg = None self.records = [] if not isinstance(cmdList, list): cmdList = list([cmdList]) self.cmdList = cmdList for cmd in cmdList: if preparedQuery: self.query.prepare(cmd) if not isinstance(args[0], list): args = list([args]) for dataSet in args: if InternalParameters.showSql: debugMessage('%s %s' % (cmd, dataSet)) for value in dataSet: self.query.addBindValue(QVariant(value)) self.success = self.query.exec_() if not self.success: break else: if InternalParameters.showSql: debugMessage(cmd) self.success = self.query.exec_(cmd) if not self.success: Query.lastError = unicode(self.query.lastError().text()) self.msg = 'ERROR in %s: %s' % (self.dbHandle.databaseName(), Query.lastError) logMessage(self.msg, prio=LOG_ERR) return self.records = None self.fields = None if self.query.isSelect(): self.retrieveRecords()
debugMessage(cmd)
debugMessage('%s:%s' %(scFlag, cmd))
def __init__(self, cmdList, args=None, dbHandle=None): """we take a list of sql statements. Only the last one is allowed to be a select statement. Do prepared queries by passing a single query statement in cmdList and the parameters in args. If args is a list of lists, execute the prepared query for every sublist. If dbHandle is passed, use that for db access. Else if the default dbHandle (Query.dbhandle) is defined, use it.""" self.dbHandle = dbHandle or Query.dbhandle preparedQuery = not isinstance(cmdList, list) and bool(args) self.query = QSqlQuery(self.dbHandle) self.msg = None self.records = [] if not isinstance(cmdList, list): cmdList = list([cmdList]) self.cmdList = cmdList for cmd in cmdList: if preparedQuery: self.query.prepare(cmd) if not isinstance(args[0], list): args = list([args]) for dataSet in args: if InternalParameters.showSql: debugMessage('%s %s' % (cmd, dataSet)) for value in dataSet: self.query.addBindValue(QVariant(value)) self.success = self.query.exec_() if not self.success: break else: if InternalParameters.showSql: debugMessage(cmd) self.success = self.query.exec_(cmd) if not self.success: Query.lastError = unicode(self.query.lastError().text()) self.msg = 'ERROR in %s: %s' % (self.dbHandle.databaseName(), Query.lastError) logMessage(self.msg, prio=LOG_ERR) return self.records = None self.fields = None if self.query.isSelect(): self.retrieveRecords()
self.msg = 'ERROR in %s: %s' % (self.dbHandle.databaseName(), Query.lastError)
self.msg = '%s:ERROR in %s: %s' % (scFlag, self.dbHandle.databaseName(), Query.lastError)
def __init__(self, cmdList, args=None, dbHandle=None): """we take a list of sql statements. Only the last one is allowed to be a select statement. Do prepared queries by passing a single query statement in cmdList and the parameters in args. If args is a list of lists, execute the prepared query for every sublist. If dbHandle is passed, use that for db access. Else if the default dbHandle (Query.dbhandle) is defined, use it.""" self.dbHandle = dbHandle or Query.dbhandle preparedQuery = not isinstance(cmdList, list) and bool(args) self.query = QSqlQuery(self.dbHandle) self.msg = None self.records = [] if not isinstance(cmdList, list): cmdList = list([cmdList]) self.cmdList = cmdList for cmd in cmdList: if preparedQuery: self.query.prepare(cmd) if not isinstance(args[0], list): args = list([args]) for dataSet in args: if InternalParameters.showSql: debugMessage('%s %s' % (cmd, dataSet)) for value in dataSet: self.query.addBindValue(QVariant(value)) self.success = self.query.exec_() if not self.success: break else: if InternalParameters.showSql: debugMessage(cmd) self.success = self.query.exec_(cmd) if not self.success: Query.lastError = unicode(self.query.lastError().text()) self.msg = 'ERROR in %s: %s' % (self.dbHandle.databaseName(), Query.lastError) logMessage(self.msg, prio=LOG_ERR) return self.records = None self.fields = None if self.query.isSelect(): self.retrieveRecords()
self.concealedTileNames.remove(allMeldTiles[3])
def exposeMeld(self, meldTiles, called=None): """exposes a meld with meldTiles: removes them from concealedTileNames, adds the meld to exposedMelds and returns it called: we got the last tile for the meld from discarded, otherwise from the wall""" game = self.game game.activePlayer = self allMeldTiles = meldTiles[:] if called: allMeldTiles.append(called.element if isinstance(called, Tile) else called) if len(allMeldTiles) == 4 and allMeldTiles[0].islower(): tile0 = allMeldTiles[0].lower() # we are adding a 4th tile to an exposed pung self.exposedMelds = [meld for meld in self.exposedMelds if meld.pairs != [tile0] * 3] meld = Meld(tile0 * 4) # TODO: test removal self.concealedTileNames.remove(allMeldTiles[3]) self.visibleTiles[tile0] += 1 else: allMeldTiles = sorted(allMeldTiles) # needed for Chow meld = Meld(allMeldTiles) for meldTile in meldTiles: self.concealedTileNames.remove(meldTile) for meldTile in allMeldTiles: self.visibleTiles[meldTile.lower()] += 1 meld.expose(bool(called)) self.exposedMelds.append(meld) game.computeDangerous(self) adding = [called] if called else None self.syncHandBoard(adding=adding) return meld
if len(missing) < 3: print 'tiles, missing for 13 orphans;', tiles, set(x.lower() for x in tiles), missing
def isCalling(self): """the hand is calling if it only needs one tile for mah jongg. Returns the tile needed for MJ or None""" if self.handLenOffset(): return None # here we assume things about the possible structure of a # winner hand. Recheck this when supporting new exotic hands. if len(self.melds) > 7: # only possibility is 13 orphans if any(x in self.tiles.lower() for x in '2345678'): # no minors allowed return None tiles = [] for meld in self.melds: tiles.extend(meld.pairs) missing = elements.majors - set(x.lower() for x in tiles) if len(missing) < 3: print 'tiles, missing for 13 orphans;', tiles, set(x.lower() for x in tiles), missing if len(missing) > 1: return None else: print 'FOUND 13 ORPHANS' return list(missing)[0] # no other legal winner hand allows singles that are not adjacent # to any other tile, so we only try tiles on the hand and for the # suit tiles also adjacent tiles hiddenTiles = [] for meld in self.hiddenMelds: hiddenTiles.extend(meld.pairs) checkTiles = set(hiddenTiles) for tile in hiddenTiles: if tile[0] in 'SBC': if tile[1] > '1': checkTiles.add(chiNext(tile, -1)) if tile[1] < '9': checkTiles.add(chiNext(tile, 1)) for tile in checkTiles: hand = HandContent.cached(self.ruleset, self.string, plusTile=tile) if hand.maybeMahjongg(): return tile
print 'FOUND 13 ORPHANS'
def isCalling(self): """the hand is calling if it only needs one tile for mah jongg. Returns the tile needed for MJ or None""" if self.handLenOffset(): return None # here we assume things about the possible structure of a # winner hand. Recheck this when supporting new exotic hands. if len(self.melds) > 7: # only possibility is 13 orphans if any(x in self.tiles.lower() for x in '2345678'): # no minors allowed return None tiles = [] for meld in self.melds: tiles.extend(meld.pairs) missing = elements.majors - set(x.lower() for x in tiles) if len(missing) < 3: print 'tiles, missing for 13 orphans;', tiles, set(x.lower() for x in tiles), missing if len(missing) > 1: return None else: print 'FOUND 13 ORPHANS' return list(missing)[0] # no other legal winner hand allows singles that are not adjacent # to any other tile, so we only try tiles on the hand and for the # suit tiles also adjacent tiles hiddenTiles = [] for meld in self.hiddenMelds: hiddenTiles.extend(meld.pairs) checkTiles = set(hiddenTiles) for tile in hiddenTiles: if tile[0] in 'SBC': if tile[1] > '1': checkTiles.add(chiNext(tile, -1)) if tile[1] < '9': checkTiles.add(chiNext(tile, 1)) for tile in checkTiles: hand = HandContent.cached(self.ruleset, self.string, plusTile=tile) if hand.maybeMahjongg(): return tile
parser.add_option('','--playopen', dest='playopen', action='store_true',
parser.add_option('','--playopen', dest='playopen', action='store_true',default=False,
def kajonggServer(): """start the server""" from twisted.internet import reactor from optparse import OptionParser parser = OptionParser() parser.add_option('', '--port', dest='port', help=m18n('the server will listen on PORT'), metavar='PORT', default=8149) parser.add_option('', '--showtraffic', dest='showtraffic', action='store_true', help=m18n('the server will show network messages'), default=False) parser.add_option('', '--showsql', dest='showsql', action='store_true', help=m18n('show database SQL commands'), default=False) parser.add_option('', '--seed', dest='seed', help=m18n('for testing purposes: Initializes the random generator with SEED'), metavar='SEED', default=0) parser.add_option('', '--db', dest='dbpath', help=m18n('name of the database'), default=None) parser.add_option('', '--socket', dest='socket', help=m18n('listen on UNIX SOCKET'), default=None, metavar='SOCKET') parser.add_option('','--playopen', dest='playopen', action='store_true', help=m18n("all robots play with visible concealed tiles")) (options, args) = parser.parse_args() InternalParameters.seed = int(options.seed) port = int(options.port) InternalParameters.playOpen |= options.playopen InternalParameters.showTraffic |= options.showtraffic InternalParameters.showSql |= options.showsql if options.dbpath: InternalParameters.dbPath = options.dbpath if options.socket: InternalParameters.socket = options.socket InitDb() realm = MJRealm() realm.server = MJServer() kajonggPortal = portal.Portal(realm, [DBPasswordChecker()]) try: if options.socket: reactor.listenUNIX(options.socket, pb.PBServerFactory(kajonggPortal)) else: reactor.listenTCP(port, pb.PBServerFactory(kajonggPortal)) except error.CannotListenError, errObj: logWarning(errObj) else: reactor.run()
idx = action.addData().toInt()[0]
idx = action.data().toInt()[0]
def __meldFromTile(self, tile): """returns a meld, lets user choose between possible meld types""" if isinstance(tile.board, HandBoard): meld = tile.board.meldWithTile(tile) assert meld if not self.lowerHalf and len(meld) == 4 and meld.state == CONCEALED: pair0 = meld.pairs[0].lower() meldVariants = [Meld(pair0*4), Meld(pair0*3 + pair0[0].upper() + pair0[1])] for variant in meldVariants: variant.tiles = meld.tiles else: return meld else: meldVariants = self.__meldVariants(tile) idx = 0 if len(meldVariants) > 1: menu = QMenu(m18n('Choose from')) for idx, variant in enumerate(meldVariants): action = menu.addAction(shortcuttedMeldName(variant.meldType)) action.setData(QVariant(idx)) if self.scene().clickedTile: menuPoint = QCursor.pos() else: mousePoint = self.tileFaceRect().bottomRight() view = self.__sourceView menuPoint = view.mapToGlobal(view.mapFromScene(tile.mapToScene(mousePoint))) action = menu.exec_(menuPoint) if not action: return None idx = action.addData().toInt()[0] if tile.board == self: meld.tiles = [] return meldVariants[idx]
print 'new saver'
def __init__(self, *what): print 'new saver' StateSaver.savers.append(self) self.widgets = [] for widget in what: name = unicode(widget.objectName()) if not name: if widget.parentWidget(): name = unicode(widget.parentWidget().objectName()+widget.__class__.__name__) else: name = unicode(widget.__class__.__name__) self.widgets.append((widget, name)) PREF.addString('States', name) for widget, name in self.widgets: oldState = QByteArray.fromHex(PREF[name]) if isinstance(widget, (QSplitter, QHeaderView)): widget.restoreState(oldState) else: widget.restoreGeometry(oldState)
self.meldDistance = 0.0
self.exposedMeldDistance = 0.3 self.concealedMeldDistance = 0.0
def __init__(self, player): self.meldDistance = 0.0 self.rowDistance = 0.2 Board.__init__(self, 22.7, 2.0 + self.rowDistance, player.game.field.tileset) self.tileDragEnabled = False self.player = player self.selector = player.game.field.selectorBoard self.setParentItem(player.front) self.setAcceptDrops(True) self.upperMelds = [] self.lowerMelds = [] self.flowers = [] self.seasons = [] self.lowerHalf = False # quieten pylint self.__moveHelper = None self.__sourceView = None self.spaceMelds = common.PREF.spaceMelds
return bool(self.meldDistance)
return bool(self.concealedMeldDistance)
def fget(self): return bool(self.meldDistance)
self.meldDistance = 0.3 if spaceMelds else 0.0
self.concealedMeldDistance = self.exposedMeldDistance if spaceMelds else 0.0
def fset(self, spaceMelds): if spaceMelds != self.spaceMelds: self.meldDistance = 0.3 if spaceMelds else 0.0 self._reload(self.tileset, self._lightSource) self.placeTiles()
upperLen = self.__lineLength(self.upperMelds) + self.meldDistance lowerLen = self.__lineLength(self.lowerMelds) + self.meldDistance
upperLen = self.__lineLength(self.upperMelds) + self.exposedMeldDistance lowerLen = self.__lineLength(self.lowerMelds) + self.concealedMeldDistance
def placeTiles(self): """place all tiles in HandBoard""" self.__removeForeignTiles() flowerY = 0 seasonY = 1.0 + self.rowDistance upperLen = self.__lineLength(self.upperMelds) + self.meldDistance lowerLen = self.__lineLength(self.lowerMelds) + self.meldDistance if upperLen + len(self.flowers) > self.width and lowerLen + len(self.seasons) < self.width \ and len(self.seasons) < len(self.flowers): flowerY, seasonY = seasonY, flowerY
bonusStart = self.width - len(lineBoni) - self.meldDistance
bonusStart = self.width - len(lineBoni) - self.exposedMeldDistance
def placeTiles(self): """place all tiles in HandBoard""" self.__removeForeignTiles() flowerY = 0 seasonY = 1.0 + self.rowDistance upperLen = self.__lineLength(self.upperMelds) + self.meldDistance lowerLen = self.__lineLength(self.lowerMelds) + self.meldDistance if upperLen + len(self.flowers) > self.width and lowerLen + len(self.seasons) < self.width \ and len(self.seasons) < len(self.flowers): flowerY, seasonY = seasonY, flowerY
meldX += self.meldDistance
meldX += self.concealedMeldDistance if yPos else self.exposedMeldDistance
def placeTiles(self): """place all tiles in HandBoard""" self.__removeForeignTiles() flowerY = 0 seasonY = 1.0 + self.rowDistance upperLen = self.__lineLength(self.upperMelds) + self.meldDistance lowerLen = self.__lineLength(self.lowerMelds) + self.meldDistance if upperLen + len(self.flowers) > self.width and lowerLen + len(self.seasons) < self.width \ and len(self.seasons) < len(self.flowers): flowerY, seasonY = seasonY, flowerY
valueNames = {'Y':m18nc('kajongg','tile'), 'b':m18nc('kajongg','white'),
valueNames = {'y':m18nc('kajongg','tile'), 'b':m18nc('kajongg','white'),
def isUpper(self, first=None, last=None): """use first and last as for ranges""" if first is not None: if last is None: return self[first].istitle() else: assert last is None first, last = 0, len(self) return all(self[x].istitle() for x in range(first, last))
if len(lastMeld) < 2:
if len(lastMeld) < 2 or len(lastMeld[1]) == 0:
def appliesToHand(hand, dummyMelds, dummyDebug=False): """see class docstring""" # pylint: disable-msg=R0911 # pylint: disable-msg=R0912 lastMeld = hand.mjStr.split(' L') if len(lastMeld) < 2: # no last tile specified: return False lastMeld = lastMeld[1].split()[0] lastTile = lastMeld[:2] lastMeld = Meld(lastMeld[2:]) if len(lastMeld) == 0: # no last meld specified: This can happen if we only want to # know if saying Mah Jongg is possible return False if lastMeld.isSingle(): # a limit hand, this rule does not matter anyway return False if lastMeld.isPung(): return False # we had two pairs... group, value = lastTile group = group.lower() if group not in 'sbc': return True intValue = int(value) if lastMeld.isChow(): if lastTile != lastMeld.pairs[1]: # left or right tile of a chow: if not ((value == '3' and lastMeld.pairs[0][1] == '1') or (value == '7' and lastMeld.pairs[0][1] == '9')): return False else: assert lastMeld.isPair() for meld in hand.hiddenMelds: # look at other hidden melds of same color: if meld != lastMeld and meld.pairs[0][0].lower() == group: if meld.isChow(): if intValue in [int(meld.pairs[0][1]) - 1, int(meld.pairs[2][1]) + 1]: # pair and adjacent Chow return False elif meld.isPung(): if abs(intValue - int(meld.pairs[0][1])) <= 2: # pair and nearby Pung return False elif meld.isSingle(): # must be 13 orphans return False return True
self.isHandBoard = True
def __init__(self, player): self.isHandBoard = True self.exposedMeldDistance = 0.2 self.concealedMeldDistance = 0.0 self.rowDistance = 0 Board.__init__(self, 15.4, 2.0 + self.rowDistance, InternalParameters.field.tileset) self.tileDragEnabled = False self.player = player self.setParentItem(player.front) self.setAcceptDrops(True) self.upperMelds = [] self.lowerMelds = [] self.flowers = [] self.seasons = [] self.lowerHalf = False self.__moveHelper = None self.__sourceView = None self.rearrangeMelds = common.PREF.rearrangeMelds self.setScale(1.5) self.showShadows = common.PREF.showShadows
from PyQt4.QtGui import QPixmapCache QPixmapCache.clear()
def setWind(self, name, roundsFinished): """change the wind""" self.name = name if isinstance(roundsFinished, bool): self.prevailing = roundsFinished else: self.prevailing = name == WINDS[roundsFinished] self.setBrush(ROUNDWINDCOLOR if self.prevailing else QColor('white')) windtilenr = {'N':1, 'S':2, 'E':3, 'W':4} self.face.setElementId('WIND_%d' % windtilenr[name]) # pixmap cache bug is back (see 23c80523816a8772cd1dba08bbffe8ee4b92a840) # without this, winds are wrong on start of 2nd remote game from PyQt4.QtGui import QPixmapCache QPixmapCache.clear()
except Exception as e:
except Exception as exception:
def __init__(self, tableList, callback): Client.__init__(self) self.root = None self.tableList = tableList self.connector = None self.table = None self.readyHandQuestion = None self.loginDialog = LoginDialog() if InternalParameters.autoPlay: self.loginDialog.accept() else: if not self.loginDialog.exec_(): raise Exception(m18n('Login aborted')) self.useSocket = self.loginDialog.host == Query.localServerName if self.useSocket or self.loginDialog.host == 'localhost': if not self.serverListening(): # give the server up to 5 seconds time to start HumanClient.startLocalServer(self.useSocket) for loop in range(5): if self.serverListening(): break time.sleep(1) self.username = self.loginDialog.username if InternalParameters.autoPlayRuleset: try: self.ruleset = Ruleset(InternalParameters.autoPlayRuleset) except Exception as e: InternalParameters.autoPlay = False InternalParameters.autoPlayRuleset = False raise e else: self.ruleset = self.loginDialog.cbRuleset.current self.login(callback)
raise e
raise exception
def __init__(self, tableList, callback): Client.__init__(self) self.root = None self.tableList = tableList self.connector = None self.table = None self.readyHandQuestion = None self.loginDialog = LoginDialog() if InternalParameters.autoPlay: self.loginDialog.accept() else: if not self.loginDialog.exec_(): raise Exception(m18n('Login aborted')) self.useSocket = self.loginDialog.host == Query.localServerName if self.useSocket or self.loginDialog.host == 'localhost': if not self.serverListening(): # give the server up to 5 seconds time to start HumanClient.startLocalServer(self.useSocket) for loop in range(5): if self.serverListening(): break time.sleep(1) self.username = self.loginDialog.username if InternalParameters.autoPlayRuleset: try: self.ruleset = Ruleset(InternalParameters.autoPlayRuleset) except Exception as e: InternalParameters.autoPlay = False InternalParameters.autoPlayRuleset = False raise e else: self.ruleset = self.loginDialog.cbRuleset.current self.login(callback)
def sorry(*args):
def sorry(none, *args):
def sorry(*args): """just output to stdout""" print args
print args
print ' '.join(args)
def sorry(*args): """just output to stdout""" print args
self.setText("By the rules, %s and %s should now exchange their seats. " % \ (swappers[0].name, swappers[1].name)) yesAnswer = QPushButton("&Exchange") self.addButton(yesAnswer, QMessageBox.YesRole) noAnswer = QPushButton("&Keep seat") self.addButton(noAnswer, QMessageBox.NoRole)
self.setText(m18n("By the rules, %1 and %2 should now exchange their seats. ", swappers[0].name, swappers[1].name)) self.yesAnswer = QPushButton(m18n("&Exchange")) self.addButton(self.yesAnswer, QMessageBox.YesRole) self.noAnswer = QPushButton(m18n("&Keep seat")) self.addButton(self.noAnswer, QMessageBox.NoRole) def exec_(self): """I do not understand the logic of the exec return value. The yes button returns 0 and the no button returns 1. According to the C++ doc, the return value is an opaque value that should not be used.""" return self.clickedButton() == self.yesAnswer
def __init__(self, swappers): QMessageBox.__init__(self) self.setWindowTitle(m18n("Swap Seats") + ' - Kajongg') self.setText("By the rules, %s and %s should now exchange their seats. " % \ (swappers[0].name, swappers[1].name)) yesAnswer = QPushButton("&Exchange") self.addButton(yesAnswer, QMessageBox.YesRole) noAnswer = QPushButton("&Keep seat") self.addButton(noAnswer, QMessageBox.NoRole)
assert( int(flags & QtCore.Qt.ItemIsEnabled) == QtCore.Qt.ItemIsEnabled or int(flags & QtCore.Qt.ItemIsEnabled ) == 0 )
assert( int(flags & QtCore.Qt.ItemIsEnabled) == QtCore.Qt.ItemIsEnabled or \ int(flags & QtCore.Qt.ItemIsEnabled ) == 0 )
def nonDestructiveBasicTest(self): """ nonDestructiveBasicTest tries to call a number of the basic functions (not all) to make sure the model doesn't outright segfault, testing the functions that makes sense. """ assert(self.model.buddy(QtCore.QModelIndex()) == QtCore.QModelIndex()) self.model.canFetchMore(QtCore.QModelIndex()) assert(self.model.columnCount(QtCore.QModelIndex()) >= 0) assert(self.model.data(QtCore.QModelIndex(), QtCore.Qt.DisplayRole) == QtCore.QVariant()) self.fetchingMore = True self.model.fetchMore(QtCore.QModelIndex()) self.fetchingMore = False flags = self.model.flags(QtCore.QModelIndex()) assert( int(flags & QtCore.Qt.ItemIsEnabled) == QtCore.Qt.ItemIsEnabled or int(flags & QtCore.Qt.ItemIsEnabled ) == 0 ) self.model.hasChildren(QtCore.QModelIndex()) self.model.hasIndex(0,0) self.model.headerData(0,QtCore.Qt.Horizontal, QtCore.Qt.DisplayRole) self.model.index(0,0, QtCore.QModelIndex()) self.model.itemData(QtCore.QModelIndex()) cache = QtCore.QVariant() self.model.match(QtCore.QModelIndex(), -1, cache) self.model.mimeTypes() assert(self.model.parent(QtCore.QModelIndex()) == QtCore.QModelIndex()) assert(self.model.rowCount(QtCore.QModelIndex()) >= 0) variant = QtCore.QVariant() self.model.setData(QtCore.QModelIndex(), variant, -1) self.model.setHeaderData(-1, QtCore.Qt.Horizontal, QtCore.QVariant()) self.model.setHeaderData(0, QtCore.Qt.Horizontal, QtCore.QVariant()) self.model.setHeaderData(999999, QtCore.Qt.Horizontal, QtCore.QVariant()) self.model.sibling(0,0,QtCore.QModelIndex()) self.model.span(QtCore.QModelIndex()) self.model.supportedDropActions()
a = self.model.index(0,0, QtCore.QModelIndex()) b = self.model.index(0,0, QtCore.QModelIndex()) assert(a==b)
idx1 = self.model.index(0, 0, QtCore.QModelIndex()) idx2 = self.model.index(0, 0, QtCore.QModelIndex()) assert(idx1==idx2)
def index(self): """ Tests self.model's implementation of QtCore.QAbstractItemModel::index() """ # Make sure that invalid values returns an invalid index assert(self.model.index(-2,-2, QtCore.QModelIndex()) == QtCore.QModelIndex()) assert(self.model.index(-2,0, QtCore.QModelIndex()) == QtCore.QModelIndex()) assert(self.model.index(0,-2, QtCore.QModelIndex()) == QtCore.QModelIndex())
return;
return
def parent(self): """ Tests self.model's implementation of QtCore.QAbstractItemModel::parent() """ # Make sure the self.model wont crash and will return an invalid QtCore.QModelIndex # when asked for the parent of an invalid index assert(self.model.parent(QtCore.QModelIndex()) == QtCore.QModelIndex())
def rowsAboutToBeInserted(self, parent, start, end):
def rowsAboutToBeInserted(self, parent, start, dummyEnd):
def rowsAboutToBeInserted(self, parent, start, end): """ Store what is about to be inserted to make sure it actually happens """ c = {} c['parent'] = parent c['oldSize'] = self.model.rowCount(parent) c['last'] = self.model.data(self.model.index(start-1, 0, parent)) c['next'] = self.model.data(self.model.index(start, 0, parent)) self.insert.append(c)