示例#1
0
# any later version.

# Mathmaker is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with Mathmaker; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

from mathmaker.lib import shared
from mathmaker.lib.tools.xml_sheet import get_xml_sheets_paths
from mathmaker.lib.sheet import S_Generic

XML_SHEETS = get_xml_sheets_paths()


def test_tables2_9():
    """Checks if 'table_2_9' is generated without any error."""
    shared.machine.write_out(str(S_Generic(XML_SHEETS['tables2_9'])))


def test_divisions():
    """Checks if 'divisions' is generated without any error."""
    shared.machine.write_out(str(S_Generic(XML_SHEETS['divisions'])))


def test_mini_problems():
    """Checks if 'mini_problems' is generated without any error."""
    shared.machine.write_out(str(S_Generic(XML_SHEETS['mini_problems'])))
示例#2
0
def entry_point():
    settings.init()
    XML_SHEETS = get_xml_sheets_paths()
    log = settings.mainlogger
    startup_actions.check_dependencies(
        euktoeps=settings.euktoeps,
        xmllint=settings.xmllint,
        lualatex=settings.lualatex,
        luaotfload_tool=settings.luaotfload_tool)
    parser = argparse.ArgumentParser(description='Creates maths exercices '
                                     'sheets and their solutions.')
    parser.add_argument('-l',
                        '--language',
                        action='store',
                        dest='lang',
                        default=settings.language,
                        help='force the language of the output to LANGUAGE. '
                        'This will override any value you may have set '
                        'in ~/.config/mathmaker/user_config.yaml')
    parser.add_argument('--pdf',
                        action='store_true',
                        dest='pdf_output',
                        help='the output will be in pdf format instead '
                        'of LaTeX')
    parser.add_argument('-d',
                        '--output-directory',
                        action='store',
                        dest='outputdir',
                        default=settings.outputdir,
                        help='where to put the possible output files, like '
                        'pictures. '
                        'This will override any value you may have set '
                        '~/.config/mathmaker/user_config.yaml. '
                        'Left undefined, the default will be current '
                        'directory.')
    parser.add_argument('-f',
                        '--font',
                        action='store',
                        dest='font',
                        default=settings.font,
                        help='The font to use. If it\'s not installed on '
                        'your system, lualatex will not be able '
                        'to compile the document. '
                        'This will override any value you may have set '
                        'in ~/.config/mathmaker/user_config.yaml')
    parser.add_argument('--encoding',
                        action='store',
                        dest='encoding',
                        default=settings.encoding,
                        help='The encoding to use. Take care it\'s available '
                        'on your system, otherwise lualatex will not be '
                        'able to compile the document. '
                        'This will override any value you may have set '
                        'in ~/.config/mathmaker/user_config.yaml')
    parser.add_argument('main_directive',
                        metavar='[DIRECTIVE|FILE]',
                        help='this can either match a sheetname included in '
                        'mathmaker, or a mathmaker xml file, or it may '
                        'be the special directive "list", that will '
                        'print the complete list and exit.')
    parser.add_argument('--version', '-v', action='version', version=__info__)
    args = parser.parse_args()
    startup_actions.install_gettext_translations(language=args.lang)
    # From now on, settings.language has its definitive value
    settings.outputdir = args.outputdir
    settings.font = args.font
    settings.encoding = args.encoding
    settings.locale = settings.language + '.' + settings.encoding
    locale.setlocale(locale.LC_ALL, settings.locale)
    startup_actions.check_settings_consistency()
    shared.init()

    if args.main_directive == 'list':
        sys.stdout.write(list_sheets.list_all_sheets())
        shared.db.close()
        sys.exit(0)
    elif args.main_directive in sheet.AVAILABLE:
        sh = sheet.AVAILABLE[args.main_directive][0]()
    elif args.main_directive in XML_SHEETS:
        sh = sheet.S_Generic(filename=XML_SHEETS[args.main_directive])
    elif os.path.isfile(args.main_directive):
        sh = sheet.S_Generic(filename=args.main_directive)
    else:
        log.error(args.main_directive + " is not a correct directive for " +
                  __software_name__ +
                  ", you can run `mathmaker list` to get the complete "
                  "list of directives.")
        # print("--- {sec} seconds ---"\
        #      .format(sec=round(time.time() - start_time, 3)))
        shared.db.close()
        sys.exit(1)

    try:
        shared.machine.write_out(str(sh), pdf_output=args.pdf_output)
    except Exception:
        log.error("An exception occured during the creation of the sheet.",
                  exc_info=True)
        shared.db.close()
        sys.exit(1)

    shared.db.commit()
    shared.db.close()
    log.info("Done.")
    sys.exit(0)
