/*
Lazily initialize the readme document, reading it from README file inside the jar
328270
public static void initReadme() {
        try {
            InputStream readmeStream = JavadocFixTool.class.getResourceAsStream("/README");
            if (readmeStream != null) {
                BufferedReader readmeReader = new BufferedReader(new InputStreamReader(readmeStream));
                StringBuilder readmeBuilder = new StringBuilder();
                String s;
                while ((s = readmeReader.readLine()) != null) {
                    readmeBuilder.append(s);
                    readmeBuilder.append("\n");
                }
                readme = readmeBuilder.toString();
            }
        } catch (IOException ignore) {} // Ignore exception - readme not initialized
    }
1082940
private Document loadDocument(String file) {
		Document doc = null;
		URL url = null;
		File f = new File(file);
		if (f.exists()) {
			try {
				url = f.toURI().toURL();
			} catch (MalformedURLException e) {
				throw new ConfigurationException("Unable to load " + file, e);
			}
		}
		if (url == null) {
			url = ClassLoader.getSystemResource(file);
		}
		InputStream is = null;
		if (url == null) {
			if (errorIfMissing) {
				throw new ConfigurationException("Could not open files of the name " + file);
			} else {
				LOG.info("Unable to locate configuration files of the name " + file + ", skipping");
				return doc;
			}
		}
		try {
			is = url.openStream();
			InputSource in = new InputSource(is);
			in.setSystemId(url.toString());
			doc = DomHelper.parse(in, dtdMappings);
		} catch (Exception e) {
			throw new ConfigurationException("Unable to load " + file, e);
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				LOG.error("Unable to close input stream", e);
			}
		}
		if (doc != null) {
			LOG.debug("Wallmod configuration parsed");
		}
		return doc;
	}
346686
function parseReadme(book) {
    var logger = book.getLogger();

    return parseStructureFile(book, 'readme')
    .spread(function(file, result) {
        if (!file) {
            throw new error.FileNotFoundError({ filename: 'README' });
        }

        logger.debug.ln('readme found at', file.getPath());

        var readme = Readme.create(file, result);
        return book.set('readme', readme);
    });
}
1312007
private final void init() {
        InputStream in = null;

        try {
            URL url =
                this.getClass()
                    .getClassLoader()
                    .getResource("padawan.conf.xml");

            if (url != null) {
                URLConnection conn = url.openConnection();
                in = conn.getInputStream();

                long newModified = conn.getLastModified();

                if ((lastModified != newModified) && (newModified != 0)) {
                    lastModified = newModified;
                    Document xmlDoc =
                        CDocumentBuilderFactory.newParser()
                                               .newDocumentBuilder()
                                               .parse(in);
                    parseDocument(xmlDoc);
                }
            }
        } catch (Exception ignore) {
            ignore.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }
419222
private synchronized void lazyInit(HttpServletRequest request) throws IOException {
        List<File> files;
        URL url;
        long lastModified;
        long now;
        Resolver resolver;
        Node localhost;
        FileNode file;
        Object[] tmp;

        resolver = application.resolver;
        if (engine != null && resolver.isLife()) {
            for (Node node : reloadFiles) {
                lastModified = node.getLastModified();
                if (lastModified > loaded) {
                    now = System.currentTimeMillis();
                    if (lastModified > now) {
                        // fail to avoid repeated re-init
                        throw new IOException(node.getUri() + " has lastModifiedDate in the future: "
                                + new Date(lastModified) + "(now: " + new Date(now) + ")");
                    }
                    LOG.info("reloading jasmin for application '" + application.getContextPath() + "' - changed file: " + node);
                    engine = null;
                    resolver.reset();
                }
            }
        }
        if (engine == null) {
            url = new URL(request.getRequestURL().toString());
            try {
                localhost = resolver.getWorld().node(new URI(url.getProtocol(), null, url.getHost(), url.getPort(), "", null, null));
            } catch (URISyntaxException e) {
                throw new IllegalStateException(e);
            }
            tmp = application.createEngine(docroot, localhost);
            engine = (Engine) tmp[0];
            LOG.info("started engine, initial url=" + url);
            for (Module module : engine.repository.modules()) {
                files = module.files();
                if (files.size() > 2) {
                    LOG.warn("deprecated: module '" + module.getName() + "' contains more than 2 file: " + files);
                }
                for (File f : files) {
                    if (f.getNormal() instanceof HttpNode) {
                        LOG.warn("deprecated: module '" + module.getName() + "' uses base LOCALHOST: " + f.getNormal().getUri());
                    }
                }
            }
            if (resolver.isLife()) {
                reloadFiles = (List<Node>) tmp[1];
                file = resolver.getLiveXml();
                if (file != null) {
                    reloadFiles.add(file);
                }
                LOG.info("reload if one of these " + reloadFiles.size() + " files is modified: ");
                for (Node node : reloadFiles) {
                    LOG.info("  " + node.getUri());
                }
                loaded = System.currentTimeMillis();
            }
            if (engine == null) {
                throw new IllegalStateException();
            }
        }
    }
919942
function pdfViewInitialize() {
    var pdfRenderingQueue = new PDFRenderingQueue();
    pdfRenderingQueue.onIdle = this.cleanup.bind(this);
    this.pdfRenderingQueue = pdfRenderingQueue;

    var pdfLinkService = new PDFLinkService();
    this.pdfLinkService = pdfLinkService;

    var container = document.getElementById('viewerContainer');
    var viewer = document.getElementById('viewer');
    this.pdfViewer = new PDFViewer({
      container: container,
      viewer: viewer,
      renderingQueue: pdfRenderingQueue,
      linkService: pdfLinkService
    });
    pdfRenderingQueue.setViewer(this.pdfViewer);
    pdfLinkService.setViewer(this.pdfViewer);

    var thumbnailContainer = document.getElementById('thumbnailView');
    this.pdfThumbnailViewer = new PDFThumbnailViewer({
      container: thumbnailContainer,
      renderingQueue: pdfRenderingQueue,
      linkService: pdfLinkService
    });
    pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer);

    Preferences.initialize();

    this.pdfHistory = new PDFHistory({
      linkService: pdfLinkService
    });
    pdfLinkService.setHistory(this.pdfHistory);

    this.findController = new PDFFindController({
      pdfViewer: this.pdfViewer,
      integratedFind: this.supportsIntegratedFind
    });
    this.pdfViewer.setFindController(this.findController);

    this.findBar = new PDFFindBar({
      bar: document.getElementById('findbar'),
      toggleButton: document.getElementById('viewFind'),
      findField: document.getElementById('findInput'),
      highlightAllCheckbox: document.getElementById('findHighlightAll'),
      caseSensitiveCheckbox: document.getElementById('findMatchCase'),
      findMsg: document.getElementById('findMsg'),
      findStatusIcon: document.getElementById('findStatusIcon'),
      findPreviousButton: document.getElementById('findPrevious'),
      findNextButton: document.getElementById('findNext'),
      findController: this.findController
    });

    this.findController.setFindBar(this.findBar);

    HandTool.initialize({
      container: container,
      toggleHandTool: document.getElementById('toggleHandTool')
    });

    this.pdfDocumentProperties = new PDFDocumentProperties({
      overlayName: 'documentPropertiesOverlay',
      closeButton: document.getElementById('documentPropertiesClose'),
      fields: {
        'fileName': document.getElementById('fileNameField'),
        'fileSize': document.getElementById('fileSizeField'),
        'title': document.getElementById('titleField'),
        'author': document.getElementById('authorField'),
        'subject': document.getElementById('subjectField'),
        'keywords': document.getElementById('keywordsField'),
        'creationDate': document.getElementById('creationDateField'),
        'modificationDate': document.getElementById('modificationDateField'),
        'creator': document.getElementById('creatorField'),
        'producer': document.getElementById('producerField'),
        'version': document.getElementById('versionField'),
        'pageCount': document.getElementById('pageCountField')
      }
    });

    SecondaryToolbar.initialize({
      toolbar: document.getElementById('secondaryToolbar'),
      toggleButton: document.getElementById('secondaryToolbarToggle'),
      presentationModeButton:
        document.getElementById('secondaryPresentationMode'),
      openFile: document.getElementById('secondaryOpenFile'),
      print: document.getElementById('secondaryPrint'),
      download: document.getElementById('secondaryDownload'),
      viewBookmark: document.getElementById('secondaryViewBookmark'),
      firstPage: document.getElementById('firstPage'),
      lastPage: document.getElementById('lastPage'),
      pageRotateCw: document.getElementById('pageRotateCw'),
      pageRotateCcw: document.getElementById('pageRotateCcw'),
      documentPropertiesButton: document.getElementById('documentProperties')
    });

    if (this.supportsFullscreen) {
      var toolbar = SecondaryToolbar;
      this.pdfPresentationMode = new PDFPresentationMode({
        container: container,
        viewer: viewer,
        pdfThumbnailViewer: this.pdfThumbnailViewer,
        contextMenuItems: [
          { element: document.getElementById('contextFirstPage'),
            handler: toolbar.firstPageClick.bind(toolbar) },
          { element: document.getElementById('contextLastPage'),
            handler: toolbar.lastPageClick.bind(toolbar) },
          { element: document.getElementById('contextPageRotateCw'),
            handler: toolbar.pageRotateCwClick.bind(toolbar) },
          { element: document.getElementById('contextPageRotateCcw'),
            handler: toolbar.pageRotateCcwClick.bind(toolbar) }
        ]
      });
    }

    PasswordPrompt.initialize({
      overlayName: 'passwordOverlay',
      passwordField: document.getElementById('password'),
      passwordText: document.getElementById('passwordText'),
      passwordSubmit: document.getElementById('passwordSubmit'),
      passwordCancel: document.getElementById('passwordCancel')
    });

    var self = this;
    var initializedPromise = Promise.all([
      Preferences.get('enableWebGL').then(function resolved(value) {
        PDFJS.disableWebGL = !value;
      }),
      Preferences.get('sidebarViewOnLoad').then(function resolved(value) {
        self.preferenceSidebarViewOnLoad = value;
      }),
      Preferences.get('pdfBugEnabled').then(function resolved(value) {
        self.preferencePdfBugEnabled = value;
      }),
      Preferences.get('showPreviousViewOnLoad').then(function resolved(value) {
        self.preferenceShowPreviousViewOnLoad = value;
      }),
      Preferences.get('defaultZoomValue').then(function resolved(value) {
        self.preferenceDefaultZoomValue = value;
      }),
      Preferences.get('disableTextLayer').then(function resolved(value) {
        if (PDFJS.disableTextLayer === true) {
          return;
        }
        PDFJS.disableTextLayer = value;
      }),
      Preferences.get('disableRange').then(function resolved(value) {
        if (PDFJS.disableRange === true) {
          return;
        }
        PDFJS.disableRange = value;
      }),
      Preferences.get('disableAutoFetch').then(function resolved(value) {
        PDFJS.disableAutoFetch = value;
      }),
      Preferences.get('disableFontFace').then(function resolved(value) {
        if (PDFJS.disableFontFace === true) {
          return;
        }
        PDFJS.disableFontFace = value;
      }),
      Preferences.get('useOnlyCssZoom').then(function resolved(value) {
        PDFJS.useOnlyCssZoom = value;
      })
      // TODO move more preferences and other async stuff here
    ]).catch(function (reason) { });

    return initializedPromise.then(function () {
      PDFViewerApplication.initialized = true;
    });
  }
1020304
function initBook(rootFolder) {
    var extension = '.md';

    return fs.mkdirp(rootFolder)

    // Parse the summary and readme
    .then(function() {
        var fs = createNodeFS(rootFolder);
        var book = Book.createForFS(fs);

        return Parse.parseReadme(book)

        // Setup default readme if doesn't found one
        .fail(function() {
            var readmeFile = File.createWithFilepath('README' + extension);
            var readme = Readme.create(readmeFile);
            return book.setReadme(readme);
        });
    })
    .then(Parse.parseSummary)

    .then(function(book) {
        var logger = book.getLogger();
        var summary = book.getSummary();
        var summaryFile = summary.getFile();
        var summaryFilename = summaryFile.getPath() || ('SUMMARY' + extension);

        var articles = summary.getArticlesAsList();

        // Write pages
        return Promise.forEach(articles, function(article) {
            var articlePath = article.getPath();
            var filePath = articlePath? path.join(rootFolder, articlePath) : null;
            if (!filePath) {
                return;
            }

            return fs.assertFile(filePath, function() {
                return fs.ensureFile(filePath)
                .then(function() {
                    logger.info.ln('create', article.getPath());
                    return fs.writeFile(filePath, '# ' + article.getTitle() + '\n\n');
                });
            });
        })

        // Write summary
        .then(function() {
            var filePath = path.join(rootFolder, summaryFilename);

            return fs.ensureFile(filePath)
            .then(function() {
                logger.info.ln('create ' + path.basename(filePath));
                return fs.writeFile(filePath, summary.toText(extension));
            });
        })

        // Log end
        .then(function() {
            logger.info.ln('initialization is finished');
        });
    });
}
319530
final void initDocument(int documentNumber)
        {
                // save masked DTM document handle
                m_docHandle = documentNumber<<DOCHANDLE_SHIFT;

                // Initialize the doc -- no parent, no next-sib
                nodes.writeSlot(0,DOCUMENT_NODE,-1,-1,0);
                // wait for the first startElement to create the doc root node
                done = false;
        }
953704
@Override
	public void init() {
		int count = 10485760;
		RandomAccessFile randomAccessFile;
		String realPath = FileHandlerUtil.generateOutputFilePath(path);

		try {
			if (FileHandlerUtil.isFileAlreadyExists(realPath)) {
				randomAccessFile = new RandomAccessFile(realPath, CoreConstants.READ_WRITE);
			} else {
				randomAccessFile = new RandomAccessFile(new File(realPath), CoreConstants.READ_WRITE);
			}
			// move the cursor to the end of the file
			randomAccessFile.seek(randomAccessFile.length());

			 out = randomAccessFile.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
573405
private static synchronized void init() {
        LOGGER.trace("Reads static resources definition from [static-resources.xml]");

        final File staticResources = Latkes.getWebFile("/WEB-INF/static-resources.xml");
        if (null == staticResources || !staticResources.exists()) {
            throw new IllegalStateException("Not found static resources definition from [static-resources.xml]");
        }

        final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

        try {
            final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            final Document document = documentBuilder.parse(staticResources);
            final Element root = document.getDocumentElement();

            root.normalize();

            final StringBuilder logBuilder = new StringBuilder("Reading static files: [").append(Strings.LINE_SEPARATOR);
            final NodeList includes = root.getElementsByTagName("include");
            for (int i = 0; i < includes.getLength(); i++) {
                final Element include = (Element) includes.item(i);
                String path = include.getAttribute("path");
                final URI uri = new URI("http", "b3log.org", path, null);
                final String s = uri.toASCIIString();
                path = StringUtils.substringAfter(s, "b3log.org");

                STATIC_RESOURCE_PATHS.add(path);

                logBuilder.append("    ").append("path pattern [").append(path).append("]");
                if (i < includes.getLength() - 1) {
                    logBuilder.append(",");
                }
                logBuilder.append(Strings.LINE_SEPARATOR);
            }

            logBuilder.append("]");

            if (LOGGER.isTraceEnabled()) {
                LOGGER.debug(logBuilder.toString());
            }
        } catch (final Exception e) {
            LOGGER.log(Level.ERROR, "Reads [" + staticResources.getName() + "] failed", e);
            throw new RuntimeException(e);
        }

        final StringBuilder logBuilder = new StringBuilder("Static files: [").append(Strings.LINE_SEPARATOR);
        final Iterator<String> iterator = STATIC_RESOURCE_PATHS.iterator();
        while (iterator.hasNext()) {
            final String pattern = iterator.next();

            logBuilder.append("    ").append(pattern);
            if (iterator.hasNext()) {
                logBuilder.append(',');
            }
            logBuilder.append(Strings.LINE_SEPARATOR);
        }
        logBuilder.append("], ").append('[').append(STATIC_RESOURCE_PATHS.size()).append("] path patterns");

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(logBuilder.toString());
        }

        inited = true;
    }
222155
private void onRead0() {
        assert inWire.startUse();

        ensureCapacity();

        try {

            while (!inWire.bytes().isEmpty()) {

                try (DocumentContext dc = inWire.readingDocument()) {
                    if (!dc.isPresent())
                        return;

                    try {
                        if (YamlLogging.showServerReads())
                            logYaml(dc);
                        onRead(dc, outWire);
                        onWrite(outWire);
                    } catch (Exception e) {
                        Jvm.warn().on(getClass(), "inWire=" + inWire.getClass() + ",yaml=" + Wires.fromSizePrefixedBlobs(dc), e);
                    }
                }
            }

        } finally {
            assert inWire.endUse();
        }
    }
1173121
private Document readDocument(InputStream in, URI file) throws TransformerConfigurationException, SAXException, IOException {
        final Document document = documentBuilder.newDocument();
        if (file != null) {
            document.setDocumentURI(file.toString());
        }

        final TransformerHandler domSerializer = saxTransformerFactory.newTransformerHandler();
        domSerializer.setResult(new DOMResult(document));
        final InputSource inputSource = new InputSource(in);
        if (file != null) {
            inputSource.setSystemId(file.toString());
        }
        validator.validate(new SAXSource(inputSource), new SAXResult(domSerializer));

        return document;
    }
583202
def process_readme():
    
    with open('../../README.md', 'r') as file:
        readme = file.read()

    readme = readme.replace('# eo-learn', '# Introduction').replace('docs/source/', '')
    readme = readme.replace('**`', '**').replace('`**', '**')

    chapters = [[]]
    for line in readme.split('\n'):
        if line.strip().startswith('## '):
            chapters.append([])
        if line.startswith('<img'):
            line = '<p></p>'

        chapters[-1].append(line)

    chapters = ['\n'.join(chapter) for chapter in chapters]

    intro = '\n'.join([chapter for chapter in chapters if not (chapter.startswith('## Install') or
                                                               chapter.startswith('## Documentation'))])
    install = '\n'.join([chapter for chapter in chapters if chapter.startswith('## Install')])

    with open(os.path.join(MARKDOWNS_FOLDER, 'INTRO.md'), 'w') as file:
        file.write(intro)
    with open(os.path.join(MARKDOWNS_FOLDER, 'INSTALL.md'), 'w') as file:
        file.write(install)
856518
static Document loadDocument(Resource xmlFile) throws SAXException, IOException {
	InputStream is = null;
	try {
	    return _loadDocument(is = IOUtil.toBufferedInputStream(xmlFile.getInputStream()));
	}
	finally {
	    IOUtil.closeEL(is);
	}
    }
321401
private void importInitialLdif() throws IOException {

        if (this.initialLdif != null) {
            try (InputStream ldifStream = this.initialLdif.openStream()) {
                this.importLdif(ldifStream);
            }
        }
    }
1351232
def parse_readme():
    """"""
    # Get the long description from the relevant file
    here = os.path.abspath(os.path.dirname(__file__))
    readme_path = os.path.join(here, 'README.md')
    with codecs.open(readme_path, encoding='utf-8') as handle:
        long_description = handle.read()

    return long_description
1112085
private void initializeMimeExtensionArrays() throws OSException {
        // lazy initialization
        if (extensionMime == null || mimeExtension == null) {
            extensionMime = new HashMap<>();
            mimeExtension = new HashMap<>();

            // list all files in all directories in MIME_TYPE_FILES
            for (String dir : MIME_TYPE_FILES) {
                File d = new File(dir);
                if (d.exists() && d.isDirectory()) {
                    for (final File fileEntry : d.listFiles()) {
                        if (fileEntry.isFile() && fileEntry.canRead()) {
                            Set<String> tmpExtensions = new HashSet<>();
                            Set<String> tmpMimeTypes = new HashSet<>();
                            try {
                                String content = new String(Files.readAllBytes(fileEntry.toPath()));

                                Matcher extMatcher = MIME_TYPE_FILE_EXTENSION_PATTERN.matcher(content);
                                while (extMatcher.find()) {
                                    tmpExtensions.add(extMatcher.group(1).toLowerCase());
                                }

                                Matcher mimeMatcher = MIME_TYPE_FILE_MIME_PATTERN.matcher(content);
                                while (mimeMatcher.find()) {
                                    tmpMimeTypes.add(mimeMatcher.group(1).toLowerCase());
                                }
                            } catch (IOException ex) {
                                throw new OSException(ex);
                            }

                            // fill arrays
                            for (String ext : tmpExtensions) {
                                if (extensionMime.containsKey(ext)) {
                                    Set<String> tmp = extensionMime.get(ext);
                                    tmp.addAll(tmpMimeTypes);
                                    extensionMime.put(ext, tmp);
                                } else {
                                    extensionMime.put(ext, tmpMimeTypes);
                                }
                            }
                            for (String mime : tmpMimeTypes) {
                                if (mimeExtension.containsKey(mime)) {
                                    Set<String> tmp = mimeExtension.get(mime);
                                    tmp.addAll(tmpExtensions);
                                    mimeExtension.put(mime, tmp);
                                } else {
                                    mimeExtension.put(mime, tmpExtensions);
                                }
                            }
                        }
                    }
                }
            }
        }
    }