Runs a chain of tasks to convert a PDF to a useful booklet PDF.
509430
def convert_to_foldable(input_filename: str,
                        output_filename: str,
                        slice_horiz: int,
                        slice_vert: int,
                        overwrite: bool = False,
                        longedge: bool = False,
                        latex_paper_size: str = LATEX_PAPER_SIZE_A4) -> bool:
    
    if not os.path.isfile(input_filename):
        log.warning("Input file does not exist or is not a file")
        return False
    if not overwrite and os.path.isfile(output_filename):
        log.error("Output file exists; not authorized to overwrite (use "
                  "--overwrite if you are sure)")
        return False
    log.info("Processing {!r}", input_filename)
    with tempfile.TemporaryDirectory() as tmpdir:
        log.debug("Using temporary directory {!r}", tmpdir)
        intermediate_num = 0

        def make_intermediate() -> str:
            nonlocal intermediate_num
            intermediate_num += 1
            return os.path.join(tmpdir,
                                "intermediate_{}.pdf".format(intermediate_num))

        # Run this as a chain, rewriting input_filename at each step:
        # Slice, if necessary.
        input_filename = slice_pdf(
            input_filename=input_filename,
            output_filename=make_intermediate(),
            slice_horiz=slice_horiz,
            slice_vert=slice_vert
        )
        # Make the final n-up
        input_filename = booklet_nup_pdf(
            input_filename=input_filename,
            output_filename=make_intermediate(),
            latex_paper_size=latex_paper_size
        )
        # Rotate?
        if longedge:
            input_filename = rotate_even_pages_180(
                input_filename=input_filename,
                output_filename=make_intermediate(),
            )
        # Done.
        log.info("Writing to {!r}", output_filename)
        shutil.move(input_filename, output_filename)
    return True
1014944
def run(self):
        ''''''
        for tpl in self.templates:
            for provider in tpl.providers:
                provider.provide()
1328295
def show(self):
        """"""
        try:
            if platform.system().lower().startswith('darwin'):
                subprocess.call(['open', self.pdf])
            elif os.name == 'nt':
                os.startfile(self.pdf)
            elif os.name == 'posix':
                subprocess.call(['xdg-open', self.pdf])
            else:
                raise IOError("")
        except IOError:
            log.info("Unable to open the pdf. Try opening it manually:")
            log.info(self.pdf)
605525
def run(self):
        '''
        
        '''
        # Print documentation only
        if self.opts.get('doc', False):
            self.print_docs()
        else:
            return self._run_runner()
488438
function (pdf_file, cb) {
            var quality = 300;
            if (options.hasOwnProperty('quality') && options.quality) {
              quality = options.quality;
            }
            convert(pdf_file.file_path, quality, function (err, tif_path) {
              var zeroBasedNumPages = num_pages-1;
              self.emit('log', 'converted page to intermediate tiff file, page '+ index+ ' (0-based indexing) of '+ zeroBasedNumPages);
              if (err) { return cb(err); }
              var ocr_flags = [
                '-psm 6'
              ];
              if (options.ocr_flags) {
                ocr_flags = options.ocr_flags;
              }
              ocr(tif_path, ocr_flags, function (err, extract) {
                fs.unlink(tif_path, function (tif_cleanup_err, reply) {
                  if (tif_cleanup_err) {
                    err += ', error removing temporary tif file: "'+tif_cleanup_err+'"';
                  }
                  if (err) { return cb(err); }
                  var page_number = index+1
                  self.emit('log', 'raw ocr: page ' + index + ' (0-based indexing) of ' +zeroBasedNumPages + ' complete');
                  single_page_pdf_file_paths.push(pdf_file.file_path);
                  self.emit('page', { hash: hash, text: extract, index: index, num_pages: num_pages, pdf_path: pdf_path, single_page_pdf_path: pdf_file.file_path});
                  text_pages.push(extract);
                  index++;
                  cb();
                });
              });
            });
          }
