rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.assertEqual(ulines(check_line("self.filterFunc = eval('lambda %s: %s'%(','.join(variables),formula),{},{})", REPORTER)),
self.assertEqual(ulines(check_line("self.filterFunc = eval('lambda %s: %s'%(','.join(variables),formula),{},{})")),
def test_known_values_all_1(self): self.assertEqual(ulines(check_line("self.filterFunc = eval('lambda %s: %s'%(','.join(variables),formula),{},{})", REPORTER)), ('C0324', "self.filterFunc = eval('lambda %s: %s'%(','.join(variables),formula),{},{})\n ^^"))
self.assertEqual(check_line('print """<a="=")\n"""', REPORTER), None)
self.assertEqual(check_line('print """<a="=")\n"""'), None)
def test_known_values_tqstring(self): self.assertEqual(check_line('print """<a="=")\n"""', REPORTER), None)
self.assertEqual(check_line("print '''<a='=')\n'''", REPORTER), None)
self.assertEqual(check_line("print '''<a='=')\n'''"), None)
def test_known_values_tastring(self): self.assertEqual(check_line("print '''<a='=')\n'''", REPORTER), None)
self.out_encoding = (self.out.encoding or locale.getdefaultlocale()[1] or sys.getdefaultencoding())
def encode(string): if not isinstance(string, unicode): return string encoding = (getattr(self.out, 'encoding', None) or locale.getdefaultlocale()[1] or sys.getdefaultencoding()) return string.encode(encoding) self.encode = encode
def set_output(self, output=None): """set output stream""" self.out = output or sys.stdout self.out_encoding = (self.out.encoding or locale.getdefaultlocale()[1] or sys.getdefaultencoding())
print >> self.out, (isinstance(string, unicode) and string.encode(self.out_encoding) or string)
print >> self.out, self.encode(string)
def writeln(self, string=''): """write a line in the output buffer""" print >> self.out, (isinstance(string, unicode) and string.encode(self.out_encoding) or string)
and exc.root().name == 'exceptions'
and exc.root().name == EXCEPTIONS_MODULE
def visit_tryexcept(self, node): """check for empty except""" exceptions_classes = [] nb_handlers = len(node.handlers) for index, handler in enumerate(node.handlers): # single except doing nothing but "pass" without else clause if nb_handlers == 1 and is_empty(handler.body) and not node.orelse: self.add_message('W0704...
if sys.version_info < (3, 0): EXCEPTIONS_MODULE = "exceptions" else: EXCEPTIONS_MODULE = "builtins"
def visit_tryexcept(self, node): """check for empty except""" exceptions_classes = [] nb_handlers = len(node.handlers) for index, handler in enumerate(node.handlers): # single except doing nothing but "pass" without else clause if nb_handlers == 1 and is_empty(handler.body) and not node.orelse: self.add_message('W0704...
if self.linter.is_message_enabled('RP0401'):
if self.linter.is_message_enabled('R0401'):
def close(self): """called before visiting project (i.e set of modules)""" # don't try to compute cycles if the associated message is disabled if self.linter.is_message_enabled('RP0401'): for cycle in get_cycles(self.import_graph): self.add_message('RP0401', args=' -> '.join(cycle))
self.add_message('RP0401', args=' -> '.join(cycle))
self.add_message('R0401', args=' -> '.join(cycle))
def close(self): """called before visiting project (i.e set of modules)""" # don't try to compute cycles if the associated message is disabled if self.linter.is_message_enabled('RP0401'): for cycle in get_cycles(self.import_graph): self.add_message('RP0401', args=' -> '.join(cycle))
self.assertEqual(self.linter.is_report_enabled('RP0001'), True)
self.assertEqual(self.linter.report_is_enabled('RP0001'), True)
def test_enable_report(self): self.assertEqual(self.linter.is_report_enabled('RP0001'), True) self.linter.disable('RP0001') self.assertEqual(self.linter.is_report_enabled('RP0001'), False) self.linter.enable('RP0001') self.assertEqual(self.linter.is_report_enabled('RP0001'), True)
self.assertEqual(self.linter.is_report_enabled('RP0001'), False)
self.assertEqual(self.linter.report_is_enabled('RP0001'), False)
def test_enable_report(self): self.assertEqual(self.linter.is_report_enabled('RP0001'), True) self.linter.disable('RP0001') self.assertEqual(self.linter.is_report_enabled('RP0001'), False) self.linter.enable('RP0001') self.assertEqual(self.linter.is_report_enabled('RP0001'), True)
self.failIf('design' in [c.name for c in self.linter.needed_checkers()])
self.failIf('design' in [c.name for c in self.linter.prepare_checkers()])
def test_enable_checkers(self): self.linter.disable('design') self.failIf('design' in [c.name for c in self.linter.needed_checkers()]) self.linter.enable('design') self.failUnless('design' in [c.name for c in self.linter.needed_checkers()])
self.failUnless('design' in [c.name for c in self.linter.needed_checkers()])
self.failUnless('design' in [c.name for c in self.linter.prepare_checkers()]) def test_errors_only(self): linter = self.linter self.linter.error_mode() checkers = self.linter.prepare_checkers() checker_names = tuple(c.name for c in checkers) should_not = ('design', 'format', 'imports', 'logging', 'metrics', 'miscellan...
def test_enable_checkers(self): self.linter.disable('design') self.failIf('design' in [c.name for c in self.linter.needed_checkers()]) self.linter.enable('design') self.failUnless('design' in [c.name for c in self.linter.needed_checkers()])
total = stats[node_type] if total == 0: doc_percent = 0 badname_percent = 0 else: documented = total - stats['undocumented_'+node_type] doc_percent = float((documented)*100) / total badname_percent = (float((stats['badname_'+node_type])*100) / total) nice_stats[node_type]['percent_documented'] = doc_percent nice_stats[...
if total != 0: try: documented = total - stats['undocumented_'+node_type] percent = (documented * 100.) / total nice_stats[node_type]['percent_documented'] = '%.2f' % percent except KeyError: nice_stats[node_type]['percent_documented'] = 'NC' try: percent = (stats['badname_'+node_type] * 100.) / total nice_stats[node_t...
def report_by_type_stats(sect, stats, old_stats): """make a report of * percentage of different types documented * percentage of different types with a bad name """ # percentage of different types documented and/or with a bad name nice_stats = {} for node_type in ('module', 'class', 'method', 'function'): nice_stats[n...
'%.2f' % nice_stats[node_type]['percent_documented'], '%.2f' % nice_stats[node_type]['percent_badname'])
nice_stats[node_type].get('percent_documented', '0'), nice_stats[node_type].get('percent_badname', '0'))
def report_by_type_stats(sect, stats, old_stats): """make a report of * percentage of different types documented * percentage of different types with a bad name """ # percentage of different types documented and/or with a bad name nice_stats = {} for node_type in ('module', 'class', 'method', 'function'): nice_stats[n...
def list_checkers_messages(self, checker): """print checker's messages in reST format""" for msgid in sort_msgs(checker.msgs.keys()): print self.get_message_help(msgid, False)
def list_checkers_messages(self, checker): """print checker's messages in reST format""" for msgid in sort_msgs(checker.msgs.keys()): print self.get_message_help(msgid, False)
for checker in sort_checkers(self._checkers.values()):
by_checker = {} for checker in self.sort_checkers():
def print_full_documentation(self): """output a full documentation in ReST format""" for checker in sort_checkers(self._checkers.values()): if checker.name == 'master': prefix = 'Main ' if checker.options: for section, options in checker.options_by_section(): if section is None: title = 'General options' else: title = ...
prefix = '' title = '%s checker' % checker.name.capitalize()
try: by_checker[checker.name][0] += checker.options_and_values() by_checker[checker.name][1].update(checker.msgs) by_checker[checker.name][2] += checker.reports except KeyError: by_checker[checker.name] = [list(checker.options_and_values()), dict(checker.msgs), list(checker.reports)] for checker, (options, msgs, report...
def print_full_documentation(self): """output a full documentation in ReST format""" for checker in sort_checkers(self._checkers.values()): if checker.name == 'master': prefix = 'Main ' if checker.options: for section, options in checker.options_by_section(): if section is None: title = 'General options' else: title = ...
print '-' * len(title) if checker.__doc__: print linesep.join([l.strip() for l in checker.__doc__.splitlines()]) if checker.options: title = 'Options' print title print '~' * len(title) for section, options in checker.options_by_section(): rest_format_section(sys.stdout, section, options) print if checker.msgs:
print '~' * len(title) rest_format_section(sys.stdout, None, options) print if msgs:
def print_full_documentation(self): """output a full documentation in ReST format""" for checker in sort_checkers(self._checkers.values()): if checker.name == 'master': prefix = 'Main ' if checker.options: for section, options in checker.options_by_section(): if section is None: title = 'General options' else: title = ...
self.list_checkers_messages( checker)
for msgid in sort_msgs(msgs.keys()): print self.get_message_help(msgid, False)
def print_full_documentation(self): """output a full documentation in ReST format""" for checker in sort_checkers(self._checkers.values()): if checker.name == 'master': prefix = 'Main ' if checker.options: for section, options in checker.options_by_section(): if section is None: title = 'General options' else: title = ...
if getattr(checker, 'reports', None):
if reports:
def print_full_documentation(self): """output a full documentation in ReST format""" for checker in sort_checkers(self._checkers.values()): if checker.name == 'master': prefix = 'Main ' if checker.options: for section, options in checker.options_by_section(): if section is None: title = 'General options' else: title = ...
for report in checker.reports:
for report in reports:
def print_full_documentation(self): """output a full documentation in ReST format""" for checker in sort_checkers(self._checkers.values()): if checker.name == 'master': prefix = 'Main ' if checker.options: for section, options in checker.options_by_section(): if section is None: title = 'General options' else: title = ...
if PY26:
if PY3K: rest = [ 'E0501', 'E0502', 'E1122', 'I0001', 'W0122', 'W0331', 'W0332', 'W0333', 'W0402', 'W0403', 'W0410', ] self.assertEqual(todo, rest) elif PY26:
def test_exhaustivity(self): # skip fatal messages todo = [msgid for msgid in linter._messages if msgid[0] != 'F'] for msgid in test_reporter.message_ids: try: todo.remove(msgid) except ValueError: continue todo.sort() if PY26: self.assertEqual(todo, ['E1122', 'I0001']) else: self.assertEqual(todo, ['I0001'])
process = Popen("pylint -f parseable -r n --disable-msg-cat=CRI '%s'" %
process = Popen("pylint -f parseable -r n --disable=C,R,I '%s'" %
def lint(filename): """Pylint the given file. When run from emacs we will be in the directory of a file, and passed its filename. If this file is part of a package and is trying to import other modules from within its own package or another package rooted in a directory below it, pylint will classify it as a failed im...
if str(ex).startswith('module importing itself'): return modnode else: self.add_message("F0401", args=modname, node=importnode) return
self.add_message("F0401", args=modname, node=importnode)
def get_imported_module(self, modnode, importnode, modname): try: return importnode.do_import_module(modname) except astng.InferenceError, ex: if str(ex).startswith('module importing itself'): # XXX return modnode else: self.add_message("F0401", args=modname, node=importnode) return
try: self.linter.check('StringIO') self.assert_(os.path.exists('pylint_StringIO.txt'))
pylint_strio = 'pylint_%s.txt' % strio try: self.linter.check(strio) self.assert_(os.path.exists(pylint_strio))
def test_lint_ext_module_with_file_output(self): self.linter.config.files_output = True try: self.linter.check('StringIO') self.assert_(os.path.exists('pylint_StringIO.txt')) self.assert_(os.path.exists('pylint_global.txt')) finally: try: os.remove('pylint_StringIO.txt') os.remove('pylint_global.txt') except: pass
os.remove('pylint_StringIO.txt')
os.remove(pylint_strio)
def test_lint_ext_module_with_file_output(self): self.linter.config.files_output = True try: self.linter.check('StringIO') self.assert_(os.path.exists('pylint_StringIO.txt')) self.assert_(os.path.exists('pylint_global.txt')) finally: try: os.remove('pylint_StringIO.txt') os.remove('pylint_global.txt') except: pass
class ImportCheckerTC(unittest.TestCase):
class ImportCheckerTC(TestCase):
def test_dependencies_graph(self): imports.dependencies_graph(self.dest, {'labas': ['hoho', 'yep'], 'hoho': ['yep']}) self.assertEqual(open(self.dest).read().strip(), '''
unittest.main()
unittest_main()
def test_checker_dep_graphs(self): l = self.linter l.global_set_option('persistent', False) l.global_set_option('enable', 'imports') l.global_set_option('import-graph', 'import.dot') l.global_set_option('ext-import-graph', 'ext_import.dot') l.global_set_option('int-import-graph', 'int_import.dot') l.global_set_option('...
except ImportError, ex:
except (ImportError, SyntaxError), ex:
def expand_modules(files_or_modules, black_list): """take a list of files/modules/packages and return the list of tuple (file, module name) which have to be actually checked """ result = [] errors = [] for something in files_or_modules: if exists(something): # this is a file or a directory try: modname = '.'.join(modpa...
if hasattr(checker, 'reports'): for r_id, r_title, r_cb in checker.reports: self.register_report(r_id, r_title, r_cb, checker)
for r_id, r_title, r_cb in checker.reports: self.register_report(r_id, r_title, r_cb, checker)
def register_checker(self, checker): """register a new checker
any(get_msg(msg, True) for msg in checker.reports) ):
any(get_msg(msg[0], True) for msg in checker.reports) ):
def needed_checkers(self): """return checkers needed for activated messages and reports""" neededcheckers = [] get_msg = self._msgs_state.get for checker in self.get_checkers(): if ( any(get_msg(msg, True) for msg in checker.msgs) or any(get_msg(msg, True) for msg in checker.reports) ): neededcheckers.append(checker) r...
return 42
return "42"
def to_be(): """return 42""" return 42
to_be().real
to_be().title
def to_be(): """return 42""" return 42
elif isinstance(expr, astng.Name) and expr.name == 'NotImplemented':
elif ( (isinstance(expr, astng.Name) and expr.name == 'NotImplemented') or (isinstance(expr, astng.CallFunc) and isinstance(expr.func, astng.Name) and expr.func.name == 'NotImplemented') ):
def _check_raise_value(self, node, expr): """check for bad values, string exception and class inheritance """ value_found = True if isinstance(expr, astng.Const): value = expr.value if isinstance(value, str): self.add_message('W0701', node=node) else: self.add_message('E0702', node=node, args=value.__class__.__name__) ...
def go_back(self): """Simulates the user clicking the "back" button on their browser."""
def go_back(self, dont_wait=''): """Simulates the user clicking the "back" button on their browser. See `introduction` for details about locating elements and about meaning of `dont_wait` argument."""
def go_back(self): """Simulates the user clicking the "back" button on their browser.""" self._selenium.go_back()
self._flex_command('flexAssertText', 'name=%s,validator=%s' % (locator, expected.replace(',', '\\,')))
self._flex_command('flexAssertText', 'name=%s,validator=%s' % (locator, expected))
def text_in_flex_should_be(self, locator, expected): self._flex_command('flexAssertText', 'name=%s,validator=%s' % (locator, expected.replace(',', '\\,')))
os.path.join(RESULTDIR, '%s-output.xml' % ARG_VALUES['browser'])])
os.path.join(RESULTDIR, 'output.xml')])
def process_output(): print call(['python', os.path.join(RESOURCEDIR, 'statuschecker.py'), os.path.join(RESULTDIR, '%s-output.xml' % ARG_VALUES['browser'])]) rebot = utils.is_windows and 'rebot.bat' or 'rebot' rebot_cmd = [rebot] + [ arg % ARG_VALUES for arg in REBOT_ARGS ] + \ [os.path.join(ARG_VALUES['outdir'], '%s-o...
[os.path.join(ARG_VALUES['outdir'], '%s-output.xml' % ARG_VALUES['browser'] ) ]
[os.path.join(ARG_VALUES['outdir'], 'output.xml') ]
def process_output(): print call(['python', os.path.join(RESOURCEDIR, 'statuschecker.py'), os.path.join(RESULTDIR, '%s-output.xml' % ARG_VALUES['browser'])]) rebot = utils.is_windows and 'rebot.bat' or 'rebot' rebot_cmd = [rebot] + [ arg % ARG_VALUES for arg in REBOT_ARGS ] + \ [os.path.join(ARG_VALUES['outdir'], '%s-o...
def test_patched_open_browser(self): rc_path = os.path.join(os.path.dirname(__file__), '..', '..', 'src', 'SeleniumLibrary', 'selenium.py') self.assertTrue('self.do_command("open", [url,"true"])' in open(rc_path).read(), "Patch for Firefox 3.6 compatibility required. See issue 114: "+ "http://code.google.com/p/robotfra...
def test_patched_open_browser(self): rc_path = os.path.join(os.path.dirname(__file__), '..', '..', 'src', 'SeleniumLibrary', 'selenium.py') self.assertTrue('self.do_command("open", [url,"true"])' in open(rc_path).read(), "Patch for Firefox 3.6 compatibility required. See issue 114: "+ "http://code.google.com/p/robotfra...
"""Dismisses currently shown confirmation dialog.
"""Dismisses currently shown confirmation dialog and returns it's message.
def confirm_action(self): """Dismisses currently shown confirmation dialog.
| Choose Confirm | |
| ${message}= | Confirm Action | | Should Be Equal | ${message} | Are your sure? |
def confirm_action(self): """Dismisses currently shown confirmation dialog.
| Choose Confirm | |
| Confirm Action | |
def confirm_action(self): """Dismisses currently shown confirmation dialog.
self._selenium.get_confirmation()
return self._selenium.get_confirmation()
def confirm_action(self): """Dismisses currently shown confirmation dialog.
must be given to `dont_wait` argument.
must be given for the `dont_wait` argument.
def shut_down_selenium_server(host='localhost', port=4444): """Shuts down the Selenium Server. `host` and `port` define where the location of Selenium Server. Does not fail even if the Selenium Server is not running. """ try: selenium(host, port, '', '').do_command('shutDownSeleniumServer', []) except socket.error: p...
we expect them not to. In these case, the keywords have an optional `wait`
we expect them not to. For these cases, the keywords have an optional `wait`
def shut_down_selenium_server(host='localhost', port=4444): """Shuts down the Selenium Server. `host` and `port` define where the location of Selenium Server. Does not fail even if the Selenium Server is not running. """ try: selenium(host, port, '', '').do_command('shutDownSeleniumServer', []) except socket.error: p...
on the samme host where the Selenium Server is running.
on the same host where the Selenium Server is running.
def choose_file(self, identifier, file_path): """Inputs the `file_path` into file input field found by `identifier`.
self._info("File '%s' does not exists on the local file system"
self._info("File '%s' does not exist on the local file system"
def choose_file(self, identifier, file_path): """Inputs the `file_path` into file input field found by `identifier`.
"it's text is '%s'." % (locator, excepted, actual)
"its text was '%s'." % (locator, excepted, actual)
def element_should_contain(self, locator, excepted, message=''): """Verifies element identified by `locator` contains text `expected`.
process_output()
return process_output()
def acceptance_tests(interpreter, browser, args): ARG_VALUES['browser'] = browser.replace('*', '') # TODO: running unit tests this way fails on my Windows, why? start_http_server() suffix = utils.is_windows and 'ybot.bat' or 'ybot' runner = "%s%s" % ('jython' == interpreter and 'j' or 'p', suffix) execute_tests(runner)...
acceptance_tests(interpreter, browser, args)
sys.exit(acceptance_tests(interpreter, browser, args))
def process_output(): print call(['python', os.path.join(RESOURCEDIR, 'statuschecker.py'), os.path.join(RESULTDIR, '%s-output.xml' % ARG_VALUES['browser'])]) rebot = utils.is_windows and 'rebot.bat' or 'rebot' rebot_cmd = [rebot] + [ arg % ARG_VALUES for arg in REBOT_ARGS ] + \ [os.path.join(ARG_VALUES['outdir'], '%s-o...
server = StoppableHttpServer(('', int(port)), StoppableHttpRequestHandler)
server = StoppableHttpServer(('localhost', int(port)), StoppableHttpRequestHandler)
def start_server(port=DEFAULT_PORT): print "Demo application starting on port %s" % port root = os.path.dirname(os.path.abspath(__file__)) os.chdir(root) server = StoppableHttpServer(('', int(port)), StoppableHttpRequestHandler) server.serve_forever()
Examples: | ${func} = | return Selenium.prototype.locateElementByJQuerySelector(locator, inDocument, inWindow); | | Add Location Strategy | jquery | ${func} |
Example: | Add Location Strategy | jquery | return Selenium.prototype.locateElementByJQuerySelector(locator, inDocument, inWindow); |
def add_location_strategy(self, strategy_name, function_definition): """Adds a custom location strategy.
def element_should_contain(self, locator, excepted, message=''):
def element_should_contain(self, locator, expected, message=''):
def element_should_contain(self, locator, excepted, message=''): """Verifies element identified by `locator` contains text `expected`.
% (locator, excepted))
% (locator, expected))
def element_should_contain(self, locator, excepted, message=''): """Verifies element identified by `locator` contains text `expected`.
if not excepted in actual:
if not expected in actual:
def element_should_contain(self, locator, excepted, message=''): """Verifies element identified by `locator` contains text `expected`.
"its text was '%s'." % (locator, excepted, actual) raise AssertionError(message) def element_text_should_be(self, locator, excepted, message=''):
"its text was '%s'." % (locator, expected, actual) raise AssertionError(message) def element_text_should_be(self, locator, expected, message=''):
def element_should_contain(self, locator, excepted, message=''): """Verifies element identified by `locator` contains text `expected`.
% (locator, excepted))
% (locator, expected))
def element_text_should_be(self, locator, excepted, message=''): """Verifies element identified by `locator` exactly contains text `expected`. In contrast to `Element Should Contain`, this keyword does not try a substring match but an exact match on the element identified by `locator`.
if excepted != actual:
if expected != actual:
def element_text_should_be(self, locator, excepted, message=''): """Verifies element identified by `locator` exactly contains text `expected`. In contrast to `Element Should Contain`, this keyword does not try a substring match but an exact match on the element identified by `locator`.
"in fact it was '%s'." % (locator, excepted, actual)
"in fact it was '%s'." % (locator, expected, actual)
def element_text_should_be(self, locator, excepted, message=''): """Verifies element identified by `locator` exactly contains text `expected`. In contrast to `Element Should Contain`, this keyword does not try a substring match but an exact match on the element identified by `locator`.
super(ContactForm, self).__init__(data=data, files=files, *args, **kwargs)
super(ContactBaseForm, self).__init__(data=data, files=files, *args, **kwargs)
def __init__(self, data=None, files=None, request=None, *args, **kwargs): if request is None: raise TypeError("Keyword argument 'request' must be supplied") super(ContactForm, self).__init__(data=data, files=files, *args, **kwargs) self.request = request
'zope.app.zcmlfiles']),
'zope.app.zcmlfiles', 'zope.login',]),
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
del viewer
def pick(self, x, y, viewer): g1 = osgUtil.IntersectorGroup() l1 = osgUtil.LineSegmentIntersector(osgUtil.Intersector.PROJECTION, x, y) g1.addIntersector(l1) iv = osgUtil.IntersectionVisitor(g1) viewer.getCameraWithFocus().accept( iv ) #check for intersections if l1.containsIntersections(): try: intersection = l1.getFi...
self.aboutToShow.connect(self.updateEntries)
QObject.connect( self, SIGNAL('aboutToShow()'), self.updateEntries)
def __init__(self,parent=None): super(QtRecentFileMenu,self).__init__(parent)
ReduceBlockFormat.labelBlock(cur,self.mode)
self.labelBlock(cur,self.mode)
def startElement(self,namespaceURI,localName,qName,atts):
if self.computation.error:
traceLogger.debug("appended to finishedComputations") if self.computation.status == QtReduceComputation.Error:
def run(self): c = self.computation.command traceLogger.debug("computing %s" % c) a = self.reduce.compute(c) self.computation.processAnswer(a,self.accTime,self.accGcTime) self.accTime = self.computation.accTime self.accGcTime = self.computation.accGcTime self.finishedComputations.append(self.computation) if self.comput...
'<small>'
'<font size="-3">'
def about(self): QMessageBox.about(self, self.tr("About QReduce"),self.tr( '<center>' '<h3>QReduce 0.2</h3>' '<p>&copy; 2009-2010 T. Sturm, 2010 C. Zengler' '</center>' 'A worksheet-based GUI for the computer algebra system Reduce.' '<p>' '<small>' '<hr>' '<strong>License: </strong>' 'Redistribution and use in source a...
'</small>'
'</font>'
def about(self): QMessageBox.about(self, self.tr("About QReduce"),self.tr( '<center>' '<h3>QReduce 0.2</h3>' '<p>&copy; 2009-2010 T. Sturm, 2010 C. Zengler' '</center>' 'A worksheet-based GUI for the computer algebra system Reduce.' '<p>' '<small>' '<hr>' '<strong>License: </strong>' 'Redistribution and use in source a...
'</small>'))
'</font>'))
def about(self): QMessageBox.about(self, self.tr("About QReduce"),self.tr( '<center>' '<h3>QReduce 0.2</h3>' '<p>&copy; 2009-2010 T. Sturm, 2010 C. Zengler' '</center>' 'A worksheet-based GUI for the computer algebra system Reduce.' '<p>' '<small>' '<hr>' '<strong>License: </strong>' 'Redistribution and use in source a...
diag = QFileDialog() fileName = diag.getSaveFileName(None,title,path,filter) diag = None
fileName = QFileDialog.getSaveFileName(self,title,path,filter)
def saveAs(self): title = self.tr("Save Reduce Worksheet") path = os.path.dirname(os.path.abspath(self.worksheet.fileName.__str__())) filter = self.tr("Reduce Worksheets (*.rws)") diag = QFileDialog()
msg += self.worksheet.fileName.split('/')[-1] or 'untitled' msg += '"?</b><p><small>Otherwise they will get lost.</small>' diag.setInformativeText(msg)
msg += self.worksheet.fileName.split('/')[-1] or 'untitled' + '"?</b><p>' msg += '<font size="-1">Otherwise they will get lost.</font>' diag.setText(msg)
def __savediag(self): diag = QMessageBox(self) msg = '<b>Do you want to save the changes in your worksheet "' msg += self.worksheet.fileName.split('/')[-1] or 'untitled' msg += '"?</b><p><small>Otherwise they will get lost.</small>' diag.setInformativeText(msg) diag.setStandardButtons(QMessageBox.StandardButton.Discard...
msg += self.worksheet.fileName.split('/')[-1] or 'untitled' + '"?'
msg += (self.worksheet.fileName.split('/')[-1] or 'untitled') + '"?'
def __savediag(self): diag = QMessageBox(self) msg = 'Do you want to save the changes in your worksheet "' msg += self.worksheet.fileName.split('/')[-1] or 'untitled' + '"?' diag.setText(msg) diag.setInformativeText("Otherwise they will get lost") diag.setIcon(QMessageBox.Warning) diag.setStandardButtons(QMessageBox.St...
self.setWindowTitle(self.tr("Untitled") + "[*]")
self.setWindowTitle("[*]" + self.tr("Untitled"))
def setTitle(self,fullPath): traceLogger.debug("fullPath=%s" % fullPath) if fullPath is '': self.setWindowTitle(self.tr("Untitled") + "[*]") else: pFullPath = fullPath.rpartition('/') traceLogger.debug("pFullPath=[%s,%s,%s]" % pFullPath) self.setWindowFilePath(fullPath) self.setWindowTitle("[*]" + pFullPath[2])
font.setPointSize(font.pointSize() - 3)
if os.uname()[0] == "Darwin": font.setPointSize(font.pointSize() - 3)
def __init__(self,parent=None): QStatusBar.__init__(self,parent) self.symbolic = None font = self.font() traceLogger.debug(font.pointSize()) font.setPointSize(font.pointSize() - 3) self.setFont(font) self.reduceMode = QLabel() self.reduceMode.setFixedWidth( QFontMetrics(font).width(self.tr("Mode: Algebraic"))) self.red...
icon = os.getcwd() + "/resources/logos/" + c['name'] + ".png"
icon = os.getcwd() + "/resources/logos/" + c['name'].replace(" ", "_") + ".png"
def showChannels(): for idx, c in enumerate(__channels__): icon = os.getcwd() + "/resources/logos/" + c['name'] + ".png" item = xbmcgui.ListItem(c['name'], iconImage = icon) url = __path__ + '?idx=' + str(idx) xbmcplugin.addDirectoryItem(__handle__, url, item, True) xbmcplugin.endOfDirectory(__handle__)
parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", metavar="PCSC",
parser.add_option("-p", "--pcsc-device", dest="pcsc_dev", type='int', metavar="PCSC",
def parse_options(): parser = OptionParser(usage="usage: %prog [options]") parser.add_option("-d", "--device", dest="device", metavar="DEV", help="Serial Device for SIM access [default: %default]", default="/dev/ttyUSB0", ) parser.add_option("-b", "--baud", dest="baudrate", type="int", metavar="BAUD", help="Baudrate ...
sl = PcscSimLink(0, observer=0)
sl = PcscSimLink(opts.pcsc_dev)
def write_parameters(opts, params): # CSV if opts.write_csv: import csv row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki'] f = open(opts.write_csv, 'a') cw = csv.writer(f) cw.writerow([params[x] for x in row]) f.close() # SQLite3 OpenBSC HLR if opts.write_hlr: import sqlite3 conn = sqlite3.connect(opts.write_...
[ sub_id, 2, sqlite3.Binary(h2b(params['ki'])) ],
[ sub_id, 2, sqlite3.Binary(_dbi_binary_quote(h2b(params['ki']))) ],
def write_parameters(opts, params): # CSV if opts.write_csv: import csv row = ['name', 'iccid', 'mcc', 'mnc', 'imsi', 'smsp', 'ki'] f = open(opts.write_csv, 'a') cw = csv.writer(f) cw.writerow([params[x] for x in row]) f.close() # SQLite3 OpenBSC HLR if opts.write_hlr: import sqlite3 conn = sqlite3.connect(opts.write_...
opts.num += 1
if opts.num is not None: opts.num += 1
def card_detect(opts, scc): # Detect type if needed card = None ctypes = dict([(kls.name, kls) for kls in _cards_classes]) if opts.type in ("auto", "auto_once"): for kls in _cards_classes: card = kls.autodetect(scc) if card: print "Autodetected card type %s" % card.name card.reset() break if card is None: print "Aut...
def __init__(self, reader_number=0, observer=0):
def __init__(self, reader_number=0):
def __init__(self, reader_number=0, observer=0): r = readers(); try: self._con = r[reader_number].createConnection() if (observer): observer = ConsoleCardConnectionObserver() self._con.addObserver(observer) self._con.connect() #print r[reader_number], b2h(self._con.getATR()) except NoCardException: raise NoCardError()
if (observer): observer = ConsoleCardConnectionObserver() self._con.addObserver(observer)
def __init__(self, reader_number=0, observer=0): r = readers(); try: self._con = r[reader_number].createConnection() if (observer): observer = ConsoleCardConnectionObserver() self._con.addObserver(observer) self._con.connect() #print r[reader_number], b2h(self._con.getATR()) except NoCardException: raise NoCardError()
self.folder.invokeFactory('plone.page', 'dp')
self.folder.invokeFactory('plone.app.page', 'dp')
def test_adding(self): # Ensure that invokeFactory() works as with normal types self.folder.invokeFactory('plone.page', 'dp')
self.folder.invokeFactory('plone.page', 'dp', title="Old title")
self.folder.invokeFactory('plone.app.page', 'dp', title="Old title")
def test_attributes_and_reindexing(self):
migration = __import__(full_name, '', '', ['Migration'])
migration = __import__(full_name, {}, {}, ['Migration'])
def migration(self): "Tries to load the actual migration module" full_name = self.full_name() try: migration = sys.modules[full_name] except KeyError: try: migration = __import__(full_name, '', '', ['Migration']) except ImportError, e: raise exceptions.UnknownMigration(self, sys.exc_info()) except Exception, e: raise e...
def load_initial_data(self, target):
def load_initial_data(self, target, db='default'):
def load_initial_data(self, target): if target is None or target != target.migrations[-1]: return # Load initial data, if we ended up at target if self.verbosity: print " - Loading initial data for %s." % target.app_label() # Override Django's get_apps call temporarily to only load from the # current app old_get_apps =...
call_command('loaddata', 'initial_data', verbosity=self.verbosity)
call_command('loaddata', 'initial_data', verbosity=self.verbosity, database=db)
def load_initial_data(self, target): if target is None or target != target.migrations[-1]: return # Load initial data, if we ended up at target if self.verbosity: print " - Loading initial data for %s." % target.app_label() # Override Django's get_apps call temporarily to only load from the # current app old_get_apps =...
self.load_initial_data(target)
self.load_initial_data(target, db=database)
def migrate_many(self, target, migrations, database): migrator = self._migrator result = migrator.__class__.migrate_many(migrator, target, migrations, database) if result: self.load_initial_data(target) return True
if not field.null and not getattr(field, '_suppress_default', False) and field.has_default(): default = field.get_default() if default is not None: if callable(default): default = default() if isinstance(default, basestring): default = "'%s'" % default.replace("'", "''") elif isinstance(default, (datetime.date, date...
if not getattr(field, '_suppress_default', False): if not field.null and not getattr(field, '_suppress_default', False) and field.has_default(): default = field.get_default() if default is not None: if callable(default): default = default() if isinstance(default, basestring): default = "'%s'" % default.replace("'", ...
def column_sql(self, table_name, field_name, field, tablespace='', with_name=True, field_prepared=False): """ Creates the SQL snippet for a column. Used by add_column and add_table. """
os.remove(self.test_path)
try: os.remove(self.test_path) except: pass
def test_db_execute_logging_validfile(self): "Does logging work when passing in a valid file?" settings.SOUTH_LOGGING_ON = True settings.SOUTH_LOGGING_FILE = self.test_path # Check to see if we can make the logfile try: open(self.test_path, "w") except IOError: # Permission was denied, ignore the test. return # Do an a...
fields['Meta']['object_name'] = repr(model._meta.object_name)
fields['Meta']['object_name'] = model._meta.object_name
def prep_for_freeze(model): """ Takes a model and returns the ready-to-serialise dict (all you need to do is just pretty-print it). """ fields = modelsinspector.get_model_fields(model, m2m=True) # Remove useless attributes (like 'choices') for name, field in fields.items(): fields[name] = remove_useless_attributes(fiel...
self.connection_init()
self._initialised = False
def __init__(self, db_alias): self.debug = False self.deferred_sql = [] self.dry_run = False self.pending_transactions = 0 self.pending_create_signals = [] self.db_alias = db_alias self.connection_init()
open(self.test_path, "w")
fh = open(self.test_path, "w")
def test_db_execute_logging_validfile(self): "Does logging work when passing in a valid file?" settings.SOUTH_LOGGING_ON = True settings.SOUTH_LOGGING_FILE = self.test_path # Check to see if we can make the logfile try: open(self.test_path, "w") except IOError: # Permission was denied, ignore the test. return # Do an a...
field_defs = "\n ".join([
field_defs = ",\n ".join([
def forwards_code(self): field_defs = "\n ".join([ "(%r, %s)" % (name, defn) for name, defn in self.triples_to_defs(self.model_def).items() ]) return self.FORWARDS_TEMPLATE % { "model_name": self.model._meta.object_name, "table_name": self.model._meta.db_table, "app_label": self.model._meta.app_label, "fie...
class AddField(Action): """ Adds a field to a model. Takes a Model class and the field name. """ FORWARDS_TEMPLATE = ''' db.add_column(%(table_name)r, %(field_name)r, %(field_def)s, keep_default=False)''' BACKWARDS_TEMPLATE = ''' db.delete_column(%(table_name)r, %(field_column)r)''' def __init__(self, model, field...
class _NullIssuesField(object): """ A field that might need to ask a question about rogue NULL values. """ allow_third_null_option = False irreversible = False IRREVERSIBLE_TEMPLATE = ''' raise RuntimeError("Cannot reverse this migration. '%(model_name)s.%(field_name)s' and its values cannot be restored.")''' def d...
def backwards_code(self): return AddModel.forwards_code(self)
if isinstance(self.field, (CharField, TextField)) and self.field.blank: self.field_def[2]['default'] = repr("")
if isinstance(field, (CharField, TextField)) and field.blank: field_def[2]['default'] = repr("")
def deal_with_not_null_no_default(self): # If it's a CharField or TextField that's blank, skip this step. if isinstance(self.field, (CharField, TextField)) and self.field.blank: self.field_def[2]['default'] = repr("") return # Oh dear. Ask them what to do. print " ? The field '%s.%s' does not have a default specified, ...
self.field.name, ) print " ? Since you are adding this field, you MUST specify a default"
field.name, ) print " ? Since you are %s, you MUST specify a default" % self.null_reason
def deal_with_not_null_no_default(self): # If it's a CharField or TextField that's blank, skip this step. if isinstance(self.field, (CharField, TextField)) and self.field.blank: self.field_def[2]['default'] = repr("") return # Oh dear. Ask them what to do. print " ? The field '%s.%s' does not have a default specified, ...
self.add_one_time_default() def add_one_time_default(self):
self.add_one_time_default(field, field_def) elif choice == "3": self.irreversible = True def add_one_time_default(self, field, field_def):
def deal_with_not_null_no_default(self): # If it's a CharField or TextField that's blank, skip this step. if isinstance(self.field, (CharField, TextField)) and self.field.blank: self.field_def[2]['default'] = repr("") return # Oh dear. Ask them what to do. print " ? The field '%s.%s' does not have a default specified, ...
self.field_def[2]['default'] = repr(result)
field_def[2]['default'] = repr(result) def irreversable_code(self, field): return self.IRREVERSIBLE_TEMPLATE % { "model_name": self.model._meta.object_name, "table_name": self.model._meta.db_table, "field_name": field.name, "field_column": field.column, } class AddField(Action, _NullIssuesField): """ Adds a field to...
def add_one_time_default(self): # OK, they want to pick their own one-time default. Who are we to refuse? print " ? Please enter Python code for your one-off default value." print " ? The datetime module is available, so you can do e.g. datetime.date.today()" while True: code = raw_input(" >>> ") if not code: print " !...
irreversible = False IRREVERSIBLE_TEMPLATE = ''' raise RuntimeError( "Cannot reverse this migration. '%(model_name)s.%(field_name)s' and its values cannot be restored.")''' def deal_with_not_null_no_default(self): print " ? The field '%s.%s' does not have a default specified, yet is NOT NULL." % ( self.model._meta....
null_reason = "removing this field" allow_third_null_option = True
def backwards_code(self): return self.BACKWARDS_TEMPLATE % { "model_name": self.model._meta.object_name, "table_name": self.model._meta.db_table, "field_name": self.field.name, "field_column": self.field.column, }
return self.IRREVERSIBLE_TEMPLATE % { "model_name": self.model._meta.object_name, "table_name": self.model._meta.db_table, "field_name": self.field.name, "field_column": self.field.column, } class ChangeField(Action):
return self.irreversable_code(self.field) class ChangeField(Action, _NullIssuesField):
def backwards_code(self): if not self.irreversible: return AddField.forwards_code(self) else: return self.IRREVERSIBLE_TEMPLATE % { "model_name": self.model._meta.object_name, "table_name": self.model._meta.db_table, "field_name": self.field.name, "field_column": self.field.column, }