Save Workbook
@params {array} wb Workbook
@params {callback} cb Callback
517582
function saveWorkbook(cb) {
		//console.log(wb);
		var XLSX;

		if (typeof filename == 'undefined') {
			res = wb;
		} else {
			XLSX = getXLSX();

			if (utils.isNode || utils.isMeteorServer) {
				XLSX.writeFile(wb, filename);
			} else {
				var wopts = {bookType: 'xlsx', bookSST: false, type: 'binary'};
				var wbout = XLSX.write(wb, wopts);

				function s2ab(s) {
					var buf = new ArrayBuffer(s.length);
					var view = new Uint8Array(buf);
					for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
					return buf;
				}

				/* the saveAs call downloads a file on the local machine */
				//				saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), '"'+filename+'"')
				//				saveAs(new Blob([s2ab(wbout)],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}), filename)
				//				saveAs(new Blob([s2ab(wbout)],{type:"application/vnd.ms-excel"}), '"'+filename+'"');
				if (isIE() == 9) {
					throw new Error(
						'Cannot save XLSX files in IE9. Please use XLS() export function'
					);
					//					var URI = 'data:text/plain;charset=utf-8,';

					/** @todo Check if this code is required */

					/*/*
					var testlink = window.open("about:blank", "_blank");
					var s = '';
					for(var i=0,ilen=wbout.length;i<ilen;i++) {
						var ch = wbout.charCodeAt(i);
						if(i<20) console.log('&#'+ch+';');
						s += '&#x'+ch.toString(16)+';';
					};
					testlink.document.write(s); //fileData has contents for the file
					testlink.document.close();
					testlink.document.execCommand('SaveAs', false, filename);
					testlink.close();
*/
					//					alert('ie9');
				} else {
					saveAs(new Blob([s2ab(wbout)], {type: 'application/octet-stream'}), filename);
				}
			}
		}
		/*/*
		// data.forEach(function(d){
		// 	s += columns.map(function(col){
		// 		return d[col.columnid];
		// 	}).join(opts.separator)+'\n';
		// });
		// alasql.utils.saveFile(filename,s);
*/
	}
441761
function save(callback) {
            var model, request;

            model = this;

            this.constructor.dispatch('beforeSave', {
                data : {
                    model : this
                }
            });
            this.dispatch('beforeSave');

            this.isValid(function (isValid) {
                if (isValid) {
                    if (model.hasOwnProperty('id') && model.id !== '') {
                        request = {
                            action : 'update',
                            data : model,
                            model : model.constructor
                        };
                        model.constructor.storage.update(request, function updateCallback(data) {
                            model.constructor.dispatch('afterSave', {
                                data : {
                                    model : model
                                }
                            });

                            model.dispatch('afterSave');
                            if (callback) {
                                callback(data);
                            }
                        });
                    }
                    else {
                        request = {
                            action : 'create',
                            data : model,
                            model : model.constructor
                        };
                        model.constructor.storage.create(request, function createCallback(data) {
                            model.constructor.dispatch('afterSave', {
                                data : {
                                    model : model
                                }
                            });

                            model.dispatch('afterSave');
                            if (callback) {
                                callback(data);
                            }
                        });
                    }
                } else {
                    if (callback) {
                        callback(data);
                    }
                }
            });

        }
861234
def save_sheet(opts = {})
      range = Args::CardRange.new(opts[:range], deck_size: size)
      batch = Args::SaveBatch.new.load!(opts, expand_by: size, layout: layout, dpi: dpi)
      sheet = Args::Sheet.new(custom_colors, { margin: 0 }, size).load!(opts, expand_by: size, layout: layout, dpi: dpi)
      sprue_file = Args::SprueFile.new.load!(opts, expand_by: size)

      if sprue_file.sprue.nil?
        render_sheet(range, batch, sheet)
      else
        tmpl = Sprue.load sprue_file.sprue, dpi
        Graphics::SaveSpruePNG.
          new(self, tmpl, sheet).
          render_sheet(range)
      end
    end
