File approve event handler
517085
def OnApprove(self, event):
        """"""

        if not self.main_window.safe_mode:
            return

        msg = _(u"You are going to approve and trust a file that\n"
                u"you have not created yourself.\n"
                u"After proceeding, the file is executed.\n \n"
                u"It may harm your system as any program can.\n"
                u"Please check all cells thoroughly before\nproceeding.\n \n"
                u"Proceed and sign this file as trusted?")

        short_msg = _("Security warning")

        if self.main_window.interfaces.get_warning_choice(msg, short_msg):
            # Leave safe mode
            self.main_window.grid.actions.leave_safe_mode()

            # Display safe mode end in status bar

            statustext = _("Safe mode deactivated.")
            post_command_event(self.main_window, self.main_window.StatusBarMsg,
                               text=statustext)
574170
private void directoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_directoryButtonActionPerformed
        // Select save directory
        JFileChooser chooser = new JFileChooser();
        chooser.setDialogTitle("Directory Select");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            folderField.setText(chooser.getSelectedFile().getAbsolutePath()
                    + File.separator);
        }
    }
82329
function updateSubmission($submission, $files) {
        $this->_flagSubmitted = false;

        if (empty($submission)) {
            $this->_submitValues = array();
        } else {
            foreach ($submission as $key => $s) {
                $type = $this->getCleanType($key, $s);
                $submission[$key] = $this->getCleanedValue($s, $type);
            }
            $this->_submitValues = $submission;
            $this->_flagSubmitted = true;
        }

        if (empty($files)) {
            $this->_submitFiles = array();
        } else {
            $this->_submitFiles = $files;
            $this->_flagSubmitted = true;
        }

        // need to tell all elements that they need to update their value attribute.
         foreach (array_keys($this->_elements) as $key) {
             $this->_elements[$key]->onQuickFormEvent('updateValue', null, $this);
         }
    }