1291617
def process(self, document):
        """"""
        self.logger.info("Processing group of tasks (parallel=%s)", self.get_parallel_mode())
        self.pipeline.data.env_list[2] = {}

        output, shells = [], []
        result = Adapter({'success': True, 'output': []})
        for task_entry in document:
            key, entry = list(task_entry.items())[0]

            if (not self.parallel or key == 'env') and len(shells) > 0:
                result = Adapter(self.process_shells(shells))
                output += result.output
                shells = []
                if not result.success:
                    break

            if key == 'env':
                self.pipeline.data.env_list[2].update(entry)

            elif key in ['shell', 'docker(container)', 'docker(image)', 'python',
                         'packer', 'ansible(simple)']:
                self.prepare_shell_data(shells, key, entry)

        if result.success:
            result = Adapter(self.process_shells(shells))
            output += result.output

        self.event.delegate(result.success)
        return {'success': result.success, 'output': output}
1248170
function process(doc, cb) {
    freeze()
    assertParser('process', processor.Parser)
    assertCompiler('process', processor.Compiler)

    if (!cb) {
      return new Promise(executor)
    }

    executor(null, cb)

    function executor(resolve, reject) {
      var file = vfile(doc)

      pipeline.run(processor, {file: file}, done)

      function done(err) {
        if (err) {
          reject(err)
        } else if (resolve) {
          resolve(file)
        } else {
          cb(null, file)
        }
      }
    }
  }
596140
def main(argv: Optional[Sequence[str]] = None) -> None:
    """"""
    parser = ArgumentParser(description="Convert Jupyter Notebook exams to PDFs")
    parser.add_argument(
        "--exam",
        type=int,
        required=True,
        help="Exam number to convert",
        dest="exam_num",
    )
    parser.add_argument(
        "--time", type=str, required=True, help="Time of exam to convert"
    )
    parser.add_argument(
        "--date", type=str, required=True, help="The date the exam will take place"
    )
    args = parser.parse_args(argv)
    process(args.exam_num, args.time, args.date)
1090807
def batch_generate_pdfs(submission_batch_data, opts = {})
      data, _status_code, _headers = batch_generate_pdfs_with_http_info(submission_batch_data, opts)
      data
    end
205383
function (data, files, cb) {
    var outDir = data.outDir;
    var zipfilename = Mustache.render(data.template, data);
    var outfile = path.join(outDir, zipfilename);

    // store the output zip file name on the task data
    data.outfile = outfile;

    var zipfile = zip.create(outfile);

    async.each(
      files,

      function (file, next) {
        var src = file.src[0];
        var dest = file.dest || src;

        if (isFile(src)) {
          grunt.log.writeln('adding file ' + src + ' to package as ' + dest);
          zipfile.addFile(src, dest, next);
        }
        // screen out the '.' directory to avoid a spurious entry
        else if (isDirectory(src) && dest !== '.') {
          grunt.log.writeln('adding directory ' + src + ' to package as ' + dest);
          zipfile.addDirectory(dest, next);
        }
        else {
          next();
        }
      },

      function (err) {
        if (err) {
          grunt.fatal(err.message);
        }
        else {
          grunt.log.writeln('\npackage written to:\n' + outfile);
          zipfile.writeToFile(cb);
        }
      }
    );
  }
289883
function forEachItem(pdf, handler) {
  var pageNumber = 0;
  for (var p in pdf.formImage.Pages) {
    var page = pdf.formImage.Pages[p];
    var number = ++pageNumber;
    handler(null, {
      page: number,
      width: pdf.formImage.Width,
      height: pdf.formImage.Pages[number - 1].Height
    });
    for (var t in page.Texts) {
      var item = page.Texts[t];
      item.text = decodeURIComponent(item.R[0].T);
      handler(null, item);
    }
  }
  handler();
}
931140
def make_reader_task(self, stream, callback):
        

        return self.loop.create_task(self.executor_wrapper(background_reader, stream, self.loop, callback))