示例#3
0
    def do_GET(self):
        # settings.init() is required here in order to have the logger
        # working (if it's in run(), even in the with clause, it works once)
        settings.init()
        log = settings.daemon_logger
        # If the db is too old (more than 1 hour, hardcoded), we delete it.
        now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        now_timestamp = time.mktime(datetime.strptime(now, "%Y-%m-%d %H:%M:%S")
                                    .timetuple())
        if os.path.isfile(settings.path.daemon_db):
            t = time.strftime('%Y-%m-%d %H:%M:%S',
                              time.localtime(os.path.getmtime(
                                  settings.path.daemon_db)))
            last_access_timestamp = time.mktime(datetime.strptime(t,
                                                "%Y-%m-%d %H:%M:%S")
                                                .timetuple())
            if now_timestamp - last_access_timestamp >= 3600:
                os.remove(settings.path.daemon_db)

        # If there's no db, a brand new one is created
        if not os.path.isfile(settings.path.daemon_db):
            open(settings.path.daemon_db, 'a').close()
            db = sqlite3.connect(settings.path.daemon_db)
            db.execute('''CREATE TABLE ip_addresses
                       (id INTEGER PRIMARY KEY,
                       ip_addr TEXT, timeStamp TEXT)''')
            db.close()

        XML_SHEETS = get_xml_sheets_paths()
        all_sheets = {}
        all_sheets.update(sheet.AVAILABLE)
        all_sheets.update(XML_SHEETS)
        query = parse_qs(self.path[2:])
        if not (1 <= len(query) <= 2):
            self.send_response(404)
            self.send_header('Content-Type', 'text/html')
            self.end_headers()
            self.wfile.write(bytes('Error 404: one or two parameters allowed',
                                   'UTF-8'))
            log.warning(self.address_string() + ' ' + self.requestline
                        + ' 404 (only one or two parameters allowed)')
        else:
            if ('sheetname' not in query
                or (len(query) == 2 and 'ip' not in query)):
                # __
                self.send_response(404)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                self.wfile.write(bytes('Error 404: sheetname must be in '
                                       'parameters. Only ip is accepted as '
                                       'other possible argument.',
                                       'UTF-8'))
                log.warning(self.address_string() + ' ' + self.requestline
                            + ' 404 (sheetname not in query or '
                            'second argument different from ip)')
            else:
                block_ip = False
                if 'ip' in query:
                    db = sqlite3.connect(settings.path.daemon_db)
                    cmd = "SELECT id,timeStamp FROM ip_addresses "\
                          "WHERE ip_addr = '" + query['ip'][0]\
                          + "' ORDER BY timeStamp DESC LIMIT 1;"
                    #   + " AND WHERE "\
                    #   "timeStamp >= datetime('now','-10 seconds');"
                    qr = tuple(db.execute(cmd))
                    most_recent_request_timestamp = 0
                    if len(qr):
                        most_recent_request_timestamp = \
                            time.mktime(datetime.strptime(qr[0][1],
                                                          "%Y-%m-%d %H:%M:%S")
                                        .timetuple())
                    cmd = "INSERT INTO ip_addresses VALUES(null, '" \
                          + query['ip'][0] + "', '" \
                          + datetime.now().strftime('%Y-%m-%d %H:%M:%S') \
                          + "');"
                    db.execute(cmd)
                    db.commit()
                    db.close()
                    if (len(qr)
                        and (now_timestamp - most_recent_request_timestamp
                             <= MINIMUM_TIME_INTERVAL)):
                        # __
                        block_ip = True
                        self.send_response(429)
                        self.send_header('Content-Type', 'text/html')
                        self.end_headers()
                        self.wfile.write(bytes('Error 429: wait at least 10 s '
                                               'between two requests.',
                                               'UTF-8'))
                        log.warning(self.address_string()
                                    + ' ' + self.requestline + ' '
                                    '429 (too many requests) '
                                    'from ip ' + query['ip'][0])

                if not block_ip:
                    if query['sheetname'][0] in all_sheets:
                        document = ''
                        try:
                            p = Popen([settings.mm_executable,
                                       '--pdf',
                                       query['sheetname'][0]],
                                      stdout=PIPE)
                            document = p.stdout.read()
                        except Exception:
                            self.send_response(500)
                            self.send_header('Content-Type', 'text/html')
                            self.end_headers()
                            self.wfile.write(bytes('Error 500: something '
                                                   'failed',
                                                   'UTF-8'))
                            log.error(self.address_string() + ' '
                                      + self.requestline + ' 500',
                                      exc_info=True)
                        else:
                            self.send_response(200)
                            self.send_header('Content-Type', 'application/pdf')
                            self.end_headers()
                            self.wfile.write(document)
                            log.info(self.address_string() + ' '
                                     + self.requestline + ' 200')
                    else:
                        self.send_response(404)
                        self.send_header('Content-Type', 'text/html')
                        self.end_headers()
                        self.wfile.write(bytes('Error 404: No such sheetname',
                                               'UTF-8'))

                        log.warning(self.address_string() + ' '
                                    + self.requestline
                                    + ' 404 (no such sheetname)')