180302
function onFile(__newFile, encoding, done) {
  var buffers = [];
  var options = this.options;

  // Check the file limit
  if (options.perMaxBytes && __newFile.byteCount > options.perMaxBytes) {
    return done(new Error('The file \'' + __newFile.filename + '\' beyond size limit, only accept less than ' + options.perMaxBytes + ' bytes'));
  }

  // Check the accept content type
  if (options.acceptTypes && options.acceptTypes.indexOf(__newFile.headers['content-type']) === -1) {
    return done(new Error('Content-type of the file \'' + __newFile.filename + '\' does not accepted'));
  }

  // Determine the file descriptor-- the unique identifier.
  // Often represents the location where file should be written.
  __newFile.fd;
  var uploadDir = __newFile.fd;
  if (uploadDir.substr(0, 1) !== '/') {
    uploadDir = '/' + uploadDir;
  }

  // When then 'data' event emited, push the chunk to the buffers array.
  __newFile.on('data', function (chunk) {
    buffers.push(chunk);
  });

  // When the 'end' event emited, upload the 'buffers' to the upyun server.
  __newFile.on('end', function () {
    var buffer = Buffer.concat(buffers);
    uploadToUpyun.bind({ options })(uploadDir, buffer, __newFile, done);
  });
}
131629
function(files, target, fm, isDir) {
			var dfrd = $.Deferred(),
				names, renames = [], hashes = {}, chkFiles = [],
				cancel = function() {
					var i = files.length;
					while (--i > -1) {
						files[i]._remove = true;
					}
				},
				resolve = function() {
					dfrd.resolve(renames, hashes);
				},
				check = function() {
					var existed = [], exists = [], i, c,
						pathStr = target !== fm.cwd().hash? fm.path(target, true) + fm.option('separator', target) : '',
						confirm = function(ndx) {
							var last = ndx == exists.length-1,
								opts = {
									cssClass : 'elfinder-confirm-upload',
									title  : fm.i18n('cmdupload'),
									text   : ['errExists', pathStr + exists[ndx].name, 'confirmRepl'], 
									all    : !last,
									accept : {
										label    : 'btnYes',
										callback : function(all) {
											!last && !all
												? confirm(++ndx)
												: resolve();
										}
									},
									reject : {
										label    : 'btnNo',
										callback : function(all) {
											var i;
			
											if (all) {
												i = exists.length;
												while (ndx < i--) {
													files[exists[i].i]._remove = true;
												}
											} else {
												files[exists[ndx].i]._remove = true;
											}
			
											!last && !all
												? confirm(++ndx)
												: resolve();
										}
									},
									cancel : {
										label    : 'btnCancel',
										callback : function() {
											cancel();
											resolve();
										}
									},
									buttons : [
										{
											label : 'btnBackup',
											cssClass : 'elfinder-confirm-btn-backup',
											callback : function(all) {
												var i;
												if (all) {
													i = exists.length;
													while (ndx < i--) {
														renames.push(exists[i].name);
													}
												} else {
													renames.push(exists[ndx].name);
												}
												!last && !all
													? confirm(++ndx)
													: resolve();
											}
										}
									]
								};
							
							if (!isDir) {
								opts.buttons.push({
									label : 'btnRename' + (last? '' : 'All'),
									cssClass : 'elfinder-confirm-btn-rename',
									callback : function() {
										renames = null;
										resolve();
									}
								});
							}
							if (fm.iframeCnt > 0) {
								delete opts.reject;
							}
							fm.confirm(opts);
						};
					
					if (! fm.file(target).read) {
						// for dropbox type
						resolve();
						return;
					}
					
					names = $.map(files, function(file, i) { return file.name && (!fm.UA.iOS || file.name !== 'image.jpg')? {i: i, name: file.name} : null ;});
					
					fm.request({
						data : {cmd : 'ls', target : target, intersect : $.map(names, function(item) { return item.name;})},
						notify : {type : 'preupload', cnt : 1, hideCnt : true},
						preventDefault : true
					})
					.done(function(data) {
						var existedArr, cwdItems;
						if (data) {
							if (data.error) {
								cancel();
							} else {
								if (fm.options.overwriteUploadConfirm && fm.option('uploadOverwrite', target)) {
									if (data.list) {
										if (Array.isArray(data.list)) {
											existed = data.list || [];
										} else {
											existedArr = [];
											existed = $.map(data.list, function(n) {
												if (typeof n === 'string') {
													return n;
												} else {
													// support to >=2.1.11 plugin Normalizer, Sanitizer
													existedArr = existedArr.concat(n);
													return false;
												}
											});
											if (existedArr.length) {
												existed = existed.concat(existedArr);
											}
											hashes = data.list;
										}
										exists = $.grep(names, function(name){
											return $.inArray(name.name, existed) !== -1 ? true : false ;
										});
										if (exists.length && existed.length && target == fm.cwd().hash) {
											cwdItems = $.map(fm.files(target), function(file) { return file.name; } );
											if ($.grep(existed, function(n) { 
												return $.inArray(n, cwdItems) === -1? true : false;
											}).length){
												fm.sync();
											}
										}
									}
								}
							}
						}
						if (exists.length > 0) {
							confirm(0);
						} else {
							resolve();
						}
					})
					.fail(function(error) {
						cancel();
						resolve();
						error && fm.error(error);
					});
				};
			if (fm.api >= 2.1 && typeof files[0] == 'object') {
				check();
			} else {
				resolve();
			}
			return dfrd;
		}
1278782
function pollStatusFile(fileKey) {
  return poll(function onPoll(onSuccess, onError, next) {
    /*
    1. Read status file content
    2. Check if we're done -> call onSuccess
       Check if it failed  -> call onError
       Otherwise call next
     */
    getFromStorage(fileKey, { type: "json", cdn: false }).then(function checkContent(content) {
      if (content && content.params) {
        switch (content.params.status) {
          case 'SUCCESS':
            onSuccess(content.params.data)
            break
          case 'PROCESSING':
          case 'ENQUEUED':
            next()
            break
          default:
            onError(content.params.data)
        }
      }
    })
  })
}
1077547
private void processFileNotifications() throws InterruptedException, TTException, IOException {
        while (true) {
            WatchKey key = mWatcher.take();
            Path dir = mKeyPaths.get(key);
            for (WatchEvent<?> evt : key.pollEvents()) {
                WatchEvent.Kind<?> eventType = evt.kind();
                if (eventType == OVERFLOW)
                    continue;
                Object o = evt.context();
                if (o instanceof Path) {
                    Path path = dir.resolve((Path)evt.context());
                    process(dir, path, eventType);
                }
            }
            key.reset();

            processFsnOnHold();
        }
    }
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();
    }