539058
private void prepare() throws IOException, DocumentException, PrintingException {
		if (baos == null) {
			baos = new ByteArrayOutputStream(); // let it grow as much as needed
		}
		baos.reset();
		boolean resize = false;
		if (page.getConstraint().getWidth() == 0 || page.getConstraint().getHeight() == 0) {
			resize = true;
		}
		// Create a document in the requested ISO scale.
		Document document = new Document(page.getBounds(), 0, 0, 0, 0);
		PdfWriter writer;
		writer = PdfWriter.getInstance(document, baos);

		// Render in correct colors for transparent rasters
		writer.setRgbTransparencyBlending(true);

		// The mapView is not scaled to the document, we assume the mapView
		// has the right ratio.

		// Write document title and metadata
		document.open();
		PdfContext context = new PdfContext(writer);
		context.initSize(page.getBounds());
		// first pass of all children to calculate size
		page.calculateSize(context);
		if (resize) {
			// we now know the bounds of the document
			// round 'm up and restart with a new document
			int width = (int) Math.ceil(page.getBounds().getWidth());
			int height = (int) Math.ceil(page.getBounds().getHeight());
			page.getConstraint().setWidth(width);
			page.getConstraint().setHeight(height);

			document = new Document(new Rectangle(width, height), 0, 0, 0, 0);
			writer = PdfWriter.getInstance(document, baos);
			// Render in correct colors for transparent rasters
			writer.setRgbTransparencyBlending(true);

			document.open();
			baos.reset();
			context = new PdfContext(writer);
			context.initSize(page.getBounds());
		}
		// int compressionLevel = writer.getCompressionLevel(); // For testing
		// writer.setCompressionLevel(0);

		// Actual drawing
		document.addTitle("Geomajas");
		// second pass to layout
		page.layout(context);
		// finally render (uses baos)
		page.render(context);

		document.add(context.getImage());
		// Now close the document
		document.close();
	}
1268596
def assemble(self, blueprint, quota):
        """"""

        # Reset the blueprint
        blueprint.reset()

        # Assemble the documents
        documents = []
        for i in range(0, int(quota)):
            documents.append(blueprint.assemble())

        return documents
488953
def run(args):
    
    kwargs = vars(args)

    if 'func' in kwargs:
        del kwargs['func']

    project_path = kwargs.pop('project_path')
    config = configure(project_path, kwargs.get('config_file'))

    output_dir = kwargs.pop('output_dir', None) or generate_output_path(args, project_path)

    stats_handler.init_stats(output_dir, config)

    topic = args.publisher_channel or uuid.uuid4().hex
    print("External publishing topic is %s" % topic)

    start_hq(output_dir, config, topic, **kwargs)

    if not args.no_results:
        process_results(output_dir, config)

    copy_config(project_path, output_dir)
    print('done.\n')