210617
function _storeVbreak()
    {
        // Return if the user hasn't specified pagebreaks
        if (empty($this->_vbreaks)) {
            return;
        }

        // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
        // It is slightly higher in Excel 97/200, approx. 1026
        $breaks = array_slice($this->_vbreaks,0,1000);

        // Sort and filter array of page breaks
        sort($breaks, SORT_NUMERIC);
        if ($breaks[0] == 0) { // don't use first break if it's 0
            array_shift($breaks);
        }

        $record  = 0x001a;               // Record identifier
        $cbrk    = count($breaks);       // Number of page breaks
        if ($this->_BIFF_version == 0x0600) {
            $length  = 2 + 6*$cbrk;      // Bytes to follow
        } else {
            $length  = 2 + 2*$cbrk;      // Bytes to follow
        }

        $header  = pack("vv",  $record, $length);
        $data    = pack("v",   $cbrk);

        // Append each page break
        foreach ($breaks as $break) {
            if ($this->_BIFF_version == 0x0600) {
                $data .= pack("vvv", $break, 0x0000, 0xffff);
            } else {
                $data .= pack("v", $break);
            }
        }

        $this->_prepend($header . $data);
    }
987072
function save(scriptModule, agent, msg, cb) {
    const filepath = path.join(scriptModule.root, msg.filename);

    fs.writeFile(filepath, msg.body, (err) => {
        if (err) {
            logger.error(`fail to write script file:${msg.filename}, ${err.stack}`);
            cb(`fail to write script file:${msg.filename}`);
            return;
        }

        cb();
    });
}
634512
def save_cb(self):
        """"""

        # This just defines the basename.
        # Extension has to be explicitly defined or things can get messy.
        w = Widgets.SaveDialog(title='Save plot')
        target = w.get_path()
        if target is None:
            # Save canceled
            return

        plot_ext = self.settings.get('file_suffix', '.png')

        if not target.endswith(plot_ext):
            target += plot_ext

        # TODO: This can be a user preference?
        fig_dpi = 100

        try:
            fig = self.tab_plot.get_figure()
            fig.savefig(target, dpi=fig_dpi)

        except Exception as e:
            self.logger.error(str(e))
        else:
            self.logger.info('Table plot saved as {0}'.format(target))
433783
def _save_cb(self, w):
        
        format = self.saved_type
        if format is None:
            return self.fv.show_error("Please save an image first.")

        # create filename
        filename = self.w.name.get_text().strip()
        if len(filename) == 0:
            return self.fv.show_error("Please set a name for saving the file")
        self.save_name = filename

        if not filename.lower().endswith('.' + format):
            filename = filename + '.' + format

        # join to path
        path = self.w.folder.get_text().strip()
        if path == '':
            path = filename
        else:
            self.save_path = path
            path = os.path.join(path, filename)

        # copy last saved file
        self.fv.error_wrap(shutil.copyfile, self.tmpname, path)
637290
def _save_xls(self, filepath):
        

        Interface = self.type2interface["xls"]

        workbook = xlwt.Workbook()
        interface = Interface(self.grid.code_array, workbook)
        interface.from_code_array()

        try:
            workbook.save(filepath)

        except IOError, err:
            try:
                post_command_event(self.main_window, self.StatusBarMsg,
                                   text=err)
            except TypeError:
                # The main window does not exist any more
                pass
1169748
function(doc, callback) {
        audit([doc], function(err) {
          if (err) {
            return callback(err);
          }
          docsDb.saveDoc(doc, callback);
        });
      }
605289
function write (buffer, cb) {
		if (isStopped) return false

		//test if we have to end
		//FIXME it should wait till all the data fed
		if (buffer == null) {
			callbackQueue.push(function () {
				end()
				cb && cb()
			})
			callbackMarks.push(count)
			return null
		}

		//push buffer
		if (!isAudioBuffer(buffer)) {
			buffer = createBuffer(buffer, {
				channels,
				context
			})
		}

		count += buffer.length
		data.append(buffer)

		//save callback
		if (cb) {
			callbackQueue.push(cb)
			callbackMarks.push(count)
		}

		return buffer
	}
1045430
function (_data, cb) {
      if(!db.data) return cb(new Error('kiddb not open'))
      if(!writing) return db._update(_data, cb)
      db.__data = _data
      qcb.push(cb)
      onWrote = function () {
        onWrote = null
        var cbs = qcb; qcb = []
        var _data = db.__data
        db.__data = null
        db.update(_data, function (err) {
          cbs.forEach(function (cb) {
            cb(err)
          })
        })
      }
    }