1155724
function handleFile(dir, options) {
  return filename => {
    const file = parseFile(dir, filename);

    debug(`found "${filename}"`);

    // Exit early if this item is not a file.
    if (!file.stat.isFile()) {
      debug(`skipped "${filename}" (not a file)`);
      return;
    }

    // Exit early if this item is not the right file type.
    if (!options.extensions.includes(file.ext)) {
      debug(`skipped "${filename}" (incorrect file type)`);
      return;
    }

    registerTask(file, options);
  };
}
678024
function handleEvent(cmd, context, filename, callback) {
  var event = JSON.parse(cmd)
  eventline.route(event)
}
197767
def emit_accepted(self):
        
        if self.result():
            filename = self.selectedFiles()[0]
            if os.path.isdir(os.path.dirname(filename)):
                self.dlg_accepted.emit(filename)
46147
def _get_file_event_handler(self, file_path, save_name):
        
        self._file_pusher.update_file(save_name, file_path)  # track upload progress

        if save_name not in self._file_event_handlers:
            if save_name == 'wandb-history.jsonl':
                self._file_event_handlers['wandb-history.jsonl'] = FileEventHandlerTextStream(
                    file_path, 'wandb-history.jsonl', self._api)
            elif save_name == 'wandb-events.jsonl':
                self._file_event_handlers['wandb-events.jsonl'] = FileEventHandlerTextStream(
                    file_path, 'wandb-events.jsonl', self._api)
            elif 'tfevents' in save_name or 'graph.pbtxt' in save_name:
                # overwrite the tensorboard but not every reload -- just
                # frequently enough to resemble realtime
                self._file_event_handlers[save_name] = FileEventHandlerThrottledOverwrite(
                    file_path, save_name, self._api, self._file_pusher)
            # Don't try to stream tensorboard files for now.
            # elif 'tfevents' in save_name:
            #    # TODO: This is hard-coded, but we want to give users control
            #    # over streaming files (or detect them).
            #    self._api.get_file_stream_api().set_file_policy(save_name,
            #                                                    BinaryFilePolicy())
            #    self._file_event_handlers[save_name] = FileEventHandlerBinaryStream(
            #        file_path, save_name, self._api)
            # Overwrite handler (non-deferred) has a bug, wherein if the file is truncated
            # during upload, the request to Google hangs (at least, this is my working
            # theory). So for now we defer uploading everything til the end of the run.
            # TODO: send wandb-summary during run. One option is to copy to a temporary
            # file before uploading.
            elif save_name == config.FNAME:
                self._file_event_handlers[save_name] = FileEventHandlerConfig(
                    file_path, save_name, self._api, self._file_pusher, self._run)
            elif save_name == 'wandb-summary.json':
                # Load the summary into the syncer process for meta etc to work
                self._run.summary.load()
                self._api.get_file_stream_api().set_file_policy(save_name, OverwriteFilePolicy())
                self._file_event_handlers[save_name] = FileEventHandlerSummary(
                    file_path, save_name, self._api, self._file_pusher, self._run)
            elif save_name.startswith('media/'):
                # Save media files immediately
                self._file_event_handlers[save_name] = FileEventHandlerOverwrite(
                    file_path, save_name, self._api, self._file_pusher)
            else:
                Handler = FileEventHandlerOverwriteDeferred
                for policy, globs in six.iteritems(self._user_file_policies):
                    if policy == "end":
                        continue
                    for g in globs:
                        if any(save_name in p for p in glob.glob(os.path.join(self._run.dir, g))):
                            if policy == "live":
                                Handler = FileEventHandlerThrottledOverwriteMinWait
                self._file_event_handlers[save_name] = Handler(
                    file_path, save_name, self._api, self._file_pusher)
        return self._file_event_handlers[save_name]
