Upload a file into a blob table
975060
def insert_blob(filename, hosts=None, table=None):
    
    conn = connect(hosts)
    container = conn.get_blob_container(table)
    with open(filename, 'rb') as f:
        digest = container.put(f)
    return '{server}/_blobs/{table}/{digest}'.format(
        server=conn.client.active_servers[0],
        table=table,
        digest=digest
    )
1374417
def next_blob(self):
        """"""
        try:
            length = struct.unpack('<i', self.blob_file.read(4))[0]
        except struct.error:
            raise StopIteration
        header = CLBHeader(file_obj=self.blob_file)
        blob = {'CLBHeader': header}
        remaining_length = length - header.size
        pmt_data = []
        pmt_raw_data = self.blob_file.read(remaining_length)
        pmt_raw_data_io = BytesIO(pmt_raw_data)
        for _ in range(int(remaining_length / 6)):
            channel_id, time, tot = struct.unpack(
                '>cic', pmt_raw_data_io.read(6)
            )
            pmt_data.append(PMTData(ord(channel_id), time, ord(tot)))
        blob['PMTData'] = pmt_data
        blob['PMTRawData'] = pmt_raw_data
        return blob
559785
async function uploadFiles( store, session, caslib, datadir ) {
    let files = readdir(datadir);
    let executeCmd = session.links('execute');

    for (let i = 0 ; i < files.length ;i++) {
    
        let parms = { caslib: caslib, name: files[i],  quiet : true};
        await store.runAction(session, {action: 'table.dropTable', data: parms})

        parms = { caslib: caslib, source: files[i],quiet : true};
        await store.runAction(session, {action: 'table.deleteSource', data: parms})

        parms = {
            rstore: { name: files[i], caslib: caslib, replace: true},
            store : readFile(files[i], datadir)
        };
        payload = { action: 'aStore.upload', data: parms };
        console.log( `uploading  ${files[i]}`);
        await store.runAction(session, payload);
        
        parms = { rstore: { name: files[i], caslib: caslib } };
        payload = { action: 'aStore.describe', data: parms };
        await store.runAction(session, payload);
       
        parms = {
            caslib : caslib,
            name   : files[i],
            replace: true,
            table: {
                caslib: caslib,
                name  : files[i]
            }
        };
        payload ={action: 'table.save', data: parms};
        await store.runAction(session, payload);

    }
}
239650
function base64toBlob(base64Data, contentType, sliceSize) {
        contentType = contentType || '';
        sliceSize = sliceSize || 512;

        var byteCharacters = atob(base64Data);
        var byteArrays = [];

        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);
            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
        }

        return new Blob(byteArrays, {type: contentType});
    }
543561
def blob_put(self, table, digest, data):
        
        response = self._request('PUT', _blob_path(table, digest),
                                 data=data)
        if response.status == 201:
            # blob created
            return True
        if response.status == 409:
            # blob exists
            return False
        if response.status in (400, 404):
            raise BlobLocationNotFoundException(table, digest)
        _raise_for_status(response)
451494
function insertData(filename, tableSchema) {
  return getSampleData(filename).then(
      function(data) {
        var rows = data.map(function(obj) {
          return tableSchema.createRow(obj);
        });
        return db.insert().into(tableSchema).values(rows);
      });
}
230186
public Blob open_blob( String db, String table, String column, long row, boolean rw ) throws jsqlite.Exception {
        synchronized (this) {
            Blob blob = new Blob();
            _open_blob(db, table, column, row, rw, blob);
            return blob;
        }
    }
707162
function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
	{
	$blob_id = ibase_blob_create($this->_connectionID);

	// ibase_blob_add($blob_id, $val);

	// replacement that solves the problem by which only the first modulus 64K /
	// of $val are stored at the blob field ////////////////////////////////////
	// Thx Abel Berenstein  aberenstein#afip.gov.ar
	$len = strlen($val);
	$chunk_size = 32768;
	$tail_size = $len % $chunk_size;
	$n_chunks = ($len - $tail_size) / $chunk_size;

	for ($n = 0; $n < $n_chunks; $n++) {
		$start = $n * $chunk_size;
		$data = substr($val, $start, $chunk_size);
		ibase_blob_add($blob_id, $data);
	}

	if ($tail_size) {
		$start = $n_chunks * $chunk_size;
		$data = substr($val, $start, $tail_size);
		ibase_blob_add($blob_id, $data);
	}
	// end replacement /////////////////////////////////////////////////////////

	$blob_id_str = ibase_blob_close($blob_id);

	return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blob_id_str)) != false;

	}
409956
def fetch_blob(cls, username, password, multifactor_password=None, client_id=None):
        """"""
        session = fetcher.login(username, password, multifactor_password, client_id)
        blob = fetcher.fetch(session)
        fetcher.logout(session)

        return blob