470251
function saveComponent(req, cb) {
  req.pause(); // Wait for tempdir.

  temp.mkdir('bowerball-', function (err, dirPath) {
    if (err) { return cb(err); }

    var filePath   = dirPath + '/component.json',
        fileStream = fs.createWriteStream(filePath, {flags: 'w', mode: '0600'});

    fileStream.on('open', function (fd) {
      req.on('end', function () { return cb(null, dirPath, filePath); });
      req.pipe(fileStream);
      req.resume();
    });
  });
}
949792
function (req, file, cb) {
            const id = guid();
            file.id = id;
            fs.writeFileSync(path.normalize(tempFolder + "/" + id + ".json"), JSON.stringify(file), "utf8");
            cb(null, id);
        }
400292
function parse_wb_bin(data, opts) {
	var wb = { AppVersion:{}, WBProps:{}, WBView:[], Sheets:[], CalcPr:{}, xmlns: "" };
	var state = [];
	var pass = false;

	if(!opts) opts = {};
	opts.biff = 12;

	var Names = [];
	var supbooks = ([[]]);
	supbooks.SheetNames = [];
	supbooks.XTI = [];

	recordhopper(data, function hopper_wb(val, R_n, RT) {
		switch(RT) {
			case 0x009C: /* 'BrtBundleSh' */
				supbooks.SheetNames.push(val.name);
				wb.Sheets.push(val); break;

			case 0x0099: /* 'BrtWbProp' */
				wb.WBProps = val; break;

			case 0x0027: /* 'BrtName' */
				if(val.Sheet != null) opts.SID = val.Sheet;
				val.Ref = stringify_formula(val.Ptg, null, null, supbooks, opts);
				delete opts.SID;
				delete val.Ptg;
				Names.push(val);
				break;
			case 0x040C: /* 'BrtNameExt' */ break;

			case 0x0165: /* 'BrtSupSelf' */
			case 0x0166: /* 'BrtSupSame' */
			case 0x0163: /* 'BrtSupBookSrc' */
			case 0x029B: /* 'BrtSupAddin' */
				if(!supbooks[0].length) supbooks[0] = [RT, val];
				else supbooks.push([RT, val]);
				supbooks[supbooks.length - 1].XTI = [];
				break;
			case 0x016A: /* 'BrtExternSheet' */
				if(supbooks.length === 0) { supbooks[0] = []; supbooks[0].XTI = []; }
				supbooks[supbooks.length - 1].XTI = supbooks[supbooks.length - 1].XTI.concat(val);
				supbooks.XTI = supbooks.XTI.concat(val);
				break;
			case 0x0169: /* 'BrtPlaceholderName' */
				break;

			/* case 'BrtModelTimeGroupingCalcCol' */
			case 0x0C00: /* 'BrtUid' */
			case 0x0C01: /* 'BrtRevisionPtr' */
			case 0x0817: /* 'BrtAbsPath15' */
			case 0x0216: /* 'BrtBookProtection' */
			case 0x02A5: /* 'BrtBookProtectionIso' */
			case 0x009E: /* 'BrtBookView' */
			case 0x009D: /* 'BrtCalcProp' */
			case 0x0262: /* 'BrtCrashRecErr' */
			case 0x0802: /* 'BrtDecoupledPivotCacheID' */
			case 0x009B: /* 'BrtFileRecover' */
			case 0x0224: /* 'BrtFileSharing' */
			case 0x02A4: /* 'BrtFileSharingIso' */
			case 0x0080: /* 'BrtFileVersion' */
			case 0x0299: /* 'BrtFnGroup' */
			case 0x0850: /* 'BrtModelRelationship' */
			case 0x084D: /* 'BrtModelTable' */
			case 0x0225: /* 'BrtOleSize' */
			case 0x0805: /* 'BrtPivotTableRef' */
			case 0x0254: /* 'BrtSmartTagType' */
			case 0x081C: /* 'BrtTableSlicerCacheID' */
			case 0x081B: /* 'BrtTableSlicerCacheIDs' */
			case 0x0822: /* 'BrtTimelineCachePivotCacheID' */
			case 0x018D: /* 'BrtUserBookView' */
			case 0x009A: /* 'BrtWbFactoid' */
			case 0x045D: /* 'BrtWbProp14' */
			case 0x0229: /* 'BrtWebOpt' */
			case 0x082B: /* 'BrtWorkBookPr15' */
				break;

			case 0x0023: /* 'BrtFRTBegin' */
				state.push(R_n); pass = true; break;
			case 0x0024: /* 'BrtFRTEnd' */
				state.pop(); pass = false; break;
			case 0x0025: /* 'BrtACBegin' */
				state.push(R_n); pass = true; break;
			case 0x0026: /* 'BrtACEnd' */
				state.pop(); pass = false; break;

			case 0x0010: /* 'BrtFRTArchID$' */ break;

			default:
				if((R_n||"").indexOf("Begin") > 0){/* empty */}
				else if((R_n||"").indexOf("End") > 0){/* empty */}
				else if(!pass || (opts.WTF && state[state.length-1] != "BrtACBegin" && state[state.length-1] != "BrtFRTBegin")) throw new Error("Unexpected record " + RT + " " + R_n);
		}
	}, opts);

	parse_wb_defaults(wb);

	// $FlowIgnore
	wb.Names = Names;

	(wb).supbooks = supbooks;
	return wb;
}
1271752
function backupFiles(job, iFile, cb) {
   if (isUndefined(cb)) {
      cb = iFile;
      iFile = 0;
   }

   if (iFile === job.document.files.length) {
      cb();
      return;
   } 

   var file = job.document.files[iFile];
   if (isUndefined(file)) {
      cb(new Error('empty file specification'));
      return;
   }

   if (isUndefined(file.fileName)) {
      cb(new Error('fileName missing'));
      return;
   }

   var filePath = path.resolve(job.document.workingDirectory || '', file.fileName);
   if (!fs.existsSync(filePath)) {
      backupFiles(job, iFile + 1, cb);
      return;
   }

   job.inProgress({ operation: job.operation, step: 'backing up existing file', fileName: file.fileName }, function(err) {
      showJobsError(err);
      copyFile(filePath, filePath + '.old', function(copyFileError) {
         if (isUndefined(copyFileError)) {
            backupFiles(job, iFile + 1, cb);
         } else {
            cb(copyFileError);
         }
      });
   });
}
148985
function write_biff8_buf(wb, opts) {
	var o = opts || {};
	var bufs = [];

	if(wb && !wb.SSF) {
		wb.SSF = SSF.get_table();
	}
	if(wb && wb.SSF) {
		make_ssf(SSF); SSF.load_table(wb.SSF);
		// $FlowIgnore
		o.revssf = evert_num(wb.SSF); o.revssf[wb.SSF[65535]] = 0;
		o.ssf = wb.SSF;
	}
	o.cellXfs = [];
	o.Strings = []; o.Strings.Count = 0; o.Strings.Unique = 0;
	get_cell_style(o.cellXfs, {}, {revssf:{"General":0}});

	for(var i = 0; i < wb.SheetNames.length; ++i) bufs[bufs.length] = write_ws_biff8(i, o, wb);
	bufs.unshift(write_biff8_global(wb, bufs, o));
	return __toBuffer([bufs]);
}
683982
function (cb) {
    this.reset();
    var bundle = this.bundle;
    var self = this;
    async.waterfall([
      function (wfCb) {
        if (self.noclean) {
          wfCb();
        } else {
          // Remove the output directory if it exists
          existsCompat(self.outputTo, function (exists) {
            if (exists) {
              if (self.verbose) {
                console.log('compileAssets: removing output directory: ' + self.outputTo);
              }
              rimraf(self.outputTo, wfCb);
            } else {
              wfCb();
            }
          });
        }
      },
      function (wfCb) {
        if (self.verbose) {
          console.log('compileAssets: starting asset discovery phase.');
        }
        executePhase(self.phases.discovery, bundle, wfCb);
      },
      function (b, wfCb) {
        if (self.verbose) {
          console.log('compileAssets: starting compilation phase.');
        }
        try {
          // Get the correct order of asset dependencies
          var orderedAssets = bundle.getProcessingOrder().map(function (assetFilePath) {
            return bundle.getAsset(assetFilePath);
          });
          async.eachSeries(orderedAssets, function (asset, eachCb) {
            setImmediateCompat(function() {
              executePhase(self.phases.compilation, asset, eachCb);
            });
          }, wfCb);
        }
        catch (e) {
          wfCb(e);
        }
      }, function (wfCb) {
        if (self.verbose) {
          console.log('compileAssets: starting post-compilation phase.');
        }
        async.eachLimit(bundle.getAllAssets(), 50, function (asset, eachCb) {
          executePhase(self.phases.postCompilation, asset, eachCb);
        }, wfCb);
      }, function (wfCb) {
        if (self.verbose) {
          console.log('compileAssets: starting output phase.');
        }
        async.eachLimit(bundle.getAllAssets(), 50, function (asset, eachCb) {
          executePhase(self.phases.output, asset, eachCb);
        }, wfCb);
      }
    ], cb);
  }