File import event handler
972911
def OnImport(self, event):
        """"""

        # Get filepath from user

        wildcards = get_filetypes2wildcards(["csv", "txt"]).values()
        wildcard = "|".join(wildcards)

        message = _("Choose file to import.")
        style = wx.OPEN
        filepath, filterindex = \
            self.interfaces.get_filepath_findex_from_user(wildcard, message,
                                                          style)

        if filepath is None:
            return

        # Get generator of import data
        import_data = self.main_window.actions.import_file(filepath,
                                                           filterindex)

        if import_data is None:
            return

        # Paste import data to grid
        grid = self.main_window.grid
        tl_cell = grid.GetGridCursorRow(), grid.GetGridCursorCol()

        grid.actions.paste(tl_cell, import_data)

        self.main_window.grid.ForceRefresh()
293182
def read(self, filehandle):
        """"""
        return self.__import(json.load(filehandle, **self.kwargs))
290056
def _filehandler(configurable):
    """"""

    filename = configurable.log_name.replace('.', sep)
    path = join(configurable.log_path, '{0}.log'.format(filename))

    return FileHandler(path, mode='a+')
1319615
def onImport(self, event):
        
        if self.grid.changes:
            print("-W- Your changes will be overwritten...")
            wind = pw.ChooseOne(self, "Import file anyway", "Save grid first",
                                "-W- Your grid has unsaved changes which will be overwritten if you import a file now...")
            wind.Centre()
            res = wind.ShowModal()
            # save grid first:
            if res == wx.ID_NO:
                self.onSave(None, alert=True, destroy=False)
                # reset self.changes
                self.grid.changes = set()

        openFileDialog = wx.FileDialog(self, "Open MagIC-format file", self.WD, "",
                                       "MagIC file|*.*", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
        result = openFileDialog.ShowModal()
        if result == wx.ID_OK:
            # get filename
            filename = openFileDialog.GetPath()
            # make sure the dtype is correct
            f = open(filename)
            line = f.readline()
            if line.startswith("tab"):
                delim, dtype = line.split("\t")
            else:
                delim, dtype = line.split("")
            f.close()
            dtype = dtype.strip()
            if (dtype != self.grid_type) and (dtype + "s" != self.grid_type):
                text = "You are currently editing the {} grid, but you are trying to import a {} file.\nPlease open the {} grid and then re-try this import.".format(self.grid_type, dtype, dtype)
                pw.simple_warning(text)
                return
            # grab old data for concatenation
            if self.grid_type in self.contribution.tables:
                old_df_container = self.contribution.tables[self.grid_type]
            else:
                old_df_container = None
            old_col_names = self.grid.col_labels
            # read in new file and update contribution
            df_container = cb.MagicDataFrame(filename, dmodel=self.dm,
                                             columns=old_col_names)
            # concatenate if possible
            if not isinstance(old_df_container, type(None)):
                df_container.df = pd.concat([old_df_container.df, df_container.df],
                                            axis=0, sort=True)
            self.contribution.tables[df_container.dtype] = df_container
            self.grid_builder = GridBuilder(self.contribution, self.grid_type,
                                            self.panel, parent_type=self.parent_type,
                                            reqd_headers=self.reqd_headers)
            # delete old grid
            self.grid_box.Hide(0)
            self.grid_box.Remove(0)
            # create new, updated grid
            self.grid = self.grid_builder.make_grid()
            self.grid.InitUI()
            # add data to new grid
            self.grid_builder.add_data_to_grid(self.grid, self.grid_type)
            # add new grid to sizer and fit everything
            self.grid_box.Add(self.grid, flag=wx.ALL, border=5)
            self.main_sizer.Fit(self)
            self.Centre()
            # add any needed drop-down-menus
            self.drop_down_menu = drop_down_menus.Menus(self.grid_type,
                                                        self.contribution,
                                                        self.grid)
            # done!
        return
1091432
def handle_import(self, name, compilation, rule):
        
        original_path = PurePath(name)

        search_exts = list(compilation.compiler.dynamic_extensions)
        if original_path.suffix and original_path.suffix in search_exts:
            basename = original_path.stem
        else:
            basename = original_path.name

        if original_path.is_absolute():
            # Remove the beginning slash
            search_path = original_path.relative_to('/').parent
        elif rule.source_file.origin:
            search_path = rule.source_file.origin
            if original_path.parent:
                search_path = os.path.normpath(str(search_path / original_path.parent))
        else:
            search_path = original_path.parent

        for prefix, suffix in product(('_', ''), search_exts):
            filename = PurePath(prefix + basename + suffix)

            full_filename, storage = get_file_and_storage(str(search_path / filename))

            if full_filename:
                with storage.open(full_filename) as f:
                    return SourceFile.from_file(f, origin=search_path, relpath=filename)
361155
function handleCurrentFileChange() {
        var newFile = MainViewManager.getCurrentlyViewedFile(MainViewManager.ACTIVE_PANE);

        if (newFile) {
            var newDocument = DocumentManager.getOpenDocumentForPath(newFile.fullPath);

            if (newDocument) {
                _currentTitlePath = _shortTitleForDocument(newDocument);
            } else {
                _currentTitlePath = ProjectManager.makeProjectRelativeIfPossible(newFile.fullPath);
            }
        } else {
            _currentTitlePath = null;
        }

        // Update title text & "dirty dot" display
        _updateTitle();
    }
850907
def _get_event_handlers():
    

    import os
    import importlib

    event_handlers = {
        "on_ready": [],
        "on_resume": [],
        "on_error": [],
        "on_message": [],
        "on_socket_raw_receive": [],
        "on_socket_raw_send": [],
        "on_message_delete": [],
        "on_message_edit": [],
        "on_reaction_add": [],
        "on_reaction_remove": [],
        "on_reaction_clear": [],
        "on_channel_delete": [],
        "on_channel_create": [],
        "on_channel_update": [],
        "on_member_join": [],
        "on_member_remove": [],
        "on_member_update": [],
        "on_server_join": [],
        "on_server_remove": [],
        "on_server_update": [],
        "on_server_role_create": [],
        "on_server_role_delete": [],
        "on_server_role_update": [],
        "on_server_emojis_update": [],
        "on_server_available": [],
        "on_server_unavailable": [],
        "on_voice_state_update": [],
        "on_member_ban": [],
        "on_member_unban": [],
        "on_typing": [],
        "on_group_join": [],
        "on_group_remove": []
    }

    # Iterate through module folders
    database_dir = "{}/modules".format(
        os.path.dirname(os.path.realpath(__file__)))
    for module_name in os.listdir(database_dir):
        module_dir = "{}/{}".format(database_dir, module_name)

        # Iterate through files in module
        if os.path.isdir(module_dir) and not module_name.startswith("_"):
            # Add all defined event handlers in module files
            module_event_handlers = os.listdir(module_dir)

            for event_handler in event_handlers.keys():
                if "{}.py".format(event_handler) in module_event_handlers:
                    import_name = ".discord_modis.modules.{}.{}".format(
                        module_name, event_handler)
                    logger.debug("Found event handler {}".format(import_name[23:]))

                    try:
                        event_handlers[event_handler].append(
                            importlib.import_module(import_name, "modis"))
                    except Exception as e:
                        # Log errors in modules
                        logger.exception(e)

    return event_handlers
265416
function preprocessInputText(inputText, currentDirectory) {
  var processDirectory = process.cwd(),
      importedFilePaths = [];

  // If the file name is an absolute path, returns it normailzed. If it is
  // a relative path starting with "./" or "../", appends it to the path
  // of the parent file, which the specified file is being expanded to.
  // Otherwise the relative path is  appended to the current directory.
  function completeFilePath(fileName, currentDirectory) {
    var directory;
    if (!path.isAbsolute(fileName)) {
      fileName = fileName.replace(/\\/g, '/');
      if (fileName.indexOf('./') === 0 ||
          fileName.indexOf('../') === 0) {
        directory = currentDirectory;
      } else {
        directory = processDirectory;
      }
      fileName = path.join(directory, fileName);
    }
    return path.resolve(path.normalize(fileName));
  }

  function expandFileImports(inputText, currentDirectory) {
    return inputText.replace(/#import: *(.*)/g, function (all, fileName) {
      fileName = completeFilePath(fileName, currentDirectory);
      if (importedFilePaths.indexOf(fileName) >= 0) {
        return '';
      }
      importedFilePaths.push(fileName);
      return expandFileImports(
          fs.readFileSync(fileName, {encoding: 'utf8'}),
          path.dirname(fileName));
    });
  }

  return expandFileImports(inputText, currentDirectory || processDirectory);
}
1351982
def _get_event(event_file_name):
    

    if event_file_name == STDIN_FILE_NAME:
        # If event is empty, listen to stdin for event data until EOF
        LOG.info("Reading invoke payload from stdin (you can also pass it from file with --event)")

    # click.open_file knows to open stdin when filename is '-'. This is safer than manually opening streams, and
    # accidentally closing a standard stream
    with click.open_file(event_file_name, 'r') as fp:
        return fp.read()