938797
def do_links(doc1, doc2, from_page = -1, to_page = -1, start_at = -1):
    ''''''
    #--------------------------------------------------------------------------
    # define skeletons for /Annots object texts
    #--------------------------------------------------------------------------
    annot_goto ='''<</Dest[%i 0 R /XYZ %g %g 0]/Rect[%s]/Subtype/Link>>'''

    annot_gotor = '''<</A<</D[%i /XYZ %g %g 0]/F<</F(%s)/UF(%s)/Type/Filespec
    >>/S/GoToR>>/Rect[%s]/Subtype/Link>>'''

    annot_gotor_n = "<</A<</D(%s)/F(%s)/S/GoToR>>/Rect[%s]/Subtype/Link>>"

    annot_launch = '''<</A<</F<</F(%s)/UF(%s)/Type/Filespec>>/S/Launch
    >>/Rect[%s]/Subtype/Link>>'''

    annot_uri = '''<</A<</S/URI/URI(%s)/Type/Action>>/Rect[%s]/Subtype/Link>>'''

    #--------------------------------------------------------------------------
    # internal function to create the actual "/Annots" object string
    #--------------------------------------------------------------------------
    def cre_annot(lnk, xref_dst, list_src, height):
        '''Create annotation object string for a passed-in link.'''

        # "from" rectangle is always there. Note: y-coords are from bottom!

        r = lnk["from"]
        rect = "%g %g %g %g" % (r.x0, height - r.y0, r.x1, height - r.y1)
        if lnk["kind"] == LINK_GOTO:
            txt = annot_goto
            idx = list_src.index(lnk["page"])
            annot = txt % (xref_dst[idx], lnk["to"].x,
                           lnk["to"].y, rect)
        elif lnk["kind"] == LINK_GOTOR:
            if lnk["page"] >= 0:
                txt = annot_gotor
                pnt = lnk.get("to", Point(0, 0))          # destination point
                if type(pnt) is not Point:
                    pnt = Point(0, 0)
                annot = txt % (lnk["page"], pnt.x, pnt.y,
                           lnk["file"], lnk["file"], rect)
            else:
                txt = annot_gotor_n
                to = getPDFstr(lnk["to"])
                to = to[1:-1]
                f = lnk["file"]
                annot = txt % (to, f, rect)

        elif lnk["kind"] == LINK_LAUNCH:
            txt = annot_launch
            annot = txt % (lnk["file"], lnk["file"], rect)
        elif lnk["kind"] == LINK_URI:
            txt = annot_uri
            annot = txt % (lnk["uri"], rect)
        else:
            annot = ""

        return annot
    #--------------------------------------------------------------------------

    # validate & normalize parameters
    if from_page < 0:
        fp = 0
    elif from_page >= doc2.pageCount:
        from_page = doc2.pageCount - 1
    else:
        fp = from_page

    if to_page < 0 or to_page >= doc2.pageCount:
        tp = doc2.pageCount - 1
    else:
        tp = to_page

    if start_at < 0:
        raise ValueError("do_links: 'start_at' arg must be >= 0")
    sa = start_at

    incr = 1 if fp <= tp else -1            # page range could be reversed
    # lists of source / destination page numbers
    list_src = list(range(fp, tp + incr, incr))
    list_dst = [sa + i for i in range(len(list_src))]
    # lists of source / destination page xref numbers
    xref_src = []
    xref_dst = []
    for i in range(len(list_src)):
        p_src = list_src[i]
        p_dst = list_dst[i]
        old_xref = doc2._getPageObjNumber(p_src)[0]
        new_xref = doc1._getPageObjNumber(p_dst)[0]
        xref_src.append(old_xref)
        xref_dst.append(new_xref)

    # create /Annots per copied page in destination PDF
    for i in range(len(xref_src)):
        page_src = doc2[list_src[i]]
        links = page_src.getLinks()
        if len(links) == 0:
            page_src = None
            continue
        height = page_src.bound().y1
        p_annots = ""
        page_dst = doc1[list_dst[i]]
        link_tab = []
        for l in links:
            if l["kind"] == LINK_GOTO and (l["page"] not in list_src):
                continue          # target not in copied pages
            annot_text = cre_annot(l, xref_dst, list_src, height)
            if not annot_text:
                print("cannot create /Annot for kind: " + str(l["kind"]))
            else:
                link_tab.append(annot_text)
        if len(link_tab) > 0:
            page_dst._addAnnot_FromString(link_tab)
        page_dst = None
        page_src = None
    return
450588
def execute
            latex = compile_latex
            Dir.mktmpdir do | dir |
                @pass_count = 0
                @log        = ''
                success     = false
                while log_suggests_rerunning? && @pass_count < 5
                    @pass_count += 1
                    success = execute_xelatex(latex,dir)
                end
                pdf_file = Pathname.new(dir).join( "output.pdf" )
                if success && pdf_file.exist?
                    yield pdf_file
                else
                    errors = @log.scan(/\*\!\s(.*?)\n\s*\n/m).map{|e| e.first.gsub(/\n/,'') }.join("; ")
                    STDERR.puts @log, errors if ErbLatex.config.verbose_logs
                    raise LatexError.new( errors.empty? ? "xelatex compile error" : errors, @log )
                end
            end
        end