1157239
function(file, event) {
    var fn = function(file) {};
    for(var i = 0; i < watchList.length; i++) {
        if(watchList[i].file === file) {
            watchers[i].on(event, fn);
            watchList[i].callback[event] = fn;
            return;
        }
    }
    throw new Error(file + " was not being watched previously");
}
464901
public void verify(@Nullable T value, Path filePath) {
        Pre.notNull(filePath, "filePath");

        File file = mapFilePath(value, filePath);

        File parentPathDirectory = file.getParentFile();
        if (parentPathDirectory != null && !parentPathDirectory.exists()) {
            try {
                fileSystemReadWriter.createDirectories(parentPathDirectory);
            } catch (IOException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
        }
        Path approvalPath = getApprovalPath(file.toPath());
        byte[] rawValue = converter.getRawForm(value);
        if (!file.exists()) {
            LOG.info(file + " didn't exist. You will be asked for approval");
            handleFirstTimeApproval(file, approvalPath, rawValue);
            return;
        }

        // Change the modification time. This will allow users to delete orphaned files
        // https://github.com/nikolavp/approval/issues/18
        boolean wasAbleSetModified = file.setLastModified(System.currentTimeMillis());
        if (!wasAbleSetModified) {
            LOG.warning("We weren't able to change the modification date for " + file.getAbsolutePath());
        }

        try {
            byte[] fileContent = fileSystemReadWriter.readFully(file.toPath());
            if (!Arrays.equals(fileContent, rawValue)) {
                try {
                    LOG.info("Approval in " + file + " is not the same as the last value. You will be asked for approval of the new value.");
                    fileSystemReadWriter.write(approvalPath, rawValue);
                } catch (IOException e) {
                    throw new AssertionError("Couldn't write the new approval file " + file, e);
                }
                reporter.notTheSame(fileContent, file, rawValue, approvalPath.toFile());
            }
        } catch (IOException e) {
            throw new AssertionError("Couldn't read the previous content in file " + file, e);
        }

        //value approved
    }
1087809
function (e, data) {
                if (e.isDefaultPrevented()) {
                    return false;
                }
                var $this = $(this),
                    that = $this.data('blueimp-fileupload') ||
                        $this.data('fileupload'),
                    options = that.options;
                data.context = that._renderUpload(data.files)
                    .data('data', data)
                    .addClass('processing');
                options.filesContainer[
                    options.prependFiles ? 'prepend' : 'append'
                ](data.context);
                that._forceReflow(data.context);
                that._transition(data.context);
                data.process(function () {
                    return $this.fileupload('process', data);
                }).always(function () {
                    data.context.each(function (index) {
                        $(this).find('.size').text(
                            that._formatFileSize(data.files[index].size)
                        );
                    }).removeClass('processing');
                    that._renderPreviews(data);
                }).done(function () {
                    data.context.find('.start').prop('disabled', false);
                    if ((that._trigger('added', e, data) !== false) &&
                            (options.autoUpload || data.autoUpload) &&
                            data.autoUpload !== false) {
                        data.submit();
                    }
                }).fail(function () {
                    if (data.files.error) {
                        data.context.each(function (index) {
                            var error = data.files[index].error;
                            if (error) {
                                $(this).find('.error').text(error);
                            }
                        });
                    }
                });
            }
1018505
function(eventArgs) {
                if (eventArgs.kind === Windows.ApplicationModel.Activation.ActivationKind.pickSaveFileContinuation) {
                    var file = eventArgs.file;
                    saveFile(file);
                    webUIApp.removeEventListener("activated", fileSaveHandler);
                }
            }
908419
function onFile(filePath, stat) {
      if (filePath.match(ignore) || filePath.match(globalIgnore)) { return; }
      var newTimestamp = updateTimestamp(stat.mtime);
      if (manifest['CACHE'].insert(toUrl(cleanPath(filePath))) || newTimestamp) {
        updateListener(manifest);
      }
    }