369718
function handleImport(results) {
    let rootDir = path.normalize(argv.root);
    let importDir = path.join(currentDir, argv.importOutput, argv.root, argv.language);
    fs.ensureDirSync(importDir);
    console.log("Writing elm-files files to:", importDir);
    results.forEach(function(result) {
        let moduleName = result[0];
        if (moduleName.indexOf(rootDir) === 0) {
            moduleName = moduleName.substr(rootDir.length)
        }
        let filePath = path.join(importDir, moduleName + ".elm");
        fs.ensureDirSync(path.dirname(filePath));
        fs.writeFileSync(filePath, result[1]);
        console.log("└── Finished writing:", filePath);
    });
    console.log("Completed");
}
759567
function _handleListEvents() {
        $dropdown
            .on("click", "a", function () {
                var $link = $(this),
                    id    = $link.attr("id"),
                    path  = $link.data("path");

                if (path) {
                    ProjectManager.openProject(path)
                        .fail(function () {
                            // Remove the project from the list only if it does not exist on disk
                            var recentProjects = getRecentProjects(),
                                index = recentProjects.indexOf(path);
                            if (index !== -1) {
                                FileSystem.resolve(path, function (err, item) {
                                    if (err) {
                                        recentProjects.splice(index, 1);
                                    }
                                });
                            }
                        });
                    closeDropdown();

                } else if (id === "open-folder-link") {
                    CommandManager.execute(Commands.FILE_OPEN_FOLDER);
                }

            })
            .on("mouseenter", "a", function () {
                if ($dropdownItem) {
                    $dropdownItem.removeClass("selected");
                }
                $dropdownItem = $(this).addClass("selected");

                if ($dropdownItem.hasClass("recent-folder-link")) {
                    // Note: we can't depend on the event here because this can be triggered
                    // manually from checkHovers().
                    addDeleteButton($(this));
                }
            })
            .on("mouseleave", "a", function () {
                var $link = $(this).removeClass("selected");

                if ($link.get(0) === $dropdownItem.get(0)) {
                    $dropdownItem = null;
                }
                if ($link.hasClass("recent-folder-link")) {
                    removeDeleteButton();
                }
            });
    }
