Filling a buffer with emptiness - node.js

How can I fill a buffer with emptiness?
This was working on v0.10.*:
var b = new Buffer(8192);
b.fill("");
But it just crashes without any error on v0.11.11.
I have this code:
var b = new Buffer(8192);
b.fill("");
console.log(1);
When I run it, 1 doesn't appear in output. What alternatives are to fill a buffer with emptiness?

Originally I suggested new Buffer(Array(32)), but we determined b.fill(0) was a workable solution.

Related

Error with functioning Script - "Document <Doc ID. is missing (perhaps it was deleted, or maybe you don't have read access?) "

I am running a script to pull a weekly schedule excel file attached to an email and posting it to a google sheet. Currently I'm triggering it manually. The code appears to be working correctly and goes to completion based on logger statements but it gives this error code each time.
Document <Sheet ID> is missing (perhaps it was deleted, or maybe you don't have read access?)
The referenced sheet ID is not the sheet i'm working on so i presume it's the temporary document that's been created and deleted. I'm not sure how to get rid of this error. Again, the code appears to be working as intended despite the error.
function getExcelFile()
{
var thread = GmailApp.getUserLabelByName("Guelph/Weekly Schedules").getThreads(0,1);
//var thread = GmailApp.getUserLabelByName(‘Reconciliation’).getThreads(0,1);
var messages = thread[0].getMessages();
var len = messages.length;
var message = messages[len-1] //get last message
var attachments = message.getAttachments(); // Get attachment of first message
var xlsxBlob = attachments[0]; // Is supposes that attachments[0] is the blob of xlsx file.
var convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, xlsxBlob).id;
var sheet = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[0]; // There is the data in 1st tab.
var data = sheet.getDataRange().getValues();
var sheet = SpreadsheetApp.openById("1e_pepsold-SHbnDXcQ0pvdN9AGiZ31O5XcLFU8YfcwE").getSheetByName("Current");
//var sheet = SpreadsheetApp.openById("some id").getSheetByName(‘Data’);
sheet.clearContents();
var range = sheet.getRange(1, 1, data.length, data[0].length);
range.setValues(data);
Drive.Files.remove(convertedSpreadsheetId); // Remove the converted file.
Logger.log(new Date().getTime() - start); // Outputs time taken to run function
}
This looks like a recurring problem; there is already a thread here: Drive.Files.remove(fileId) remove the item but return an error message
My best guess is when the script removes the file, it still uses that same file, so the script returns an error message that the recently removed file is missing.
I know this may not be the best workaround, but you can move the file to Trash instead of deleting immediately:
Drive.Files.trash(convertedSpreadsheetId);
Then you can empty the Trash manually or do it in GAS using:
Drive.Files.emptyTrash();
References:
Trash
Empty Trash

Can't set the value of textItem.contents

I am trying to write a script that will update the value of a text layer in Photoshop.
I have a layer stored in a variable myLayer which I log out so I know it is an ArtLayer with a type of LayerKind.TEXT and has a textItem object associated that has a string value in place. All as I would expect.
The documentation says that textItem.contents is read-write so I thought myLayer.textItem.contents = "Hello World" should update the value but when I try this I get General Photoshop Error occurred. This functionality might not be available in this version of Photoshop.
Can anyone advise on what I'm missing?
I am using Photoshop CC 2014 and the CC 2014 Javascript Reference
Thankyou in advance for you help :)
Its hard to see whats going wrong when there is no code example. This works for me.
Tested in PS CC 2014 Mac OSX
// needs a Photoshop document with only one textlayer
var d = app.activeDocument;
var l = d.artLayers[0];
if(l.hasOwnProperty ("textItem")){
$.writeln("yes");
l.textItem.contents = "Hello World";
}
This works in CS2: (Assuming the active layer (mylayer) is a text layer)
var srcDoc = app.activeDocument;
var myLayer= srcDoc.activeLayer;
var text = myLayer.textItem.contents;
myLayer.textItem.contents = "Hello World";

Ignoring formatting while importing to xls using CasperJS

I have a script in casperJS that scrapes data from a webpage, then puts that information into a variable
var lbdes = casper.fetchText(x('//*[#id="product_overview"]'));
and I call that variable using FS to create an excel doc.
casper.then(function() {
var f = fs.open('scrapetest.xls', 'w');
f.write(lbdes);
f.close();
});
Problem is, when that variable imports into excel it looks like the image below -- Ideally I would love to keep that formatting but somehow force that string to stay in 1 cell rather than spanning across 3+ rows and 3+ columns.

Excel process stays alive even after calling Quit