308361
function update (table, columns, values) {
    if (this.typecheck) t.typecheck('update', [table, columns, values]);
    if ('string'===typeof columns) {
        columns = [columns];
        values = [values];
    }
    var result = [];
    for (var i=0; i < columns.length; i++) {
        var value = ('string'===typeof values[i]
            // X\'blob\' \'\\xblob\'
            && values[i].indexOf("X\'") != 0 && values[i].indexOf("\'\\x") != 0)
            ? this.string(values[i]) : values[i];
        result.push(columns[i]+'='+value);
    }
    return ['update',table,'set',result.join()].join(' ');
}
1368042
def Upload(self,directory,filename):
        """"""

        db = self._loadDB(directory)

        logger.debug("wp: Attempting upload of %s"%(filename))

        # See if this already exists in our DB
        if db.has_key(filename):
            pid=db[filename]
            logger.debug('wp: Found %s in DB with post id %s'%(filename,pid))
        else:
            pid=None

        fullfile=os.path.join(directory,filename)

        fid=open(fullfile,'r');

        # Read meta data and content into dictionary
        post=self._readMetaAndContent(fid)

        #Connect to WP
        self._connectToWP()

        # If no pid, it means post is fresh off the press
        # and not uploaded yet!
        if not pid:
            # Get a PID by uploading
            pid=self.wp.call(NewPost(post))
            if pid:
                logger.debug("wp: Uploaded post with pid %s",pid)
                db[filename]=pid
                self._saveDB(directory,db)
                return True
            else:
                logger.error("wp: Couldn't upload post")
                return False
        else:
            # Already has PID, replace post
            logger.debug("wp: Replacing post with pid %s",pid)
            #FIXME: Check return value?!
            self.wp.call(EditPost(pid,post))
            return True

        return False
1343952
def blob_put(table, digest, data)
      uri = blob_path(table, digest)
      @logger.debug("BLOB PUT #{uri}")
      req = Net::HTTP::Put.new(blob_path(table, digest), headers)
      req.body = data
      response = request(req)
      case response.code
      when '201'
        true
      else
        @logger.info("Response #{response.code}: " + response.body)
        false
      end
    end
847165
function _bn_getFile(input) {
    // if there is custom file upload logic, for example, images are resized client-side
    // generated Blobs should be assigned to fileInput._file
    // and can be sent via ajax with FormData

    // if file was deleted, custom field can be set to an empty string

    // Bunny Validation detects if there is custom Blob assigned to file input
    // and uses this file for validation instead of original read-only input.files[]
    if (input._file !== undefined && input._file !== '') {
        if (input._file instanceof Blob === false) {
            console.error("Custom file for input " + input.name + " is not an instance of Blob");
            return false;
        }
        return input._file;
    }
    return input.files[0] || false;
}
109894
function UpdateBlob($table,$column,$val,$where,$blobtype='image')
	{
		$sql = "UPDATE $table SET $column = ? WHERE $where";
		if( !($stmt = @odbtp_prepare($sql, $this->_connectionID)) )
			return false;
		if( !@odbtp_input( $stmt, 1, ODB_BINARY, 1000000, $blobtype ) )
			return false;
		if( !@odbtp_set( $stmt, 1, $val ) )
			return false;
		return @odbtp_execute( $stmt ) != false;
	}
509889
def _prepare_upload(self, ase):
        # type: (Uploader, blobxfer.models.azure.StorageEntity) -> None
        
        if ase.mode == blobxfer.models.azure.StorageModes.Append:
            if ase.append_create:
                # create container if necessary
                blobxfer.operations.azure.blob.create_container(
                    ase, self._containers_created)
                # create remote blob
                blobxfer.operations.azure.blob.append.create_blob(ase)
        elif ase.mode == blobxfer.models.azure.StorageModes.Block:
            # create container if necessary
            blobxfer.operations.azure.blob.create_container(
                ase, self._containers_created)
        elif ase.mode == blobxfer.models.azure.StorageModes.File:
            # create share directory structure
            with self._fileshare_dir_lock:
                # create container if necessary
                blobxfer.operations.azure.file.create_share(
                    ase, self._containers_created)
                # create parent directories
                blobxfer.operations.azure.file.create_all_parent_directories(
                    ase, self._dirs_created)
            # create remote file
            blobxfer.operations.azure.file.create_file(ase)
        elif ase.mode == blobxfer.models.azure.StorageModes.Page:
            # create container if necessary
            blobxfer.operations.azure.blob.create_container(
                ase, self._containers_created)
            # create remote blob
            blobxfer.operations.azure.blob.page.create_blob(ase)
248770
def write_file(self, blob, dest):
        '''
        
        '''
        with salt.utils.files.fopen(dest, 'wb+') as fp_:
            blob.stream_data(fp_)