368749
function processFile(idx, count, filename, data, parsedDeclarations, pluggable) {
  const declarations = parsedDeclarations.files[filename];
  // Inject dependent declaration extraction to last file
  const dependentDeclarations = idx === count - 1 ? parsedDeclarations.dependentDeclarations : [];
  const variables = { global: {} };

  const globalDeclarationResultHandler = (declaration, value, sassValue) => {
    if(!variables.global[declaration.declaration]) {
      variables.global[declaration.declaration] = [];
    }
    const variableValue = pluggable.run(Pluggable.POST_VALUE, { value, sassValue }).value;
    variables.global[declaration.declaration].push({ declaration, value: variableValue });
  }

  const fileId = getFileId(filename);
  const injection = injectExtractionFunctions(fileId, declarations, dependentDeclarations, { globalDeclarationResultHandler });
  const injectedData = `${data}\n\n${injection.injectedData}`;
  const injectedFunctions = injection.injectedFunctions;

  return {
    fileId,
    declarations,
    variables,
    injectedData,
    injectedFunctions,
  };
}
241910
async function importCustomSelectorsFromJSFile(from) {
	const object = await import(path.resolve(from));

	return importCustomSelectorsFromObject(object);
}
1303095
def event_handler(self, event_type, src_path):
        
        filename = os.path.relpath(src_path, self.searchpath)
        if self.should_handle(event_type, src_path):
            print("%s %s" % (event_type, filename))
            if self.site.is_static(filename):
                files = self.site.get_dependencies(filename)
                self.site.copy_static(files)
            else:
                templates = self.site.get_dependencies(filename)
                self.site.render_templates(templates)
1325758
function Importer(opts) {
  var self = this;
  opts = opts || {};
  EventEmitter.call(this);
  this.cwd = opts.cwd ? path.resolve(opts.cwd) : process.cwd();
  this.file = opts.file ? path.resolve(opts.cwd, opts.file) : this.cwd;
  this.data = opts.data;
  this.includePaths = opts.includePaths || [];

  // Map all include paths to configured working directory:
  this.includePaths = this.includePaths.map(function(includePath) {
    return path.resolve(self.cwd, includePath);
  });
}
533278
function registerInputBlurHandler(inputEl, fileId) {
        inheritedInternalApi.getDisposeSupport().attach(inputEl, "blur", function() {
            handleNameUpdate(inputEl, fileId);
        });
    }
309938
def _per_file_event_handler(self):
        
        file_event_handler = PatternMatchingEventHandler()
        file_event_handler.on_created = self._on_file_created
        file_event_handler.on_modified = self._on_file_modified
        file_event_handler.on_moved = self._on_file_moved
        file_event_handler._patterns = [
            os.path.join(self._watch_dir, os.path.normpath('*'))]
        # Ignore hidden files/folders and output.log because we stream it specially
        file_event_handler._ignore_patterns = [
            '*/.*',
            '*.tmp',
            os.path.join(self._run.dir, OUTPUT_FNAME)
        ]
        for glob in self._api.settings("ignore_globs"):
            file_event_handler._ignore_patterns.append(
                os.path.join(self._run.dir, glob))

        return file_event_handler