I am trying to convert this http cache into a normal html page so I can see the content.
Here is the http cache I am trying to convert: http://mediapreset.com/http-cache.log
There is this site that can help with converting http cache page into a normal html page, but their service is not working:
http://www.sensefulsolutions.com/2012/01/viewing-chrome-cache-easy-way.html
They do however provide this function:
(function() {
var preTags = document.getElementsByTagName('pre');
var preWithHeaderInfo = preTags[0];
var preWithContent = preTags[2];
var lines = preWithContent.textContent.split('\n');
// get data about the formatting (changes between different versions of chrome)
var rgx = /^(0{8}:\s+)([0-9a-f]{2}\s+)[0-9a-f]{2}/m;
var match = rgx.exec(lines[0]);
var text = '';
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var firstIndex = match[1].length; // first index of the chars to match (e.g. where a '84' would start)
var indexJump = match[2].length; // how much space is between each set of numbers
var totalCharsPerLine = 16;
index = firstIndex;
for (var j = 0; j < totalCharsPerLine; j++) {
var hexValAsStr = line.substr(index, 2);
if (hexValAsStr == ' ') {
// no more chars
break;
}
var asciiVal = parseInt(hexValAsStr, 16);
text += String.fromCharCode(asciiVal);
index += indexJump;
}
}
var headerText = preWithHeaderInfo.textContent;
var elToInsertBefore = document.body.childNodes[0];
var insertedDiv = document.createElement("div");
document.body.insertBefore(insertedDiv, elToInsertBefore);
// find the filename
var nodes = [document.body];
var filepath = '';
while (true) {
var node = nodes.pop();
if (node.hasChildNodes()) {
var children = node.childNodes;
for (var i = children.length - 1; i >= 0; i--) {
nodes.push(children[i]);
}
}
if (node.nodeType === Node.TEXT_NODE && /\S/.test(node.nodeValue)) {
// 1st depth-first text node (with non-whitespace chars) found
filepath = node.nodeValue;
break;
}
}
outputResults(insertedDiv, convertToBase64(text), filepath, headerText);
insertedDiv.appendChild(document.createElement('hr'));
function outputResults(parentElement, fileContents, fileUrl, headerText) {
// last updated 1/27/12
var rgx = /.+\/([^\/]+)/;
var filename = rgx.exec(fileUrl)[1];
// get the content type
rgx = /content-type: (.+)/i;
var match = rgx.exec(headerText);
var contentTypeFound = match != null;
var contentType = "text/plain";
if (contentTypeFound) {
contentType = match[1];
}
var dataUri = "data:" + contentType + ";base64," + fileContents;
// check for gzipped file
var gZipRgx = /content-encoding: gzip/i;
if (gZipRgx.test(headerText)) {
filename += '.gz';
}
// check for image
var imageRgx = /image/i;
var isImage = imageRgx.test(contentType);
// create link
var aTag = document.createElement('a');
aTag.textContent = "Left-click to download the cached file";
aTag.setAttribute('href', dataUri);
aTag.setAttribute('download', filename);
parentElement.appendChild(aTag);
parentElement.appendChild(document.createElement('br'));
// create image
if (isImage) {
var imgTag = document.createElement('img');
imgTag.setAttribute("src", dataUri);
parentElement.appendChild(imgTag);
parentElement.appendChild(document.createElement('br'));
}
// create warning
if (!contentTypeFound) {
var pTag = document.createElement('p');
pTag.textContent = "WARNING: the type of file was not found in the headers... defaulting to text file.";
parentElement.appendChild(pTag);
}
}
function getBase64Char(base64Value) {
if (base64Value < 0) {
throw "Invalid number: " + base64Value;
} else if (base64Value <= 25) {
// A-Z
return String.fromCharCode(base64Value + "A".charCodeAt(0));
} else if (base64Value <= 51) {
// a-z
base64Value -= 26; // a
return String.fromCharCode(base64Value + "a".charCodeAt(0));
} else if (base64Value <= 61) {
// 0-9
base64Value -= 52; // 0
return String.fromCharCode(base64Value + "0".charCodeAt(0));
} else if (base64Value <= 62) {
return '+';
} else if (base64Value <= 63) {
return '/';
} else {
throw "Invalid number: " + base64Value;
}
}
function convertToBase64(input) {
// http://en.wikipedia.org/wiki/Base64#Example
var remainingBits;
var result = "";
var additionalCharsNeeded = 0;
var charIndex = -1;
var charAsciiValue;
var advanceToNextChar = function() {
charIndex++;
charAsciiValue = input.charCodeAt(charIndex);
return charIndex < input.length;
};
while (true) {
var base64Char;
// handle 1st char
if (!advanceToNextChar()) break;
base64Char = charAsciiValue >>> 2;
remainingBits = charAsciiValue & 3; // 0000 0011
result += getBase64Char(base64Char); // 1st char
additionalCharsNeeded = 3;
// handle 2nd char
if (!advanceToNextChar()) break;
base64Char = (remainingBits << 4) | (charAsciiValue >>> 4);
remainingBits = charAsciiValue & 15; // 0000 1111
result += getBase64Char(base64Char); // 2nd char
additionalCharsNeeded = 2;
// handle 3rd char
if (!advanceToNextChar()) break;
base64Char = (remainingBits << 2) | (charAsciiValue >>> 6);
result += getBase64Char(base64Char); // 3rd char
remainingBits = charAsciiValue & 63; // 0011 1111
result += getBase64Char(remainingBits); // 4th char
additionalCharsNeeded = 0;
}
// there may be an additional 2-3 chars that need to be added
if (additionalCharsNeeded == 2) {
remainingBits = remainingBits << 2; // 4 extra bits
result += getBase64Char(remainingBits) + "=";
} else if (additionalCharsNeeded == 3) {
remainingBits = remainingBits << 4; // 2 extra bits
result += getBase64Char(remainingBits) + "==";
} else if (additionalCharsNeeded != 0) {
throw "Unhandled number of additional chars needed: " + additionalCharsNeeded;
}
return result;
}
})()
How to use the function above to carry out the http cache conversion?
Here is the fiddle I'm working on: https://jsfiddle.net/emporio/9jdw8r68/2/
Here's a modified version that outputs ungzipped data to console:
(function convertCache() {
var preTags = document.querySelectorAll('script[type="http-cache"]');
var preWithHeaderInfo = preTags[0];
var preWithContent = preTags[1];
var lines = preWithContent.textContent.split('\n');
// get data about the formatting (changes between different versions of chrome)
var rgx = /^(0{8}:\s+)([0-9a-f]{2}\s+)[0-9a-f]{2}/m;
var match = rgx.exec(lines[0]);
var text = '';
var data = [];
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var firstIndex = match[1].length; // first index of the chars to match (e.g. where a '84' would start)
var indexJump = match[2].length; // how much space is between each set of numbers
var totalCharsPerLine = 16;
index = firstIndex;
for (var j = 0; j < totalCharsPerLine; j++) {
var hexValAsStr = line.substr(index, 2);
if (hexValAsStr == ' ') {
// no more chars
break;
}
var asciiVal = parseInt(hexValAsStr, 16);
data.push(asciiVal);
text += String.fromCharCode(asciiVal);
index += indexJump;
}
}
var headerText = preWithHeaderInfo.textContent;
var elToInsertBefore = document.body.childNodes[0];
var insertedDiv = document.createElement("div");
document.body.insertBefore(insertedDiv, elToInsertBefore);
// find the filename
var nodes = [document.body];
var filepath = '';
while (true) {
var node = nodes.pop();
if (node.hasChildNodes()) {
var children = node.childNodes;
for (var i = children.length - 1; i >= 0; i--) {
nodes.push(children[i]);
}
}
if (node.nodeType === Node.TEXT_NODE && /\S/.test(node.nodeValue)) {
// 1st depth-first text node (with non-whitespace chars) found
filepath = node.nodeValue;
break;
}
}
var gZipRgx = /content-encoding: gzip/i;
if (gZipRgx.test(headerText)) {
var binData = new Uint8Array(data);
var data = pako.ungzip(binData);
var strData = String.fromCharCode.apply(null, new Uint8Array(data));
console.log(strData);
}
outputResults(insertedDiv, convertToBase64(text), filepath, headerText);
insertedDiv.appendChild(document.createElement('hr'));
function outputResults(parentElement, fileContents, fileUrl, headerText) {
// last updated 1/27/12
var rgx = /.+\/([^\/]+)/;
var filename = rgx.exec(fileUrl)[1];
// get the content type
rgx = /content-type: (.+)/i;
var match = rgx.exec(headerText);
var contentTypeFound = match != null;
var contentType = "text/plain";
if (contentTypeFound) {
contentType = match[1];
}
var dataUri = "data:" + contentType + ";base64," + fileContents;
// check for gzipped file
var gZipRgx = /content-encoding: gzip/i;
if (gZipRgx.test(headerText)) {
filename += '.gz';
}
// check for image
var imageRgx = /image/i;
var isImage = imageRgx.test(contentType);
// create link
var aTag = document.createElement('a');
aTag.textContent = "Left-click to download the cached file";
aTag.setAttribute('href', dataUri);
aTag.setAttribute('download', filename);
parentElement.appendChild(aTag);
parentElement.appendChild(document.createElement('br'));
// create image
if (isImage) {
var imgTag = document.createElement('img');
imgTag.setAttribute("src", dataUri);
parentElement.appendChild(imgTag);
parentElement.appendChild(document.createElement('br'));
}
// create warning
if (!contentTypeFound) {
var pTag = document.createElement('p');
pTag.textContent = "WARNING: the type of file was not found in the headers... defaulting to text file.";
parentElement.appendChild(pTag);
}
}
function getBase64Char(base64Value) {
if (base64Value < 0) {
throw "Invalid number: " + base64Value;
} else if (base64Value <= 25) {
// A-Z
return String.fromCharCode(base64Value + "A".charCodeAt(0));
} else if (base64Value <= 51) {
// a-z
base64Value -= 26; // a
return String.fromCharCode(base64Value + "a".charCodeAt(0));
} else if (base64Value <= 61) {
// 0-9
base64Value -= 52; // 0
return String.fromCharCode(base64Value + "0".charCodeAt(0));
} else if (base64Value <= 62) {
return '+';
} else if (base64Value <= 63) {
return '/';
} else {
throw "Invalid number: " + base64Value;
}
}
function convertToBase64(input) {
// http://en.wikipedia.org/wiki/Base64#Example
var remainingBits;
var result = "";
var additionalCharsNeeded = 0;
var charIndex = -1;
var charAsciiValue;
var advanceToNextChar = function() {
charIndex++;
charAsciiValue = input.charCodeAt(charIndex);
return charIndex < input.length;
};
while (true) {
var base64Char;
// handle 1st char
if (!advanceToNextChar()) break;
base64Char = charAsciiValue >>> 2;
remainingBits = charAsciiValue & 3; // 0000 0011
result += getBase64Char(base64Char); // 1st char
additionalCharsNeeded = 3;
// handle 2nd char
if (!advanceToNextChar()) break;
base64Char = (remainingBits << 4) | (charAsciiValue >>> 4);
remainingBits = charAsciiValue & 15; // 0000 1111
result += getBase64Char(base64Char); // 2nd char
additionalCharsNeeded = 2;
// handle 3rd char
if (!advanceToNextChar()) break;
base64Char = (remainingBits << 2) | (charAsciiValue >>> 6);
result += getBase64Char(base64Char); // 3rd char
remainingBits = charAsciiValue & 63; // 0011 1111
result += getBase64Char(remainingBits); // 4th char
additionalCharsNeeded = 0;
}
// there may be an additional 2-3 chars that need to be added
if (additionalCharsNeeded == 2) {
remainingBits = remainingBits << 2; // 4 extra bits
result += getBase64Char(remainingBits) + "=";
} else if (additionalCharsNeeded == 3) {
remainingBits = remainingBits << 4; // 2 extra bits
result += getBase64Char(remainingBits) + "==";
} else if (additionalCharsNeeded != 0) {
throw "Unhandled number of additional chars needed: " + additionalCharsNeeded;
}
return result;
}
})()
https://jsfiddle.net/9jdw8r68/6/
Data from chrome://cache info has to be split into two separate script tags (each with type="http-cache" attribute). When you open cache of specific URL and check page source code, you will see three pre tags there.
copy content of first pre into first script type="http-cache" tag
ignore second pre tag
copy content of third pre into second script type="http-cache" tag
ignore the rest
Unfortunately it throws if data is too big. You would have to find different implementation of gzip or maybe put it into webworker to workaround that.
Related
Here is my code:
var ct = 0;
var sheet = SpreadsheetApp.getActiveSheet();
var cell = sheet.getCurrentCell();
var cellcol = cell.getColumn();
var cellrow = cell.getRow()
var notate = cell.getA1Notation();
var temp, letter = '';
var solved = new Array()
var pend = new Array()
var cellcol1 = cellcol + 1;
var p;
function copycell1() {
getFirstEmptyRowByColumnArray();
cell.copyTo(sheet.getRange(ct,cellcol,1,1))
cell.clearContent();
}
function getFirstEmptyRowByColumnArray() {
columnToLetter(cellcol)
var column = sheet.getRange(letter + ':' + letter);
var values = column.getValues();
while ( values[ct] && values[ct][0] !== "" ) {
ct++;
}
ct++
}
function getFirstEmptyRowByColumnArray2() {
columnToLetter(cellcol);
var cellrow = cell.getRow();
var column = sheet.getRange(letter + cellrow + ':' + letter);
var values = column.getValues();
while ( values[ct] && values[ct][0] !== "" ) {
ct++;
}
}
function columnToLetter(column)
{
while (column > 0)
{
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
}
function totalSolved() {
getFirstEmptyRowByColumnArray2()
var compacolumn = sheet.getRange(letter + cellrow + ':' + letter + (ct+cellrow));
var valuesSolved = compacolumn.getValues();
solved = valuesSolved
}
function totalPending() {
letter = '';
ct = 0;
cellcol = cellcol + 1;
getFirstEmptyRowByColumnArray2()
cellrow = cell.getRow();
var compacolumn = sheet.getRange(letter + cellrow + ':' + letter + (ct + cellrow));
var valuesPend = compacolumn.getValues();
pend = valuesPend
}
function compa() {
var i;
var o;
totalSolved();
totalPending();
for ( i = 0; i < pend.length; i++ ) {
for (o = 0; o < solved.length; o++) {
if (pend[i].toString() == solved[o].toString()) {
sheet.getRange(i+cellrow,cellcol1).clearContent();
}
else {
}
}
}
clearemp();
clearemp();
clearemp();
}
function clearemp() {
lastRowForColumn(cellcol1)
for (var i = 0; i < p; i++){
if((sheet.getRange(letter+(cellrow+i)).getValue()) == "")
{
Logger.log(sheet.getRange(letter+(cellrow+i)).getA1Notation());
sheet.getRange(letter+(cellrow+i)).deleteCells(SpreadsheetApp.Dimension.ROWS);
}
}
}
function lastRowForColumn(column){
var numRows = sheet.getLastRow();
Logger.log("numRows is " + numRows)
var data = sheet.getRange(1, column, numRows).getValues();
Logger.log("data is " + data)
Logger.log("data.length is " + data.length)
for(p = data.length - 1 ; p >= 0 ; p--){
if (data[p][0] != null && data[p][0] != ""){
Logger.log ("p is " + p)
return p + 1;
}
}
}
function test() {
Logger.log("cellcol is " + cellcol1)
lastRowForColumn(cellcol1)
Logger.log("p is " + p)
}
The function I'm talking about is compa().
The specific function that deletes the cells is clearemp(). But whenever I do it it is still not complete and I am at a loss on what to do
CONTEXT: I am working on comparing two lists and then removing the equal cells on the 2nd column and then shifting the cells up.
function delcels(col=1) {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet1');
const rg=sh.getRange(1,col,sh.getLastRow());
const c1=rg.getValues().filter((e)=>!(e===""));//thanks to iansedano
rg.clearContent();
sh.getRange(1,col,c1.length,1).setValues(c1);
}
A possible solution
There are a few approaches, but here is one, that is essentially the same as Cooper's, except that it doesn't clear values that are 0. Only if the cell is empty, i.e. "" will it clear the cell.
/**
* Clears empty cells in column
*
* #param columnToClear - the column that should be cleared, defaults to 1
* #param sheetName - the name of the sheet, defaults to "Sheet1"
*/
function clearBlanks(columnToClear = 1, sheetName = "Sheet1") {
const file = SpreadsheetApp.getActive();
const sheet = file.getSheetByName(sheetName);
const range = sheet.getRange(1, columnToClear, sheet.getLastRow(), 1);
const output = range.getValues().filter(e => !(e[0] === ""));
range.clearContent();
const outputRange = sheet.getRange(1, columnToClear, output.length, 1)
outputRange.setValues(output)
}
This gets the whole range into memory as a 2D array.
Uses filter to take out any values that are strictly equal === to and empty string. So it will not clear 0 values.
Clears the whole column, and pastes in the filtered array.
Filter
This is called on an array
array.filter(function)
You need to pass in a function that will return either a True or False value. The filter will go through each element and if it gets False then it will remove that element. In the example above, its passed in as an arrow function. When its an arrow function, if its on one line, you don't need to include the return statement.
There are a few useful functions that are like this. For example, forEach and map that can be very useful for the types of operation you are doing.
Reference
filter
I've created a script to create a new array called spots, here is the script:
main();
function main() {
var doc = app.activeDocument;
var selectedSwatches = doc.swatches.getSelected();
var pageNumber = 1;
var count = 0;
if (selectedSwatches.length > 0) {
var text = 'var spots = new Array(\n';
for (var i = 0; i < selectedSwatches.length; i++) {
var swatch = selectedSwatches[i]
var color = swatch.color;
// Spot
if (color.typename == "SpotColor") {
count++;
text += '"' + color.spot.name + '", ' + "\n";
color = color.spot.color;
if (count % 10 == 0)
pageNumber++;
}
}
var textend = ');';
var textArray = text + textend;
alert(textArray);
} else {
alert("No Swatches Selected.");
}
}
This script alerts the following:
var spots = new Array(
"Yellow 012 C",
"Bright Red C",
);
How do I now alert the contents of that array i.e. Yellow 012 C, Bright Red C
I have tried using:
alert(spots);
But I get the error undefined maybe because the array is created on the fly and its not placed in the script?
UPDATE:
As per the comments, I have edited the script adding:
var spots = [];
spots.push(color.spot)
alert(spots);
I now get the following error: undefined is not an object
Here's the full script
main();
function main() {
var doc = app.activeDocument;
var selectedSwatches = doc.swatches.getSelected();
var pageNumber = 1;
var count = 0;
if (selectedSwatches.length > 0) {
var text = 'var spots = new Array(\n';
for (var i = 0; i < selectedSwatches.length; i++) {
var swatch = selectedSwatches[i]
var color = swatch.color;
// Spot
if (color.typename == "SpotColor") {
count++;
text += '"' + color.spot.name + '", ' + "\n";
color = color.spot.color;
if (count % 10 == 0)
pageNumber++;
}
}
var textend = ');';
var textArray = text + textend;
var spots = [];
spots.push(color.spot)
alert(spots);
} else {
alert("No Swatches Selected.");
}
}
Try
function main() {
//var doc = app.activeDocument;
var selectedSwatches
= [{"color":{"spot":{"color":"#ff0000","name":"red"},"typename":"SpotColor"}}
,{"color":{"spot":{"color":"#000000","name":"black"},"typename":"SpotColor"}}];
// = doc.swatches.getSelected();
var pageNumber = 1;
var count = 0;
var spots = [];
if (selectedSwatches.length > 0) {
for (var i = 0; i < selectedSwatches.length; i++) {
var swatch = selectedSwatches[i]
var color = swatch.color;
// Spot
if (color.typename == "SpotColor") {
count++;
spots.push(color.spot.name);
color = color.spot.color;
if (count % 10 == 0)
pageNumber++;
}
}
alert(spots.toString());
} else {
alert("No Swatches Selected.");
}
}
<button onclick="main()">Main</>
I've been working on a Math Parser project. I'm almost finished but I encountered a problem that I couldn't find the reason for it.
I've got 3 javascript files:
main.js
var button1 = document.getElementById("button");
var text1 = document.getElementById("text");
var output = document.getElementById("result");
button1.addEventListener("click", function(){
var textInput = text1.value;
var cleared = new clearingUnwantedCharacters(textInput);
var marked = new subgroupMarking(cleared.output);
var prioritizedList = new subgroupPrioritization(marked.parenGroups);
for(var i = 0; i <= 360; i++){
var splittedPieces = new splittingOperators(prioritizedList.prioritizedGroups);
var calculatedPieces = new calculatePieces(splittedPieces.seperatedPieces, i, true);
console.log(calculatedPieces.result);
}
});
objects.js
function clearingUnwantedCharacters(inputText){
this.output = inputText;
this.output = this.output.replace(/\s+/g, '');
this.output = this.output.toLowerCase();
}
function subgroupMarking(inputText){
this.parenGroups = [inputText];
this.locLeftParen = markChar(this.parenGroups[0], "(");
this.locRigthParen = markChar(this.parenGroups[0], ")");
for(var i = this.locLeftParen.length-1; i >= 0; i--){
var leftParen = this.locLeftParen[i];
var rightParen = this.locRigthParen.find(function(res){return res > leftParen});
this.parenGroups[i+1] = this.parenGroups[0].substring(leftParen+1, rightParen);
this.parenGroups[0] = changeAt(this.parenGroups[0], leftParen, rightParen+1, "{_"+(i+1)+"}");
this.locLeftParen = markChar(this.parenGroups[0], "(");
this.locRigthParen = markChar(this.parenGroups[0], ")");
}
}
function subgroupPrioritization(subgroupList){
var withParenGroup = [];
var withoutParenGroup = [];
for(var i = 0; i < subgroupList.length; i++){
var content = subgroupList[i].toString();
var hasParenGroup = content.search(/{_\d+}/g);
if(hasParenGroup == -1){
withoutParenGroup.push(content);
}else{
withParenGroup.push(content);
}
}
this.prioritizedGroups = withParenGroup.concat(withoutParenGroup);
}
function splittingOperators(prioritizedGroupList){
this.seperatedPieces = [];
for(var i = prioritizedGroupList.length-1; i >= 0; i--){
var pieces = prioritizedGroupList[i].split(/(\+|\*|\/|\^|\b(?=-)|(?<=})(?=-))/g);
for(var k = 0; k < pieces.length; k++){
if(pieces[k] == ""){
pieces[k] = "+";
}
}
this.seperatedPieces.unshift(pieces);
}
}
function calculatePieces(pieceList, x, degreeOption){
this.result = pieceList;
for(var i = this.result.length-1; i >= 0; i--){ // ["34", "+", "2{_2}"]
for(var k = 0; k < this.result[i].length; k++){ // 34, +, 2{_2}
var specialFlag = false;
var totalMultiplication = (countChar(this.result[i][k], "-")%2 == 0) ? 1 : -1;
var has = {
x : this.result[i][k].includes("x"),
subgroup : (this.result[i][k].search(/{_\d+}/g) != -1),
logarithm : this.result[i][k].includes("log"),
trigonometry : (this.result[i][k].includes("sin") || this.result[i][k].includes("cos") || this.result[i][k].includes("tan") || this.result[i][k].includes("cot"))
};
if(has.trigonometry){
specialFlag = true;
var trigSubgroupIndexes = [];
var trigTypes = [];
var trigsMultiplied = 1;
this.result[i][k] = this.result[i][k].replace(/(?:arc)?(sin|cos|tan|cot){_(\d+)}/g, function(match, type, index){
trigSubgroupIndexes.push(parseInt(index));
if(match.includes("arc")){
trigTypes.push([true, type]);
}else{
trigTypes.push([false, type]);
}
return " ";
});
for(var l = 0; l < trigTypes.length; l++){
var inverseness = trigTypes[l][0];
var type = trigTypes[l][1];
var parameter = (degreeOption) ? convertToRadian(parseFloat(this.result[trigSubgroupIndexes[l]])) : parseFloat(this.result[trigSubgroupIndexes[l]]);
var result;
if(inverseness){
switch(type){
case "sin":
result = Math.asin(parameter);
break;case "cos":
result = Math.acos(parameter);
break;case "tan":
result = Math.atan(parameter);
break;case "cot":
result = 1 / Math.atan(parameter);
break;
}
}else{
switch(type){
case "sin":
result = Math.sin(parameter);
break;case "cos":
result = Math.cos(parameter);
break;case "tan":
result = Math.tan(parameter);
break;case "cot":
result = 1 / Math.tan(parameter);
break;
}
}
trigsMultiplied *= result;
}
totalMultiplication *= trigsMultiplied;
}
if(has.logarithm){
specialFlag = true;
var logSubgroupIndexes = [];
var logsMultiplied = 1;
this.result[i][k] = this.result[i][k].replace(/log{_(\d+)}{_(\d+)}/g, function(match, firstIndex, secondIndex){
logSubgroupIndexes.push([parseInt(firstIndex), parseInt(secondIndex)]);
return " ";
});
for(var l = 0; l < logSubgroupIndexes.length; l++){
var base = this.result[logSubgroupIndexes[l][0]];
var power = this.result[logSubgroupIndexes[l][1]];
logsMultiplied *= (Math.log(power) / Math.log(base));
}
totalMultiplication *= logsMultiplied;
}
if(has.subgroup){
specialFlag = true;
var subgroupIndexes = [];
var groupsMultiplied = 1;
this.result[i][k] = this.result[i][k].replace(/{_(\d+)}/g, function(match, index){
subgroupIndexes.push(parseInt(index));
return " ";
});
for(var l = 0; l < subgroupIndexes.length; l++){
groupsMultiplied *= this.result[subgroupIndexes[l]];
}
totalMultiplication *= groupsMultiplied;
}
if(has.x){
specialFlag = true;
var powerX = countChar(this.result[i][k], "x");
this.result[i][k] = this.result[i][k].replace("x", " ");
totalMultiplication *= Math.pow(x, powerX);
}
if(specialFlag == true){
var factors = this.result[i][k].match(/\d+/g);
if(factors !== null){
for(var l = 0; l < factors.length; l++){
totalMultiplication *= parseFloat(factors[l]);
}
}
if(!isFinite(totalMultiplication) || checkNum(this.result[i][k]) || this.result[i][k].includes("(") || this.result[i][k].includes(")")){
this.result[i][k] = NaN;
}else{
this.result[i][k] = totalMultiplication;
}
}
}
var operators = ["^","*","/","+","-"];
for(var k = 0; k < operators.length; k++){
var search = this.result[i].indexOf(operators[k]);
while(search != -1){
switch(operators[k]){
case "+":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) + checkParse(this.result[i][search+1]));
break;case "-":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) - checkParse(this.result[i][search+1]));
break;case "*":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) * checkParse(this.result[i][search+1]));
break;case "/":
this.result[i].splice(search-1, 3, checkParse(this.result[i][search-1]) / checkParse(this.result[i][search+1]));
break;case "^":
this.result[i].splice(search-1, 3, Math.pow(checkParse(this.result[i][search-1]) , checkParse(this.result[i][search+1])));
break;
}
if(this.result[i].indexOf(operators[k], search) == -1){
break;
}else{
search = this.result[i].indexOf(operators[k], search);
}
}
}
}
if(isNaN(this.result[0][0])){
this.result = "An error has occured, please make sure the parameters are correct.";
}else{
this.result = this.result[0][0];
}
}
functions.js
function countChar(str, character){
return str.toString().split(character).length-1;
}
function markChar(str, character){
var charCount = str.split(character).length;
var result = [];
for(var i = 0; i < charCount - 1; i++){
if(result.length == 0){
result.push(str.indexOf(character));
}else{
result.push(str.indexOf(character, result[i-1] + 1));
}
}
return result;
}
function changeAt(str, startingIndex, endingIndex, replacement){ // Returns the given string with the part between startingIndex and endingIndex replaced with replacement.
return str.substring(0, startingIndex) + replacement + str.substring(endingIndex, str.length);
}
function checkParse(str){
if(/[a-z]/.test(str) || countChar(str, ".") > 1){
return NaN;
}else{
return parseFloat(str);
}
}
function checkNum(str){
return (/[a-z]/.test(str) || countChar(str, ".") > 1);
}
function convertToRadian(degrees) {
return degrees * Math.PI / 180;
}
It works as intended when done like above. It puts values to x according to the range specified in the for loop in main.js and console.logs the results. But I don't want to create splittingOperators object everytime I recalculate with another x value. It's unnecessary since the actual formula stays the same.
var button1 = document.getElementById("button");
var text1 = document.getElementById("text");
var output = document.getElementById("result");
button1.addEventListener("click", function(){
var textInput = text1.value;
var cleared = new clearingUnwantedCharacters(textInput);
var marked = new subgroupMarking(cleared.output);
var prioritizedList = new subgroupPrioritization(marked.parenGroups);
var splittedPieces = new splittingOperators(prioritizedList.prioritizedGroups);
for(var i = 0; i <= 360; i++){
var calculatedPieces = new calculatePieces(splittedPieces.seperatedPieces, i, true);
console.log(calculatedPieces.result);
}
});
When I put the object creation outside of the for loop, it calculates and logs the first x value, but it gives
Uncaught TypeError: this.result[i][k].includes is not a function
as error after that. I suspect it's because it changes splittedPieces.seperatedPieces when it shouldn't. I couldn't find any reason for it to do that or maybe I am missing something.
I am trying to desteghide an image to reveal the secret message.
I have got it working, but only by browsing the image which contains the message.
If you take a look at the screenshot:
To make this work I need to save the image (the arsenal badge). Then use the browse to upload the image again to make this work. I want to skip the browse stage and make automatically by grabbing the image straight from the div.
Any ideas?
here is my code (its quite messy sorry)
window.onload = function() {
// add action to the file input
var input = document.getElementById('file');
input.addEventListener('change', importImage);
};
var maxMessageSize = 1000;
$("#desteg").click(function()
{
decode();
});
var importImage = function(e) {
var reader = new FileReader();
reader.onload = function(event) {
// set the preview
document.getElementById('preview').style.display = 'block';
document.getElementById('preview').src = event.target.result;
// wipe all the fields clean
document.getElementById('pass').value = '';
document.getElementById('ContentArea').innerHTML = '';
// read the data into the canvas element
var img = new Image();
img.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
ctx.canvas.width = img.width;
ctx.canvas.height = img.height;
ctx.drawImage(img, 0, 0);
decode();
};
img.src = event.target.result;
};
reader.readAsDataURL(e.target.files[0]);
};
// encode the image and save it
// decode the image and display the contents if there is anything
var decode = function() {
var password = document.getElementById('pass').value;
var passwordFail = 'Password is incorrect or there is nothing here.';
// decode the message with the supplied password
var ctx = document.getElementById('canvas').getContext('2d');
var imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
var message = decodeMessage(imgData.data, sjcl.hash.sha256.hash(password));
// try to parse the JSON
var obj = null;
try {
obj = JSON.parse(message);
} catch (e) {
// display the "choose" view
if (password.length > 0) {
alert(passwordFail);
}
}
// display the "reveal" view
if (obj) {
// decrypt if necessary
if (obj.ct) {
try {
obj.text = sjcl.decrypt(password, message);
} catch (e) {
alert(passwordFail);
}
}
// escape special characters
var escChars = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
'\'': ''',
'/': '/',
'\n': '<br/>'
};
var escHtml = function(string) {
return String(string).replace(/[&<>"'\/\n]/g, function (c) {
return escChars[c];
});
};
document.getElementById('ContentArea').innerHTML = escHtml(obj.text);
}
};
// returns a 1 or 0 for the bit in 'location'
var getBit = function(number, location) {
return ((number >> location) & 1);
};
// sets the bit in 'location' to 'bit' (either a 1 or 0)
var setBit = function(number, location, bit) {
return (number & ~(1 << location)) | (bit << location);
};
// returns an array of 1s and 0s for a 2-byte number
var getBitsFromNumber = function(number) {
var bits = [];
for (var i = 0; i < 16; i++) {
bits.push(getBit(number, i));
}
return bits;
};
// returns the next 2-byte number
var getNumberFromBits = function(bytes, history, hash) {
var number = 0, pos = 0;
while (pos < 16) {
var loc = getNextLocation(history, hash, bytes.length);
var bit = getBit(bytes[loc], 0);
number = setBit(number, pos, bit);
pos++;
}
return number;
};
// returns an array of 1s and 0s for the string 'message'
var getMessageBits = function(message) {
var messageBits = [];
for (var i = 0; i < message.length; i++) {
var code = message.charCodeAt(i);
messageBits = messageBits.concat(getBitsFromNumber(code));
}
return messageBits;
};
// gets the next location to store a bit
var getNextLocation = function(history, hash, total) {
var pos = history.length;
var loc = Math.abs(hash[pos % hash.length] * (pos + 1)) % total;
while (true) {
if (loc >= total) {
loc = 0;
} else if (history.indexOf(loc) >= 0) {
loc++;
} else if ((loc + 1) % 4 === 0) {
loc++;
} else {
history.push(loc);
return loc;
}
}
};
// encodes the supplied 'message' into the CanvasPixelArray 'colors'
// returns the message encoded in the CanvasPixelArray 'colors'
var decodeMessage = function(colors, hash) {
// this will store the color values we've already read from
var history = [];
// get the message size
var messageSize = getNumberFromBits(colors, history, hash);
// exit early if the message is too big for the image
if ((messageSize + 1) * 16 > colors.length * 0.75) {
return '';
}
// exit early if the message is above an artificial limit
if (messageSize === 0 || messageSize > maxMessageSize) {
return '';
}
// put each character into an array
var message = [];
for (var i = 0; i < messageSize; i++) {
var code = getNumberFromBits(colors, history, hash);
message.push(String.fromCharCode(code));
}
// the characters should parse into valid JSON
return message.join('');
};
I posted a similar question at the Drupal Forum, but I haven't had much luck.
I'm upgrading a site from D6 to D7. So far it's gone well, but I'm getting a Javascript error that I just can't pin down a solution for.
This is a cut down version of the whole script:
(function($) {
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
Date.prototype.toISODate =
new Function("with (this)\nreturn " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
The part that keeps throwing an error I'm seeing in Firebug is at:
Date.prototype.toISODate =
new Function("with (this)\n return " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
Firebug keeps stopping at "addZero is not defined". JS has never been my strong point, and I know some changes have been made in D7. I've already wrapped the entire script in "(function($) { }(jQuery));", but I must be missing something else. The same script works perfectly on the D6 site.
Here is the "fixed" version of the whole code with #Pointy suggestion added. All I left out is the part of the script for making the hash that goes to Amazon, and some of my declared variables.
(function($) {
var typedText;
var strSearch = /asin:/;
var srchASIN;
$(document).ready(function() {
$("#edit-field-game-title-und-0-asin").change(function() {
typedText = $("#edit-field-game-title-und-0-asin").val();
$.ajax({
type: 'POST',
data: {typedText: typedText},
dataType: 'text',
url: '/asin/autocomplete/',
success:function(){
document.getElementById('asin-lookup').style.display='none';
x = typedText.search(strSearch);
y = (x+5);
srchASIN = typedText.substr(y,10)
amazonSearch();
}
});
});
$("#search_asin").click(function() {
$("#edit-field-game-title-und-0-asin").val('');
document.getElementById('name-lookup').style.display='none';
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#edit-body").val('');
srchASIN = $("#field-asin-enter").val();
amazonSearch();
});
$("#clear_search").click(function() {
$("#field-asin-enter").val('');
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-release-dt2-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#field-amazon-platform").val('');
$("#field-amazon-esrb").val('');
$("#edit-body-und-0-value").val('');
document.getElementById('asin-lookup').style.display='';
document.getElementById('name-lookup').style.display='';
});
function amazonSearch(){
var ASIN = srchASIN;
var azScr = cel("script");
azScr.setAttribute("type", "text/javascript");
var requestUrl = invokeRequest(ASIN);
azScr.setAttribute("src", requestUrl);
document.getElementsByTagName("head").item(0).appendChild(azScr);
}
});
var amzJSONCallback = function(tmpData){
if(tmpData.Item){
var tmpItem = tmpData.Item;
}
$("#edit-title").val(tmpItem.title);
$("#edit-field-game-edition-und-0-value").val(tmpItem.edition);
$("#edit-field-release-date-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-release-dt2-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-asin-und-0-asin").val(tmpItem.asin);
$("#edit-field-ean-und-0-value").val(tmpItem.ean);
$("#field-amazon-platform").val(tmpItem.platform);
$("#field-amazon-publisher").val(tmpItem.publisher);
$("#field-amazon-esrb").val(tmpItem.esrb);
};
function ctn(x){ return document.createTextNode(x); }
function cel(x){ return document.createElement(x); }
function addEvent(obj,type,fn){
if (obj.addEventListener){obj.addEventListener(type,fn,false);}
else if (obj.attachEvent){obj["e"+type+fn]=fn; obj.attachEvent("on"+type,function(){obj["e"+type+fn]();});}
}
var styleXSL = "http://www.tlthost.net/sites/vglAmazonAsin.xsl";
function invokeRequest(ASIN) {
cleanASIN = ASIN.replace(/[-' ']/g,'');
var unsignedUrl = "http://xml-us.amznxslt.com/onca/xml?Service=AWSECommerceService&AssociateTag=theliterarytimes&IdType=ASIN&ItemId="+cleanASIN+"&Operation=ItemLookup&ResponseGroup=Medium,ItemAttributes,OfferFull&Style="+styleXSL+"&ContentType=text/javascript&CallBack=amzJSONCallback";
var lines = unsignedUrl.split("\n");
unsignedUrl = "";
for (var i in lines) { unsignedUrl += lines[i]; }
// find host and query portions
var urlregex = new RegExp("^http:\\/\\/(.*)\\/onca\\/xml\\?(.*)$");
var matches = urlregex.exec(unsignedUrl);
var host = matches[1].toLowerCase();
var query = matches[2];
// split the query into its constituent parts
var pairs = query.split("&");
// remove signature if already there
// remove access key id if already present
// and replace with the one user provided above
// add timestamp if not already present
pairs = cleanupRequest(pairs);
// encode the name and value in each pair
pairs = encodeNameValuePairs(pairs);
// sort them and put them back together to get the canonical query string
pairs.sort();
var canonicalQuery = pairs.join("&");
var stringToSign = "GET\n" + host + "\n/onca/xml\n" + canonicalQuery;
// calculate the signature
//var secret = getSecretAccessKey();
var signature = sign(secret, stringToSign);
// assemble the signed url
var signedUrl = "http://" + host + "/onca/xml?" + canonicalQuery + "&Signature=" + signature;
//document.write ("<html><body><pre>REQUEST: "+signedUrl+"</pre></body></html>");
return signedUrl;
}
function encodeNameValuePairs(pairs) {
for (var i = 0; i < pairs.length; i++) {
var name = "";
var value = "";
var pair = pairs[i];
var index = pair.indexOf("=");
// take care of special cases like "&foo&", "&foo=&" and "&=foo&"
if (index == -1) {
name = pair;
} else if (index == 0) {
value = pair;
} else {
name = pair.substring(0, index);
if (index < pair.length - 1) {
value = pair.substring(index + 1);
}
}
// decode and encode to make sure we undo any incorrect encoding
name = encodeURIComponent(decodeURIComponent(name));
value = value.replace(/\+/g, "%20");
value = encodeURIComponent(decodeURIComponent(value));
pairs[i] = name + "=" + value;
}
return pairs;
}
function cleanupRequest(pairs) {
var haveTimestamp = false;
var haveAwsId = false;
var nPairs = pairs.length;
var i = 0;
while (i < nPairs) {
var p = pairs[i];
if (p.search(/^Timestamp=/) != -1) {
haveTimestamp = true;
} else if (p.search(/^(AWSAccessKeyId|SubscriptionId)=/) != -1) {
pairs.splice(i, 1, "AWSAccessKeyId=" + accessKeyId);
haveAwsId = true;
} else if (p.search(/^Signature=/) != -1) {
pairs.splice(i, 1);
i--;
nPairs--;
}
i++;
}
if (!haveTimestamp) {
pairs.push("Timestamp=" + getNowTimeStamp());
}
if (!haveAwsId) {
pairs.push("AWSAccessKeyId=" + accessKeyId);
}
return pairs;
}
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
Here's a better version of your code:
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
That moves "addDate" inside the extension function, and it avoids the horrid with statement.