65324
function upload() {
      stop_loop = false;

      if (!files) {
        opts.error(errors[0]);
        return false;
      }

      if (opts.allowedfiletypes.push && opts.allowedfiletypes.length) {
        for(var fileIndex = files.length;fileIndex--;) {
          if(!files[fileIndex].type || $.inArray(files[fileIndex].type, opts.allowedfiletypes) < 0) {
            opts.error(errors[3], files[fileIndex]);
            return false;
          }
        }
      }

      var filesDone = 0,
          filesRejected = 0;

      if (files_count > opts.maxfiles && opts.queuefiles === 0) {
        opts.error(errors[1]);
        return false;
      }

      // Define queues to manage upload process
      var workQueue = [];
      var processingQueue = [];
      var doneQueue = [];

      // Add everything to the workQueue
      for (var i = 0; i < files_count; i++) {
        workQueue.push(i);
      }

      // Helper function to enable pause of processing to wait
      // for in process queue to complete
      var pause = function(timeout) {
        setTimeout(process, timeout);
        return;
      };

      // Process an upload, recursive
      var process = function() {

        var fileIndex;

        if (stop_loop) {
          return false;
        }

        // Check to see if are in queue mode
        if (opts.queuefiles > 0 && processingQueue.length >= opts.queuefiles) {
          return pause(opts.queuewait);
        } else {
          // Take first thing off work queue
          fileIndex = workQueue[0];
          workQueue.splice(0, 1);

          // Add to processing queue
          processingQueue.push(fileIndex);
        }

        try {
          if (beforeEach(files[fileIndex]) !== false) {
            if (fileIndex === files_count) {
              return;
            }
            var reader = new FileReader(),
                max_file_size = 1048576 * opts.maxfilesize;

            reader.index = fileIndex;
            if (files[fileIndex].size > max_file_size) {
              opts.error(errors[2], files[fileIndex], fileIndex);
              // Remove from queue
              processingQueue.forEach(function(value, key) {
                if (value === fileIndex) {
                  processingQueue.splice(key, 1);
                }
              });
              filesRejected++;
              return true;
            }

            reader.onloadend = !opts.beforeSend ? send : function (e) {
              opts.beforeSend(files[fileIndex], fileIndex, function () { send(e); });
            };

            reader.readAsBinaryString(files[fileIndex]);

          } else {
            filesRejected++;
          }
        } catch (err) {
          // Remove from queue
          processingQueue.forEach(function(value, key) {
            if (value === fileIndex) {
              processingQueue.splice(key, 1);
            }
          });
          opts.error(errors[0]);
          return false;
        }

        // If we still have work to do,
        if (workQueue.length > 0) {
          process();
        }
      };

      var send = function(e) {

        var fileIndex = ((typeof(e.srcElement) === "undefined") ? e.target : e.srcElement).index;

        // Sometimes the index is not attached to the
        // event object. Find it by size. Hack for sure.
        if (e.target.index === undefined) {
          e.target.index = getIndexBySize(e.total);
        }

        var xhr = new XMLHttpRequest(),
            upload = xhr.upload,
            file = files[e.target.index],
            index = e.target.index,
            start_time = new Date().getTime(),
            boundary = '------multipartformboundary' + (new Date()).getTime(),
            global_progress_index = global_progress.length,
            builder,
            newName = rename(file.name),
            mime = file.type;

        if (typeof newName === "string") {
          builder = getBuilder(newName, e.target.result, mime, boundary);
        } else {
          builder = getBuilder(file.name, e.target.result, mime, boundary);
        }

        upload.index = index;
        upload.file = file;
        upload.downloadStartTime = start_time;
        upload.currentStart = start_time;
        upload.currentProgress = 0;
        upload.global_progress_index = global_progress_index;
        upload.startData = 0;
        upload.addEventListener("progress", progress, false);

        xhr.open("POST", opts.url, true);
        xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);

        // Add headers
        $.each(opts.headers, function(k, v) {
          xhr.setRequestHeader(k, v);
        });

        xhr.sendAsBinary(builder);

        global_progress[global_progress_index] = 0;
        globalProgress();

        opts.uploadStarted(index, file, files_count);

        xhr.onload = function() {
            var serverResponse = null;

            if (xhr.responseText) {
              try {
                serverResponse = jQuery.parseJSON(xhr.responseText);
              }
              catch (e) {
                serverResponse = xhr.responseText;
              }
            }

            var now = new Date().getTime(),
                timeDiff = now - start_time,
                result = opts.uploadFinished(index, file, serverResponse, timeDiff, xhr);
            filesDone++;

            // Remove from processing queue
            processingQueue.forEach(function(value, key) {
              if (value === fileIndex) {
                processingQueue.splice(key, 1);
              }
            });

            // Add to donequeue
            doneQueue.push(fileIndex);

            // Make sure the global progress is updated
            global_progress[global_progress_index] = 100;
            globalProgress();

            if (filesDone === (files_count - filesRejected)) {
              afterAll();
            }
            if (result === false) {
              stop_loop = true;
            }
          

          // Pass any errors to the error option
          if (xhr.status < 200 && xhr.status > 299) {
            opts.error(xhr.statusText);
          }
        };
      };

      // Initiate the processing loop
      process();
    }