Пример #1
0
exports.css.updater = function (filepath, data, callback) {
  data = data.toString();

  debug('Creating css update call');

  if (this.options.minify) {
    debug('CSS uglify: %s, length: %d', filepath, data.length);
    data = uglifycss.processString(data);
    debug('CSS after uglify: %s, length: %d', filepath, data.length);
  }

  data = stringUtils.escapeStringForJavascript(data);

  var result = {
    other: [
      {
        type: 'eval', eval: "require('/" +
        path.relative(this.options.input, filepath) +
        "').innerHTML = '" + data + "';"
      }
    ]
  };

  callback(null, result);
};
Пример #2
0
 minify: function (source) {
     var options = {
         maxLineLen: 0,
         expandVars: false,
         uglyComments: true
     };
     var uglifycss = require('uglifycss');
     return uglifycss.processString(source, options);
 }
Пример #3
0
function UglifyCSSMinifier(asset, context, done) {
  var options = context.minify;
  if ('object' === typeof options) {
    options = _extend(_extend({}, DEFAULT_UGLIFY_OPTIONS), options);
  } else {
    options = DEFAULT_UGLIFY_OPTIONS;
  }

  asset.body = UGLIFY.processString(asset.body, options);
  done();
}
Пример #4
0
Файл: do.js Проект: zjliu/editor
function doArticle(type,min,value,articleData,res){
	var contentValue = '';
	switch(type.toLowerCase()){
		case 'javascript':
		case 'js':
			contentValue = "application/x-javascript";
			if(min){
				try{
					var UglifyJS = require("uglify-js");
					var result = UglifyJS.minify(value, {fromString: true});
					value = result.code;
				}catch(e){
					console.log(e.message);
				}
			}
		break;
		case 'css':
			contentValue = 'text/css';
			if(min){
				try{
					var uglifycss = require('uglifycss');
					value = uglifycss.processString(value);
				}catch(e){
					console.log(e.message);
				}
			}
		break;
		case 'markdown':
		case 'md':
			try{
				/*
				var md = require('markdown').markdown;
				value = md.toHTML(value);
				*/
				var MarkdownIt = require('markdown-it'),
					md = new MarkdownIt();
					value = md.render(value);
				value = createBlog(articleData.title,value,articleData.cdate,articleData.udate,articleData.aid);
			}catch(e){
				console.log(e.message);
			}
			contentValue =  'text/html';
		break;
		case 'html':
			contentValue =  'text/html';
		break;
	}
	if(contentValue){
		res.writeHead(200,{"Content-Type":`${contentValue};charset=utf-8`});
		res.write(value);
		res.end();
	}
}
Пример #5
0
 this.getUrl(function (error, body) {
     if (error) {
         callback({ error: error });
     }else{
         //minify
         body = uglifycss.processString(body);
         
         callback({
             type: 'css',
             js: helpers.cssToJs(body)
         });
     }
 });
Пример #6
0
 _.forEach(fields, (value, key) => {
     settingsFile[key] = value;
     if(key === 'customCss_input'){
         settingsFile['customCss'] = escape.encode(uglifycss.processString(value));
     }
     if(key === 'footerHtml_input'){
         let footerHtml = typeof value !== 'undefined' || value === '' ? escape.encode(value) : '';
         settingsFile['footerHtml'] = footerHtml;
     }
     if(key === 'googleAnalytics_input'){
         let googleAnalytics = typeof value !== 'undefined' ? escape.encode(value) : '';
         settingsFile['googleAnalytics'] = googleAnalytics;
     }
 });