I am creating Excel Sheet using Devexpress Exporter and then saving the file at a particular location.
After the creation of file, I have to open it, to add dropdownlist of items and then save it again in same location.
After all the operations, the file has to be emailed automatically to the email address from database.
Now if I have 1000 email addresses, and to automate this process, it is creating more than 10 instances of Excel.
How can I stop creation of those instance and how can I use excel operations without using more memory.
Code is as below:
protected string CreateExcelFile(string FilterName)
{
Random ranNumber = new Random();
int number = ranNumber.Next(0, 10000000);
string FileName = "TestDoc"+DateTime.Now.Year.ToString()+number.ToString()+DateTime.Now.Second.ToString()+".xls";
string path = #"c:\TestDocuments\"+FileName;
Directory.CreateDirectory(Path.GetDirectoryName(path));
FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
XlsExportOptions options = new XlsExportOptions();
options.ExportHyperlinks = false;
ASPxExporter.WriteXls(fs, options);
fs.Close();
AddDropDownToExcel(path);
return path;
}
//Adding The Dropdownlist Of Items TO Generated Excel Sheet
protected void AddDropDownToExcel(string path)
{
Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
string fileName = path.Replace("\\", "\\\\");
string RowCount = "F" + (testgrid.VisibleRowCount + 1).ToString();
// Open Excel and get first worksheet.
var workbook = application.Workbooks.Open(fileName);
var worksheet = workbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
// Set range for dropdownlist
var rangeNewStatus = worksheet.get_Range("F2", RowCount);
rangeNewStatus.ColumnWidth = 20;
rangeNewStatus.Validation.Add(Microsoft.Office.Interop.Excel.XlDVType.xlValidateList, Microsoft.Office.Interop.Excel.XlDVAlertStyle.xlValidAlertStop,
Microsoft.Office.Interop.Excel.XlFormatConditionOperator.xlBetween, "Item1,Item2,Item3,Item4");
// Save.
workbook.Save();
workbook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, Type.Missing, Type.Missing);
application.Quit();
}
First, I sincerely hope this isn't running on a server.
Then, if your problem is that too many instances of Excel are created, a thought is "don't create an instance every single time". Instead of starting Excel every time AddDropDownToExcel is called, can you reuse the same instance?
The problem you are having shows up regularly in Excel interop scenario; even though you are done and tell Excel to close, it "stays alive". It's usually caused by your app still holding a reference to a COM object that hasn't been disposed, preventing Excel from closing. This StackOverflow answer provides some pointers: https://stackoverflow.com/a/158752/114519
In general, to avoid that problem, you want to follow the "one-dot" rule. For instance, in your code:
var workbook = application.Workbooks.Open(fileName);
will be a problem, because an "anonymous" wrapper for Workbooks is created, and will likely not be disposed properly. The "one-dot" rule would say "don't use more than one dot when working with Excel interop", in this case:
var workbooks = application.Workbooks;
var workbook = workbooks.Open(fileName);
A totally different thought - instead of using Interop, can't you use OpenXML to generate your Excel file? I have never tried it to create drop downs, but if it supports it, it will be massively faster than Interop, and the type of problems you have won't happen.
Hope this helps.
As I know the grow of number of runnig excel.exe processes is 'normal' situation to excel :)
The dumbest advice is just kill sometimes it's processes. BUT, this way will be absolutely unhelpful if you use excel during your app is working because of you rather don't get which one excel.exe is yours.

Insert image into a specified location

I have a Google Apps script which replaces placeholders in a copy of a template document with some text by calling body.replaceText('TextA', 'TextB');.
Now I want to extend it to contain images. Does anybody have idea how to do this?
Thank you,
Andrey
EDIT: Just to make it clear what my script does. I have a Google form created in a spreadsheet. I've created a script which runs upon form submission, traverses a sheet corresponding to the form, find unprocessed rows, takes values from corresponding cells and put them into a copy of a Google document.
Some fields in the Google form are multi-line text fields, that's where '\r\r' comes from.
Here's a workaround I've come up with by now, not elegant, but it works so far:
// replace <IMG src="URL"> with the image fetched from URL
function processIMG_(Doc) {
var totalElements = Doc.getNumChildren();
for( var j = 0; j < totalElements; ++j ) {
var element = Doc.getChild(j);
var type = element.getType();
if (type =='PARAGRAPH'){
var par_text = element.getText();
var start = par_text.search(new RegExp('<IMG'));
var end = par_text.search(new RegExp('>'));
if (start==-1)
continue;
// Retrieve an image from the web.
var url = getURL_(par_text.substring(start,end));
if(url==null)
continue;
// Before image
var substr = par_text.substring(0,start);
var new_par = Doc.insertParagraph(++j, substr);
// Insert image
var resp = UrlFetchApp.fetch(url);
new_par.appendInlineImage(resp.getBlob());
// After image
var substr = par_text.substring(end+1);
Doc.insertParagraph(++j, substr);
element.removeFromParent();
j -= 2; // one - for latter increment; another one - for increment in for-loop
totalElements = Doc.getNumChildren();
}
}
}
Here is a piece of code that does (roughly) what you want.
(there are probably other ways to do that and it surely needs some enhancements but the general idea is there)
I have chosen to use '###" in the doc to mark the place where the image will be inserted, the image must be in your google drive (or more accurately in 'some' google drive ).
The code below uses a document I shared and an image I shared too so you can try it.
here is the link to the doc, don't forget to remove the image and to put a ### somewhere before testing (if ever someone has run the code before you ;-)
function analyze() { // just a name, I used it to analyse docs
var Doc = DocumentApp.openById('1INkRIviwdjMC-PVT9io5LpiiLW8VwwIfgbq2E4xvKEo');
var image = DocsList.getFileById('0B3qSFd3iikE3cF8tSTI4bWxFMGM')
var totalElements = Doc.getNumChildren();
var el=[]
for( var j = 0; j < totalElements; ++j ) {
var element = Doc.getChild(j);
var type = element.getType();
Logger.log(j+" : "+type);// to see doc's content
if (type =='PARAGRAPH'){
el[j]=element.getText()
if(el[j]=='###'){element.removeFromParent();// remove the ###
Doc.insertImage(j, image);// 'image' is the image file as blob
}
}
}
}
EDIT : for this script to work the ### string MUST be alone in its paragraph, no other character before nor after... remember that each time one forces a new line with ENTER the Document creates a new paragraph.

Resources