Пример #7
0
app.post('/css', upload.fields(mfields), function (req, resp) {
    if(!(req.headers.authorization == api_key || req.body.api_key == api_key))
        return errorResponse(resp, "Authorization failed")

    console.log(req.files)
    var cssString = "";
    for(var _file in req.files)
        for(var i in req.files[_file])
            cssString = cssString + req.files[_file][i].buffer.toString();

    var UglifyCSS = require("uglifycss");
    var result = UglifyCSS.processString(cssString)
    console.log("Response length: " + result.length);
    resp.send(JSON.stringify({status: "ok", css: new Buffer(result).toString("base64")}))
})
Пример #8
0
exports.css = function (filepath, data, callback) {

  data = data.toString();

  if (this.options.minify) {
    debug('CSS uglify: %s, length: %d', filepath, data.length);
    data = uglifycss.processString(data);
    debug('CSS after uglify: %s, length: %d', filepath, data.length);
  }

  data = stringUtils.escapeStringForJavascript(data);

  var result = " var style = module.exports = document.createElement('style');\n";
  result += " style.appendChild(document.createTextNode('" + data + "'));";

  callback(null, result);
};
Пример #9
0
var miniInline = function(content, type, options){
    var isMinifyCss = options && !!options.minifyCss,
        isMinifyJs  = options && !!options.minifyJs,
        ignore      = options['ignore'] || 'ignore',
        basePath    = options['basePath'] || '',
        queryKey    = options['queryKey'] || '_gm_inline',
        queryRegx   = new RegExp('&*'+ queryKey +'[=|&]?', 'i'),
        code = content,
        tags;

    tags = content.match(/<[\s\S]*?<*\/*[\s\S]*?>/gi);

    if(tags && tags[0] && tags[0].indexOf(ignore) !== -1)
        return content;

    if('css' === type){
        if(!isMinifyCss) return content;
        code = uglifycss.processString(content, options);
    }
    else if('js' === type){
        if(!isMinifyJs) return content;

        /**
         * FIX BUGS FOR replace
         */
        // gmutil.alert('content: \n'+content)
        // gmutil.alert('opts: \n'+JSON.stringify(options))

        var pt = /(?=['"]?)([\w\/\-\?\&\=]*?\.js)(?=['"]?)/gm,
            item

        // 如果没有标记inline,那么不处理
        if((item = content.match(pt)) && (item = item[0])){
            if(!item.match(queryRegx)) return content
        }

        // gmutil.alert(jsmin(content, options).code)
        code = jsmin(content, options).code.replace(/\n*\t*/gi, '');
    }
    return code;
};
Пример #10
0
    req.on('end',function(){
        console.log(req.url);

        if (req.url.startsWith("/js")) {
            try {
                var result = UglifyJS.minify(body, {fromString: true});
                resp.end(result.code);
            } catch (err) {
                console.log(err);
                resp.writeHead(400, {'Content-Type': 'text/plain'});
                resp.end("parse error");
            }
        } else {
            try {
                var result = uglifycss.processString(body);
                resp.end(result);
            } catch (err) {
                console.log(err);
                resp.writeHead(400, {'Content-Type': 'text/plain'});
                resp.end("parse error");
            }
        }
    });
/**
 *
 * @method compileStylesheets
 * @param {function} callback Handle composition done
 * @private
 *
 */
function compileStylesheets( callback ) {
    var reset = path.join( directories.styles, "reset.css" ),
        lessCss = "",
        pureCss = "",
        fpath,
        file;

    if ( fs.existsSync( reset ) ) {
        pureCss += functions.readFile( reset );
    }

    for ( var i = 0, len = config.stylesheets.length; i < len; i++ ) {
        fpath = path.join( directories.styles, config.stylesheets[ i ] );

        if ( !fs.existsSync( fpath ) ) {
            continue;
        }

        file = ("" + fs.readFileSync( fpath ));

        if ( rLess.test( config.stylesheets[ i ] ) ) {
            lessCss += file;

        } else {
            pureCss += file;
        }
    }

    less.render( lessCss, function ( error, css ) {
        lessCss = css;
    });

    siteCss = uglifycss.processString( (pureCss + lessCss) );

    return callback;
}
Пример #12
0
  function compress() {
    try {
      var final_code;
      if (/\.js$/.test(name)) {
        // extract copyright
        var copyright = extract_copyright(orig_code) || "";
        if (copyright.length) copyright += "\n\n";

        // compress javascript
        var ast = jsp.parse(orig_code); // parse code and get the initial AST
        ast = pro.ast_mangle(ast); // get a new AST with mangled names
        ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
        final_code = copyright + pro.split_lines(pro.gen_code(ast), 32 * 1024); // compressed code here
      } else if (/\.css$/.test(name)) {
        // compress css
        final_code = uglifycss.processString(orig_code);
      } else {
        return cb("can't determine content type: " + name);
      }
      cb(null, final_code);
    } catch(e) {
      cb("error compressing: " + e.toString() + "\n");
    }
  }
Пример #13
0
        this.minifyCSS = function (files, outputFile) {
            var value = '',
                j,
                content,
                packed;

            // read files to value
            grunt.log.writeln('Concatenating and minifying ' + files.length + ' files');
            for (j = 0; j < files.length; j += 1) {
                if (!fs.existsSync(files[j])) {
                    grunt.fail.fatal('Couldnt locate ' + files[j]);
                }
                content = fs.readFileSync(files[j], 'utf8');
                value = value + '\n' + content;
            }

            // FIXME: Make a better effort when improving tooling for Oskari2
            // fix image paths to minified form
            // "../images/pic.png" -> "./images/pic.png"
            value = value.replace(/\.\.\/images\//g, replaceImageDir);
            // "../../../something/resources/images/pic.png" -> "./images/pic.png"
            value = value.replace(/\.\.\/\.\.\/\.\.\/.*\/images\//g, replaceImageDir);

            // minify value
            packed = cssPacker.processString(value);
            grunt.log.writeln('Writing packed CSS to ' + outputFile);

            // write value to outputfile
            fs.writeFile(outputFile, packed, function (err) {
                // ENOENT means the file did not exist, which is ok. Let's just create it.
                if (err && err.code !== 'ENOENT') {
                    grunt.fail.fatal('Error writing packed CSS: ' + err);
                }
                done();
            });
        };
Пример #14
0
router.post('/css', cssParser, function(req, res, next) {
	res.send(uglifycss.processString(req.body));
});
Пример #15
0
function compressCSS(code) {
  var uglifycss=require('uglifycss');
  return uglifycss.processString(code);
}
Пример #16
0
#!/usr/bin/env node

process.chdir(__dirname)
process.chdir('..')

var fs = require('fs'),
    uglifyCss = require('uglifycss')

var files = [
    'js/Main.css',
    'js/Blink.css',
    'js/Field.css',
    'js/MainPanel.css',
    'js/MuteButton.css',
    'js/TapButton.css',
]

var source = ''
files.forEach(function (file) {
    source += fs.readFileSync(file, 'utf-8') + '\n'
})

var compressCss = uglifyCss.processString(source)
fs.writeFileSync('compressed.css', compressCss)
Пример #17
0
		    result = fileList.map(function(filePath) {
				var content=_fs.readFileSync(filePath, FILE_ENCODING);
				content=uglifyCSS.processString(optimize.flattenCss(filePath,content));
				return content;
			});
Пример #18
0
    'RootPane.css',
    'SaveChangesConfirmDialog.css',
    'SaveFileDialog.css',
    'SearchFilesDialog.css',
    'ShareSessionDialog.css',
    'SidePane.css',
    'Spinner.css',
    'Tabs/Tab.css',
    'Tabs/Tabs.css',
    'TextField.css',
    'ToggleToolButton.css',
    'ToolBar.css',
    'BottomToolBar.css',
    'ToolBarSeparator.css',
    'ToolButton.css',
    'TopLabel.css',
    'FileList/EmptyFolder.css',
    'FileList/FileItem.css',
    'FileList/FolderItem.css',
    'FileList/List.css',
    'Main.css',
]

var source = ''
files.forEach(function (file) {
    source += fs.readFileSync('javascript/' + file, 'utf8') + '\n'
})

source = uglifyCss.processString(source)
fs.writeFileSync('compressed.css', source)
Пример #19
0
}, function(){
	Object.keys(serverConfig.users).forEach(function(currusername){
		if (!userTimestamps.hasOwnProperty(currusername)) {
			return;
		}

		var points = 0;
		Object.keys(contestProblems).forEach(function(currproblemid){
			var currproblem = contestProblems[currproblemid];
			if (currproblem.testcases.length < 1) {
				return;
			}
			console.log('Evaluating problem "' + currproblemid + '" for user "' + currusername + '"...');
			if (!currproblem.userdata[currusername]) {
				currproblem.userdata[currusername] = {code: getEmptyCode(currproblemid, currproblem.name)};
			}
			var curruserproblem = currproblem.userdata[currusername];
			curruserproblem.success = false;
			curruserproblem.error = false;
			curruserproblem.testcases = [];
			curruserproblem.successcount = 0;
			currproblem.testcases.some(function(currrawproblem){
				var currtestcase = [];
				currtestcase.initialtape = currrawproblem[0];
				currtestcase.expectedtape = currrawproblem[1];
				currtestcase.outcome = 'Not Run';
				currtestcase.steps = 0;
				currtestcase.endstate = '';
				currtestcase.finaltape = '';
				currtestcase.warnings = [];
				currtestcase.instance = new TuringMachine({
					code: curruserproblem.code,
					tapetext: currtestcase.initialtape,
					onstop: function(){
						currtestcase.outcome = 'Run';
					},
					onerror: function(obj){
						curruserproblem.error = obj;
					},
					onwarning: function(warning){
						currtestcase.warnings.push(warning);
					}
				});
				currtestcase.instance.start();
				while (currtestcase.instance.stepcount <= serverConfig.results.maxSteps && currtestcase.instance.tick());
				currtestcase.steps = currtestcase.instance.stepcount;
				currtestcase.endstate = currtestcase.instance.currstate;
				currtestcase.finaltape = String(currtestcase.instance.tapetext).replace(new RegExp('^ *(.*?) *$'), '$1');
				delete currtestcase.instance;
				if (curruserproblem.error) {
					return true;
				}
				if (currtestcase.outcome !== 'Run' && currtestcase.steps > serverConfig.results.maxSteps) {
					console.log('Timeout!');
					currtestcase.outcome = 'Timeout';
				} else if (currtestcase.outcome === 'Run' && currtestcase.finaltape === currtestcase.expectedtape) {
					currtestcase.success = true;
					curruserproblem.successcount++;
				}
				curruserproblem.testcases.push(currtestcase);
			});
			if (curruserproblem.successcount === currproblem.testcases.length) {
				curruserproblem.success = true;
				if (currproblem.points) {
					points += currproblem.points;
				}
			}
		});

		var lastsavedate = new Date(userTimestamps[currusername]);
		var lastsavetime = getLastSaveTime(lastsavedate);
		var contestTableHtml = '<div id="results"><h1 align="center">Verifica della gara del '+lastsavedate.getDate()+'/'+(lastsavedate.getMonth()+1)+'/'+lastsavedate.getFullYear()+'</h1><p>Per provare usare il <a href="#simulator">simulatore</a> pre-caricato con i problemi della squadra \'<i>'+sanitizer.escape(String(currusername))+'</i>\'.</p><h2>Sommario ('+points+' punt'+(points === 1 ? 'o' : 'i')+', ultimo salvataggio '+lastsavetime+')</h2><table border="1"><tr><th>Problem</th><th>Points</th><th>Result</th><th>Count</th></tr>';
		Object.keys(contestProblems).forEach(function(currproblemid){
			var currproblem = contestProblems[currproblemid];
			contestTableHtml += '<tr><td><a';
			if (currproblem.testcases.length > 0) {
				contestTableHtml += ' href="#'+sanitizer.escape(String(currproblemid))+'"';
			}
			contestTableHtml += '>'+sanitizer.escape(String(currproblem.name))+'</a> (<a href="progs/'+sanitizer.escape(String(currproblemid))+'.t">download</a>)</td>';
			if (currproblem.testcases.length > 0) {
				contestTableHtml += '<td>' + currproblem.points + '</td>';
				var xcolor = (currproblem.userdata[currusername].success ? 'green' : (currproblem.userdata[currusername].successcount > 0 ? 'yellow' : 'red'));
				contestTableHtml += '<td class="' + xcolor + '">' + (currproblem.userdata[currusername].success ? 'OK' : 'FAIL') + '</td>';
				contestTableHtml += '<td class="' + xcolor + '">' + currproblem.userdata[currusername].successcount + '/' + currproblem.testcases.length + '</td>';
			} else {
				contestTableHtml += '<td>N/A</td><td>N/A</td><td>N/A</td>';
			}
			contestTableHtml += '</tr>';
		});
		contestTableHtml += '</table>';
		Object.keys(contestProblems).forEach(function(currproblemid){
			var currproblem = contestProblems[currproblemid];
			if (currproblem.testcases.length < 1) {
				return;
			}
			var curruserproblem = currproblem.userdata[currusername];
			contestTableHtml += '<h2><a name="'+sanitizer.escape(String(currproblemid))+'">'+sanitizer.escape(String(currproblem.name))+'</a> ('+currproblem.points+' punt'+(currproblem.points === 1 ? 'o' : 'i')+')</h2><table border="1"><tr><th>Outcome</th><th>Input</th><th>Output</th><th>Atteso</th><th>Passi</th><th>Risultato</th></tr>';
			if (curruserproblem.error) {
				contestTableHtml += '<tr><td colspan="6" style="color:#f00">'+sanitizer.escape(String((curruserproblem.error.errorType === 'syntax' ? String(currlang.SYNTAX_ERROR_LABEL).replace('%d', curruserproblem.error.errorLine + 1) : currlang.UNKNOWN_ERROR_LABEL) + ' ' + currlang[curruserproblem.error.errorMessage]))+'</td></tr>';
			} else {
				curruserproblem.testcases.forEach(function(currtestcase){
					contestTableHtml += '<tr><td>'+sanitizer.escape(String(currtestcase.outcome))+'</td><td class="codecell">'+sanitizer.escape(String(currtestcase.initialtape))+'</td><td class="codecell">'+sanitizer.escape(String(currtestcase.finaltape))+'</td><td class="codecell">'+sanitizer.escape(String(currtestcase.expectedtape))+'</td><td>'+currtestcase.steps+'</td><td class="'+(currtestcase.success ? 'green' : 'red')+'">'+(currtestcase.success ? 'OK' : 'FAIL')+'</td></tr>';
				});
			}
			contestTableHtml += '</table>';
		});
		contestTableHtml += '<h2 align="center"><a name="simulator">Simulatore pre-caricato con i problemi della squadra \'<i>'+sanitizer.escape(String(currusername))+'</i>\'</a></h2></div>';

		fs.mkdirSync(path.join(resultsDirName, currusername));
		fs.mkdirSync(path.join(resultsDirName, currusername, 'progs'));

		var preloadedProblems = [];
		Object.keys(contestProblems).forEach(function(currproblemid){
			var currproblem = contestProblems[currproblemid];
			var currcode = (currproblem.userdata[currusername] ? currproblem.userdata[currusername].code : getEmptyCode(currproblemid, currproblem.name));
			preloadedProblems.push({name: currproblem.name, code: currcode});
			fs.writeFileSync(path.join(resultsDirName, currusername, 'progs', currproblemid + '.t'), currcode);
		});
		fs.writeFileSync(path.join(resultsDirName, currusername, 'index.html'), ('<!doctype html>\n<!-- saved from url=(0014)about:internet -->\n<!--\n' + licenseText + '--><html class="notranslate"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><title>Turing Machine Competition Results</title>' + htmlheadHtml + '<style>' + uglifycss(String(cssStyle)) + '</style>' + iecsshacksHtml + '</head><body class="loadmode displayresults">' + contestTableHtml + turingMachineHtml + '<script>' + uglifyjs.minify('(function(){' + turingMachineJS + i18nJS + handleHTMLPageJS + 'var preloadedProblems = '+JSON.stringify(preloadedProblems)+';' + handlePreloadedProblemsJS + '})();', {fromString: true}).code + '</script></body></html>').replace(new RegExp('(?:\\r\\n|\\n|\\r)', 'g'), '\r\n')); // just another IE 6 fix
		fs.writeFileSync(path.join(resultsDirName, currusername, 'jstmsimulator.gif'), jstmsimulatorGif);

		userPoints[currusername] = points;

		// TODO creare htpasswd e htaccess qui. il realm sta in serverConfig.results.authRealm, l'username sta in currusername e la password sta in serverConfig.users[currusername]

		console.log('');
	});
	var lastsavedate = new Date(lastTimestamp);
	var lastsavetime = getLastSaveTime(lastsavedate);
	var contestTableHtml = '<div id="results"><h1 align="center">Classifica della gara del '+lastsavedate.getDate()+'/'+(lastsavedate.getMonth()+1)+'/'+lastsavedate.getFullYear()+'</h1><h2>Ultimo salvataggio globale: '+lastsavetime+'</h2><table border="1"><tr><th>Posizione</th><th>Nome utente</th><th>Punteggio</th><th>Ultimo salvataggio</th>';
	var contestCSV = '"Nome utente";"Posizione";"Punteggio";"Ultimo salvataggio"\n';
	Object.keys(contestProblems).forEach(function(currproblemid){
		var currproblem = contestProblems[currproblemid];
		if (currproblem.testcases.length > 0) {
			contestTableHtml += '<th class="prob">' + sanitizer.escape(String(currproblem.name)) + '</th>';
		}
	});
	contestTableHtml += '</tr>';

	Object.keys(serverConfig.users).filter(function(currusername){
		return !!userTimestamps.hasOwnProperty(currusername);
	}).sort(function(a, b){
		if (userPoints[a] != userPoints[b]) {
			return userPoints[b] - userPoints[a];
		}
		if (!isNaN(userTimestamps[a]) && !isNaN(userTimestamps[b])) {
			return userTimestamps[a] - userTimestamps[b];
		}
		if (isNaN(userTimestamps[a]) && !isNaN(userTimestamps[b])) {
			return b;
		}
		if (isNaN(userTimestamps[b]) && !isNaN(userTimestamps[a])) {
			return a;
		}
		return a < b ? -1 : 1;
	}).forEach(function(currusername, j){
		if (!serverConfig.results.startFromZero) {
			j++;
		}
		contestTableHtml += '<tr><td>'+j+'°</td><td><a href="'+sanitizer.escape(String(currusername))+'">'+sanitizer.escape(String(currusername))+'</a></td><td>'+userPoints[currusername]+'</td><td>'+sanitizer.escape(String(getLastSaveTime(new Date(userTimestamps[currusername]))))+'</td>';
		contestCSV += '"' + sanitizer.escape(String(currusername)) + '","'+j+'","'+userPoints[currusername]+'","'+sanitizer.escape(String(getLastSaveTime(new Date(userTimestamps[currusername]))))+'"\n';
		Object.keys(contestProblems).forEach(function(currproblemid){
			var currproblem = contestProblems[currproblemid];
			if (currproblem.testcases.length > 0) {
				contestTableHtml += '<td class="prob ' + (currproblem.userdata[currusername].success ? 'green' : (currproblem.userdata[currusername].successcount > 0 ? 'yellow' : 'red')) + '">' + currproblem.userdata[currusername].successcount + '/' + currproblem.testcases.length + '</td>';
			}
		});
		contestTableHtml += '</tr>';
	});
	contestTableHtml += '</table></div>';

	fs.writeFileSync(path.join(resultsDirName, 'index.html'), ('<!doctype html>\n<!-- saved from url=(0014)about:internet -->\n<!--\n' + licenseText + '--><html class="notranslate"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><title>Turing Machine Competition Results</title>' + htmlheadHtml + '<style>' + uglifycss(String(cssStyle)) + '</style>' + iecsshacksHtml + '</head><body class="loadmode displayresults">' + contestTableHtml + '</body></html>').replace(new RegExp('(?:\\r\\n|\\n|\\r)', 'g'), '\r\n')); // just another IE 6 fix
	fs.writeFileSync(path.join(resultsDirName, 'index.csv'), contestCSV);

	console.log('Results written into ' + resultsDirName);
});
Пример #20
0
 return contents.then(function(v) { return uglifycss.processString(v); });
Пример #21
0
	db.each('SELECT username, password FROM users', function(err, row){
		if (!(!err && row)) {
			throw new Error('select users failed');
		}
		var points = 0;
		contestProblems.forEach(function(currproblem){
			if (currproblem.testcases.length < 1) {
				return;
			}
			console.log('Evaluating problem "' + currproblem.id + '" for user "' + row.username + '"...');
			if (!currproblem.userdata[row.username]) {
				currproblem.userdata[row.username] = {code: getEmptyCode(currproblem.id, currproblem.name)};
			}
			var curruserproblem = currproblem.userdata[row.username];
			curruserproblem.success = false;
			curruserproblem.error = false;
			curruserproblem.testcases = [];
			curruserproblem.successcount = 0;
			currproblem.testcases.some(function(currrawproblem, j){
				var currtestcase = [];
				currtestcase.initialtape = currrawproblem.initialtape;
				currtestcase.expectedtape = currrawproblem.expectedtape;
				currtestcase.outcome = 'Not Run';
				currtestcase.steps = 0;
				currtestcase.endstate = '';
				currtestcase.finaltape = '';
				currtestcase.warnings = [];
				currtestcase.instance = new TuringMachine({
					code: curruserproblem.code,
					tapetext: currtestcase.initialtape,
					onstop: function(){
						currtestcase.outcome = 'Run';
					},
					onerror: function(obj){
						curruserproblem.error = obj;
					},
					onwarning: function(warning){
						currtestcase.warnings.push(warning);
					}
				});
				currtestcase.instance.start();
				while (currtestcase.instance.stepcount <= 100000 && currtestcase.instance.tick());
				currtestcase.steps = currtestcase.instance.stepcount;
				currtestcase.endstate = currtestcase.instance.currstate;
				currtestcase.finaltape = String(currtestcase.instance.tapetext).replace(new RegExp('^ *(.*?) *$'), '$1');
				delete currtestcase.instance;
				if (curruserproblem.error) {
					return true;
				}
				if (currtestcase.outcome !== 'Run' && currtestcase.steps > 100000) {
					currtestcase.outcome = 'Timeout';
				} else if (currtestcase.outcome === 'Run' && currtestcase.finaltape === currtestcase.expectedtape) {
					currtestcase.success = true;
					curruserproblem.successcount++;
				}
				curruserproblem.testcases.push(currtestcase);
			});
			if (curruserproblem.successcount === currproblem.testcases.length) {
				curruserproblem.success = true;
				if (currproblem.points) {
					points += currproblem.points;
				}
			}
		});
		//console.dir(contestProblems);

		var lastsavedate = new Date(userTimestamps[row.username]);
		var lastsavehour = lastsavedate.getHours();
		var lastsavemins = lastsavedate.getMinutes();
		var lastsavesecs = lastsavedate.getSeconds();
		var lastsavetime = (lastsavehour < 10 ? '0' : '') + lastsavehour + ':' + (lastsavemins < 10 ? '0' : '') + lastsavemins + ':' + (lastsavesecs < 10 ? '0' : '') + lastsavesecs;
		var contestTableHtml = '<div id="results"><h1 align="center">Verifica della gara del '+lastsavedate.getDate()+'/'+(lastsavedate.getMonth()+1)+'/'+lastsavedate.getFullYear()+'</h1><p>Per provare usare il <a href="#simulator">simulatore</a> pre-caricato con i problemi della squadra \'<i>'+sanitizer.escape(String(row.username))+'</i>\'.</p><h2>Sommario ('+points+' punt'+(points === 1 ? 'o' : 'i')+', ultimo salvataggio '+lastsavetime+')</h2><table border="1">';
		contestProblems.forEach(function(currproblem, j){
			contestTableHtml += '<tr><td><a'+(currproblem.testcases.length > 0 ? ' href="#'+sanitizer.escape(String(currproblem.id))+'"' : '')+'>'+sanitizer.escape(String(currproblem.name))+'</a> (<a href="progs/'+sanitizer.escape(String(currproblem.id))+'.t">download</a>)</td><td>'+(currproblem.testcases.length > 0 ? (currproblem.userdata[row.username].success ? 'OK' : 'FAIL') : 'N/A')+'</td><td>'+(currproblem.testcases.length > 0 ? currproblem.points : 'N/A')+'</td></tr>';
		});
		contestTableHtml += '</table>';
		contestProblems.forEach(function(currproblem, j){
			if (currproblem.testcases.length < 1) {
				return;
			}
			var curruserproblem = currproblem.userdata[row.username];
			contestTableHtml += '<h2><a name="'+sanitizer.escape(String(currproblem.id))+'">'+sanitizer.escape(String(currproblem.name))+'</a> ('+currproblem.points+' punt'+(currproblem.points === 1 ? 'o' : 'i')+')</h2><table border="1"><tr><td>Outcome</td><td>Input</td><td>Output</td><td>Atteso</td><td>Passi</td><td>Risultato</td></tr>';
			if (curruserproblem.error) {
				contestTableHtml += '<tr><td colspan="6"><font color="#ff0000">'+sanitizer.escape(String((curruserproblem.error.errorType === 'syntax' ? String(currlang.SYNTAX_ERROR_LABEL).replace('%d', curruserproblem.error.errorLine + 1) : currlang.UNKNOWN_ERROR_LABEL) + ' ' + currlang[curruserproblem.error.errorMessage]))+'</font></td></tr>';
			} else {
				curruserproblem.testcases.forEach(function(currtestcase){
					contestTableHtml += '<tr><td>'+sanitizer.escape(String(currtestcase.outcome))+'</td><td class="codecell">'+sanitizer.escape(String(currtestcase.initialtape))+'</td><td class="codecell">'+sanitizer.escape(String(currtestcase.finaltape))+'</td><td class="codecell">'+sanitizer.escape(String(currtestcase.expectedtape))+'</td><td>'+currtestcase.steps+'</td><td>'+(currtestcase.success ? 'OK' : 'FAIL')+'</td></tr>';
				});
			}
			contestTableHtml += '</table>';
		});
		contestTableHtml += '<h2 align="center"><a name="simulator">Simulatore pre-caricato con i problemi della squadra \'<i>'+sanitizer.escape(String(row.username))+'</i>\'</a></h2></div>';

		fs.mkdirSync(path.join(resultsDirName, row.username));
		fs.mkdirSync(path.join(resultsDirName, row.username, 'progs'));

		var preloadedProblems = [];
		contestProblems.forEach(function(currproblem){
			var currcode = (currproblem.userdata[row.username] ? currproblem.userdata[row.username].code : getEmptyCode(currproblem.id, currproblem.name));
			preloadedProblems.push({name: currproblem.name, code: currcode});
			fs.writeFileSync(path.join(resultsDirName, row.username, 'progs', currproblem.id + '.t'), currcode);
		});
		fs.writeFileSync(path.join(resultsDirName, row.username, 'index.html'), ('<!doctype html>\n<!-- saved from url=(0014)about:internet -->\n<!--\n' + licenseText + '--><html class="notranslate"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><title>Turing Machine Competition Results</title>' + htmlheadHtml + '<style>' + uglifycss(String(cssStyle)) + '</style>' + iecsshacksHtml + '</head><body class="loadmode displayresults">' + contestTableHtml + turingMachineHtml + '<script>' + uglifyjs.minify('(function(){' + turingMachineJS + i18nJS + handleHTMLPageJS + 'var preloadedProblems = '+JSON.stringify(preloadedProblems)+';' + handlePreloadedProblemsJS + '})();', {fromString: true}).code + '</script></body></html>').replace(new RegExp('(?:\\r\\n|\\n|\\r)', 'g'), '\r\n')); // just another IE 6 fix
		fs.writeFileSync(path.join(resultsDirName, row.username, 'jstmsimulator.gif'), jstmsimulatorGif);

		// TODO creare htpasswd e htaccess qui. l'username sta in row.username e la password sta in row.password

		console.log('');
	}, function(){
Пример #22
0
 minCSS = function(input){
   return uglifycss.processString(input);
 };
Пример #23
0
var replaceCallback = function(sourceRegx, match, parentFile, type, options){

    var ms = sourceRegx.exec(match),
        code = '',
        query,
        isMinifyCss = options && !!options.minifyCss,
        isMinifyJs  = options && !!options.minifyJs,
        ignore      = options['ignore'] || 'ignore',
        basePath    = options['basePath'] || '',
        queryKey    = options['queryKey'] || '_gm_inline',
        queryRegx   = new RegExp('&*'+ queryKey +'[=|&]?', 'i');

    if(!ms || !ms[2] || '' === ms[2]){
        return miniInline(match, type, options);
    }
    var attr = ms[1] || '',
        href = ms[2] || '';


    if(match.indexOf(ignore) !== -1)
            return match.replace(queryRegx, '');

    //在url地址上加上 _gm_inline_字段就可以直接嵌入网页
    query = getParams(queryKey, href);

    if(query === undefined){
        return match.replace(queryRegx, '');
    }

    // 如果使用绝对路径
    if(options['absoluteRoot']){
        var sourceFile = path.join(options['root'], options['absoluteRoot'], href.split('?')[0])
    }else {
        var sourceFile = path.normalize(path.dirname(parentFile) + path.sep + basePath + href.split('?')[0])
    }

    if(!options['is_runtime']){

        var url_runtime_dir = path.join(options['root'], options['runtime_dir']),
            url_dist_dir = path.join(options['root'], options['dist_dir']),
        sourceFile = sourceFile.replace(url_dist_dir, url_runtime_dir)
    }
    // remove the url prefix for once
    // the url is abs url
    sourceFile = sourceFile.replace(options['url_prefix'], '')
    
    if(!fs.existsSync(sourceFile)){
        gmutil.error('\n*Error: \n*Inline File Not Exist: '+sourceFile+'\n')

        return match;
    }

    content = getFileContent(sourceFile);

    // add for gulpman store save
    store.save(sourceFile, _file.path)


    if('css' === type){
        if(!isMinifyCss)
            return joint('style', content);
        code = uglifycss.processString(content, options);
        code = joint('style', code);
    }
    else if('js' === type){

        if(!isMinifyJs)
            return joint('script', content);
        code = jsmin(content, options).code.replace(/\n*\t*/gi, '');
        code = joint('script', code);
    }

    return code;

};