text:
#include "poppler-page.h"
#include "poppler-page-transition.h"

#include "poppler-document-private.h"
#include "poppler-page-private.h"
#include "poppler-private.h"

#include "TextOutputDev.h"

#include <memory>

using namespace poppler;

page_private::page_private(document_private *_doc, int _index)
    : doc(_doc)
    , page(doc->doc->getCatalog()->getPage(_index + 1))
    , index(_index)
    , transition(0)
{
}

page_private::~page_private()
{
    delete transition;
}

/**
 \class poppler::page poppler-page.h "poppler/cpp/poppler-page.h"

 A page in a PDF %document.
 */

/**
 \enum poppler::page::orientation_enum

 The possible orientation of a page.
*/

/**
 \enum poppler::page::search_direction_enum

 The direction/action to follow when performing a text search.
*/

/**
 \enum poppler::page::text_layout_enum

 A layout of the text of a page.
*/

page::page(document_private *doc, int index)
    : d(new page_private(doc, index))
{
}

/**
 Destructor.
 */
page::~page()
{
    delete d;
}

/**
 \returns the orientation of the page
 */
page::orientation_enum page::orientation() const
{
    const int rotation = d->page->getRotate();
    switch (rotation) {
    case 90:
        return landscape;
        break;
    case 180:
        return upside_down;
        break;
    case 270:
        return seascape;
        break;
    default:
        return portrait;
    }
}

/**
 The eventual duration the page can be hinted to be shown in a presentation.

 If this value is positive (usually different than -1) then a PDF viewer, when
 showing the page in a presentation, should show the page for at most for this
 number of seconds, and then switch to the next page (if any). Note this is
 purely a presentation attribute, it has no influence on the behaviour.

 \returns the duration time (in seconds) of the page
 */
double page::duration() const
{
    return d->page->getDuration();
}

/**
 Returns the size of one rect of the page.

 \returns the size of the specified page rect
 */
rectf page::page_rect(page_box_enum box) const
{
    PDFRectangle *r = 0;
    switch (box) {
    case media_box:
        r = d->page->getMediaBox();
        break;
    case crop_box:
        r = d->page->getCropBox();
        break;
    case bleed_box:
        r = d->page->getBleedBox();
        break;
    case trim_box:
        r = d->page->getTrimBox();
        break;
    case art_box:
        r = d->page->getArtBox();
        break;
    }
    if (r) {
        return detail::pdfrectangle_to_rectf(*r);
    }
    return rectf();
}

/**
 \returns the label of the page, if any
 */
ustring page::label() const
{
    GooString goo;
    if (!d->doc->doc->getCatalog()->indexToLabel(d->index, &goo)) {
        return ustring();
    }

    return detail::unicode_GooString_to_ustring(&goo);
}

/**
 The transition from this page to the next one.

 If it is set, then a PDF viewer in a presentation should perform the
 specified transition effect when switching from this page to the next one.

 \returns the transition effect for the switch to the next page, if any
 */
page_transition* page::transition() const
{
    if (!d->transition) {
        Object o;
        if (d->page->getTrans(&o)->isDict()) {
            d->transition = new page_transition(&o);
        }
        o.free();
    }
    return d->transition;
}

/**
 Search the page for some text.

 \param text the text to search
 \param[in,out] r the area where to start search, which will be set to the area
                  of the match (if any)
 \param direction in which direction search for text
 \param case_sensitivity whether search in a case sensitive way
 \param rotation the rotation assumed for the page
 */
bool page::search(const ustring &text, rectf &r, search_direction_enum direction,
                  case_sensitivity_enum case_sensitivity, rotation_enum rotation) const
{
    const size_t len = text.length();
    std::vector<Unicode> u(len);
    for (size_t i = 0; i < len; ++i) {
        u[i] = text[i];
    }

    const GBool sCase = case_sensitivity == case_sensitive ? gTrue : gFalse;
    const int rotation_value = (int)rotation * 90;

    bool found = false;
    double rect_left = r.left();
    double rect_top = r.top();
    double rect_right = r.right();
    double rect_bottom = r.bottom();

    TextOutputDev td(NULL, gTrue, 0, gFalse, gFalse);
    d->doc->doc->displayPage(&td, d->index + 1, 72, 72, rotation_value, false, true, false);
    TextPage *text_page = td.takeText();

    switch (direction) {
    case search_from_top:
        found = text_page->findText(&u[0], len,
                    gTrue, gTrue, gFalse, gFalse, sCase, gFalse, gFalse,
                    &rect_left, &rect_top, &rect_right, &rect_bottom);
        break;
    case search_next_result:
        found = text_page->findText(&u[0], len,
                    gFalse, gTrue, gTrue, gFalse, sCase, gFalse, gFalse,
                    &rect_left, &rect_top, &rect_right, &rect_bottom);
        break;
    case search_previous_result:
        found = text_page->findText(&u[0], len,
                    gFalse, gTrue, gTrue, gFalse, sCase, gTrue, gFalse,
                    &rect_left, &rect_top, &rect_right, &rect_bottom);
        break;
    }

    text_page->decRefCnt();
    r.set_left(rect_left);
    r.set_top(rect_top);
    r.set_right(rect_right);
    r.set_bottom(rect_bottom);

    return found;
}

/**
 Returns the text in the page, in its physical layout.

 \param r if not empty, it will be extracted the text in it; otherwise, the
          text of the whole page

 \returns the text of the page in the specified rect or in the whole page
 */
ustring page::text(const rectf &r) const
{
    return text(r, physical_layout);
}

/**
 Returns the text in the page.

 \param rect if not empty, it will be extracted the text in it; otherwise, the
             text of the whole page
 \param layout_mode the layout of the text

 \returns the text of the page in the specified rect or in the whole page

 \since 0.16
 */
ustring page::text(const rectf &r, text_layout_enum layout_mode) const
{
    std::auto_ptr<GooString> s;
    const GBool use_raw_order = (layout_mode == raw_order_layout);
    TextOutputDev td(0, gFalse, 0, use_raw_order, gFalse);
    d->doc->doc->displayPage(&td, d->index + 1, 72, 72, 0, false, true, false);
    if (r.is_empty()) {
        const PDFRectangle *rect = d->page->getCropBox();
        s.reset(td.getText(rect->x1, rect->y1, rect->x2, rect->y2));
    } else {
        s.reset(td.getText(r.left(), r.top(), r.right(), r.bottom()));
    }
    return ustring::from_utf8(s->getCString());
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/BattleshipTest.iml" filepath="$PROJECT_DIR$/BattleshipTest.iml" />
    </modules>
  </component>
</project>

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using CoreGraphics;
using Foundation;
using UIKit;

namespace Xamarin.iOS.FileExplorer.Services.File
{
	public interface IFileSpecificationProvider
	{
		IEnumerable<string> Extensions { get; }

		UIImage GetThumbnail(NSUrl atUri, CGSize withSize);

		UIViewController GetViewControllerForItem(NSUrl atUri, NSData data, NSFileAttributes fileAttribute);
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React Test</title>
    <link href="app.css" rel="stylesheet" />


text:
package hex;

import hex.Layer.VecsInput;
import water.fvec.Vec;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.util.Random;

public class MnistCanvas extends Canvas {
  static final int PIXELS = 784, EDGE = 28;

  static Random _rand = new Random();
  static int _level = 1;
  Trainer _trainer;

  public MnistCanvas(Trainer trainer) {
    _trainer = trainer;
  }

  public JPanel init() {
    JToolBar bar = new JToolBar();
    bar.add(new JButton("refresh") {
      @Override protected void fireActionPerformed(ActionEvent event) {
        MnistCanvas.this.repaint();
      }
    });
    bar.add(new JButton("++") {
      @Override protected void fireActionPerformed(ActionEvent event) {
        _level++;
      }
    });
    bar.add(new JButton("--") {
      @Override protected void fireActionPerformed(ActionEvent event) {
        _level--;
      }
    });
    bar.add(new JButton("histo") {
      @Override protected void fireActionPerformed(ActionEvent event) {
        Histograms.initFromSwingThread();
        Histograms.build(_trainer.layers());
      }
    });
    JPanel pane = new JPanel();
    BorderLayout bord = new BorderLayout();
    pane.setLayout(bord);
    pane.add("North", bar);
    setSize(1024, 1024);
    pane.add(this);
    return pane;
  }

  @Override public void paint(Graphics g) {
    Layer[] ls = _trainer.layers();
    Vec[] vecs = ((VecsInput) ls[0]).vecs;
//    Vec resp = ((VecSoftmax) ls[ls.length - 1]).vec;
    int edge = 56, pad = 10;
    int rand = _rand.nextInt((int) vecs[0].length());

    // Side
    {
      BufferedImage in = new BufferedImage(EDGE, EDGE, BufferedImage.TYPE_INT_RGB);
      WritableRaster r = in.getRaster();

      // Input
      int[] pix = new int[PIXELS];
      for( int i = 0; i < pix.length; i++ )
        pix[i] = (int) (vecs[i].at8(rand));
      r.setDataElements(0, 0, EDGE, EDGE, pix);
      g.drawImage(in, pad, pad, null);

      // Labels
//      g.drawString("" + resp.at8(rand), 10, 50);
//      g.drawString("RBM " + _level, 10, 70);
    }

    // Outputs
    int offset = pad;
//    float[] visible = new float[MnistNeuralNetTest.PIXELS];
//    System.arraycopy(_images, rand * MnistNeuralNetTest.PIXELS, visible, 0, MnistNeuralNetTest.PIXELS);
//    for( int i = 0; i <= _level; i++ ) {
//      for( int pass = 0; pass < 10; pass++ ) {
//        if( i == _level ) {
//          int[] output = new int[visible.length];
//          for( int v = 0; v < visible.length; v++ )
//            output[v] = (int) Math.min(visible[v] * 255, 255);
//          BufferedImage out = new BufferedImage(MnistNeuralNetTest.EDGE, MnistNeuralNetTest.EDGE,
//              BufferedImage.TYPE_INT_RGB);
//          WritableRaster r = out.getRaster();
//          r.setDataElements(0, 0, MnistNeuralNetTest.EDGE, MnistNeuralNetTest.EDGE, output);
//          BufferedImage image = new BufferedImage(edge, edge, BufferedImage.TYPE_INT_RGB);
//          Graphics2D ig = image.createGraphics();
//          ig.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
//          ig.clearRect(0, 0, edge, edge);
//          ig.drawImage(out, 0, 0, edge, edge, null);
//          ig.dispose();
//          g.drawImage(image, pad * 2 + MnistNeuralNetTest.EDGE, offset, null);
//          offset += pad + edge;
//        }
//        if( _ls[i]._v != null ) {
//          float[] hidden = new float[_ls[i]._b.length];
//          _ls[i].forward(visible, hidden);
//          visible = _ls[i].generate(hidden);
//        }
//      }
//      float[] t = new float[_ls[i]._b.length];
//      _ls[i].forward(visible, t);
//      visible = t;
//    }

    // Weights
    int buf = EDGE + pad + pad;
    Layer layer = ls[_level];
    double mean = 0;
    int n = layer._w.length;
    for( int i = 0; i < n; i++ )
      mean += layer._w[i];
    mean /= layer._w.length;
    double sigma = 0;
    for( int i = 0; i < layer._w.length; i++ ) {
      double d = layer._w[i] - mean;
      sigma += d * d;
    }
    sigma = Math.sqrt(sigma / (layer._w.length - 1));

    for( int o = 0; o < layer._b.length; o++ ) {
      if( o % 10 == 0 ) {
        offset = pad;
        buf += pad + edge;
      }

      int[] start = new int[layer._previous._a.length];
      for( int i = 0; i < layer._previous._a.length; i++ ) {
        double w = layer._w[o * layer._previous._a.length + i];
        w = ((w - mean) / sigma) * 200;
        if( w >= 0 )
          start[i] = ((int) Math.min(+w, 255)) << 8; //GREEN
        else
          start[i] = ((int) Math.min(-w, 255)) << 16; //RED
      }

      BufferedImage out = new BufferedImage(EDGE, EDGE, BufferedImage.TYPE_INT_RGB);
      WritableRaster r = out.getRaster();
      r.setDataElements(0, 0, EDGE, EDGE, start);

      BufferedImage resized = new BufferedImage(edge, edge, BufferedImage.TYPE_INT_RGB);
      Graphics2D g2 = resized.createGraphics();
      try {
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2.clearRect(0, 0, edge, edge);
        g2.drawImage(out, 0, 0, edge, edge, null);
      } finally {
        g2.dispose();
      }
      g.drawImage(resized, buf, offset, null);

      offset += pad + edge;
    }
  }
}


text:
<EMET Version="5.52.6156.38091">
  <EMET_Apps>
    <AppConfig Path="*\Adobe\*\Reader" Executable="AcroRd32Info.exe">
      <Mitigation Name="DEP" Enabled="true" />
      <Mitigation Name="SEHOP" Enabled="true" />
      <Mitigation Name="NullPage" Enabled="true" />
      <Mitigation Name="HeapSpray" Enabled="true" />
      <Mitigation Name="EAF" Enabled="true" />
      <Mitigation Name="EAF+" Enabled="true" />
      <Mitigation Name="MandatoryASLR" Enabled="true" />
      <Mitigation Name="BottomUpASLR" Enabled="true" />
      <Mitigation Name="LoadLib" Enabled="true" />
      <Mitigation Name="MemProt" Enabled="true" />
      <Mitigation Name="Caller" Enabled="true" />
      <Mitigation Name="SimExecFlow" Enabled="true" />
      <Mitigation Name="StackPivot" Enabled="true" />
      <Mitigation Name="ASR" Enabled="false" />
      <Mitigation Name="Fonts" Enabled="false" />
    </AppConfig>
    <AppConfig Path="*\Adobe\*\Reader" Executable="AcroTextExtractor.exe">
      <Mitigation Name="DEP" Enabled="true" />
      <Mitigation Name="SEHOP" Enabled="true" />
      <Mitigation Name="NullPage" Enabled="true" />
      <Mitigation Name="HeapSpray" Enabled="true" />
      <Mitigation Name="EAF" Enabled="true" />
      <Mitigation Name="EAF+" Enabled="true" />
      <Mitigation Name="MandatoryASLR" Enabled="true" />
      <Mitigation Name="BottomUpASLR" Enabled="true" />
      <Mitigation Name="LoadLib" Enabled="true" />
      <Mitigation Name="MemProt" Enabled="true" />
      <Mitigation Name="Caller" Enabled="true" />
      <Mitigation Name="SimExecFlow" Enabled="true" />
      <Mitigation Name="StackPivot" Enabled="true" />
      <Mitigation Name="ASR" Enabled="false" />
      <Mitigation Name="Fonts" Enabled="false" />
    </AppConfig>
    <AppConfig Path="*\Adobe\ARM\*" Executable="AdobeARM.exe">
      <Mitigation Name="DEP" Enabled="true" />
      <Mitigation Name="SEHOP" Enabled="true" />
      <Mitigation Name="NullPage" Enabled="true" />
      <Mitigation Name="HeapSpray" Enabled="true" />
      <Mitigation Name="EAF" Enabled="true" />
      <Mitigation Name="EAF+" Enabled="true" />
      <Mitigation Name="MandatoryASLR" Enabled="true" />
      <Mitigation Name="BottomUpASLR" Enabled="true" />
      <Mitigation Name="LoadLib" Enabled="true" />
      <Mitigation Name="MemProt" Enabled="true" />
      <Mitigation Name="Caller" Enabled="true" />
      <Mitigation Name="SimExecFlow" Enabled="true" />
      <Mitigation Name="StackPivot" Enabled="true" />
      <Mitigation Name="ASR" Enabled="false" />
      <Mitigation Name="Fonts" Enabled="false" />
    </AppConfig>
    <AppConfig Path="*\Adobe\ARM\*" Executable="AdobeARMHelper.exe">
      <Mitigation Name="DEP" Enabled="true" />
      <Mitigation Name="SEHOP" Enabled="true" />
      <Mitigation Name="NullPage" Enabled="true" />
      <Mitigation Name="HeapSpray" Enabled="true" />
      <Mitigation Name="EAF" Enabled="true" />
      <Mitigation Name="EAF+" Enabled="true" />
      <Mitigation Name="MandatoryASLR" Enabled="true" />
      <Mitigation Name="BottomUpASLR" Enabled="true" />
      <Mitigation Name="LoadLib" Enabled="true" />
      <Mitigation Name="MemProt" Enabled="true" />
      <Mitigation Name="Caller" Enabled="true" />
      <Mitigation Name="SimExecFlow" Enabled="true" />
      <Mitigation Name="StackPivot" Enabled="true" />
      <Mitigation Name="ASR" Enabled="false" />
      <Mitigation Name="Fonts" Enabled="false" />
    </AppConfig>
    <AppConfig Path="*\Adobe\ARM\*" Executable="armsvc.exe">
      <Mitigation Name="DEP" Enabled="true" />
      <Mitigation Name="SEHOP" Enabled="true" />
      <Mitigation Name="NullPage" Enabled="true" />
      <Mitigation Name="HeapSpray" Enabled="true" />
      <Mitigation Name="EAF" Enabled="true" />
      <Mitigation Name="EAF+" Enabled="true" />
      <Mitigation Name="MandatoryASLR" Enabled="true" />
      <Mitigation Name="BottomUpASLR" Enabled="true" />
      <Mitigation Name="LoadLib" Enabled="true" />
      <Mitigation Name="MemProt" Enabled="true" />
      <Mitigation Name="Caller" Enabled="true" />
      <Mitigation Name="SimExecFlow" Enabled="true" />
      <Mitigation Name="StackPivot" Enabled="true" />
      <Mitigation Name="ASR" Enabled="false" />
      <Mitigation Name="Fonts" Enabled="false" />
    </AppConfig>
    <AppConfig Path="*\Adobe\*\Reader" Executable="AcroRd32.exe">
      <Mitigation Name="DEP" Enabled="true" />
      <Mitigation Name="SEHOP" Enabled="true" />
      <Mitigation Name="NullPage" Enabled="true" />
      <Mitigation Name="HeapSpray" Enabled="true" />
      <Mitigation Name="EAF" Enabled="true" />
      <Mitigation Name="EAF+" Enabled="true">
        <eaf_modules>AcroRd32.dll;Acrofx32.dll;AcroForm.api</eaf_modules>
      </Mitigation>
      <Mitigation Name="MandatoryASLR" Enabled="true" />
      <Mitigation Name="BottomUpASLR" Enabled="true" />
      <Mitigation Name="LoadLib" Enabled="true" />
      <Mitigation Name="MemProt" Enabled="true" />
      <Mitigation Name="Caller" Enabled="true" />
      <Mitigation Name="SimExecFlow" Enabled="true" />
      <Mitigation Name="StackPivot" Enabled="true" />
      <Mitigation Name="ASR" Enabled="false" />
      <Mitigation Name="Fonts" Enabled="false" />
    </AppConfig>
    <AppConfig Path="*\Adobe\Acrobat*\Acrobat" Executable="Acrobat.exe">
      <Mitigation Name="DEP" Enabled="true" />
      <Mitigation Name="SEHOP" Enabled="true" />
      <Mitigation Name="NullPage" Enabled="true" />
      <Mitigation Name="HeapSpray" Enabled="true" />
      <Mitigation Name="EAF" Enabled="true" />
      <Mitigation Name="EAF+" Enabled="true">
        <eaf_modules>AcroRd32.dll;Acrofx32.dll;AcroForm.api</eaf_modules>
      </Mitigation>
      <Mitigation Name="MandatoryASLR" Enabled="true" />
      <Mitigation Name="BottomUpASLR" Enabled="true" />
      <Mitigation Name="LoadLib" Enabled="true" />
      <Mitigation Name="MemProt" Enabled="true" />
      <Mitigation Name="Caller" Enabled="true" />
      <Mitigation Name="SimExecFlow" Enabled="true" />
      <Mitigation Name="StackPivot" Enabled="true" />
      <Mitigation Name="ASR" Enabled="false" />
      <Mitigation Name="Fonts" Enabled="false" />
    </AppConfig>
  </EMET_Apps>
</EMET>


text:
package org.robovm.samples.tablesearch.ui;

import org.robovm.apple.foundation.NSNumber;
import org.robovm.apple.foundation.NSNumberFormatter;
import org.robovm.apple.foundation.NSNumberFormatterStyle;
import org.robovm.apple.uikit.UINib;
import org.robovm.apple.uikit.UITableViewCell;
import org.robovm.apple.uikit.UITableViewController;
import org.robovm.objc.annotation.CustomClass;
import org.robovm.samples.tablesearch.APLProduct;

@CustomClass("APLBaseTableViewController")
public class APLBaseTableViewController extends UITableViewController {
    final String CELL_IDENTIFIER = "cellID";
    private final String TABLE_CELL_NIB_NAME = "TableCell";

    @Override
    public void viewDidLoad() {
        super.viewDidLoad();

        // we use a nib which contains the cell's view and this class as the
        // files owner
        getTableView().registerReusableCellNib(UINib.create(TABLE_CELL_NIB_NAME, null), CELL_IDENTIFIER);
    }

    public void configureCell(UITableViewCell cell, APLProduct product) {
        cell.getTextLabel().setText(product.getTitle());

        // build the price and year string
        // use NSNumberFormatter to get the currency format out of this NSNumber
        // (product.introPrice)
        NSNumberFormatter numFormatter = new NSNumberFormatter();
        numFormatter.setNumberStyle(NSNumberFormatterStyle.Currency);
        String priceString = numFormatter.format(NSNumber.valueOf(product.getIntroPrice()));

        String detailedStr = String.format("%s | %d", priceString, product.getYearIntroduced());
        cell.getDetailTextLabel().setText(detailedStr);
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/talent/v4beta1/common.proto

package com.google.cloud.talent.v4beta1;

/**
 *
 *
 *

 * Additional information returned to client, such as debugging information.
 *

 *
 * Protobuf type {@code google.cloud.talent.v4beta1.ResponseMetadata}
 */
public final class ResponseMetadata extends com.google.protobuf.GeneratedMessageV3
    implements
    // @@protoc_insertion_point(message_implements:google.cloud.talent.v4beta1.ResponseMetadata)
    ResponseMetadataOrBuilder {
  private static final long serialVersionUID = 0L;
  // Use ResponseMetadata.newBuilder() to construct.
  private ResponseMetadata(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
    super(builder);
  }

  private ResponseMetadata() {
    requestId_ = "";
  }

  @java.lang.Override
  @SuppressWarnings({"unused"})
  protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
    return new ResponseMetadata();
  }

  @java.lang.Override
  public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
    return this.unknownFields;
  }

  public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
    return com.google.cloud.talent.v4beta1.CommonProto
        .internal_static_google_cloud_talent_v4beta1_ResponseMetadata_descriptor;
  }

  @java.lang.Override
  protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internalGetFieldAccessorTable() {
    return com.google.cloud.talent.v4beta1.CommonProto
        .internal_static_google_cloud_talent_v4beta1_ResponseMetadata_fieldAccessorTable
        .ensureFieldAccessorsInitialized(
            com.google.cloud.talent.v4beta1.ResponseMetadata.class,
            com.google.cloud.talent.v4beta1.ResponseMetadata.Builder.class);
  }

  public static final int REQUEST_ID_FIELD_NUMBER = 1;
  private volatile java.lang.Object requestId_;
  /**
   *
   *
   *

   * A unique id associated with this call.
   * This id is logged for tracking purposes.
   *

   *
   * string request_id = 1;
   *
   * @return The requestId.
   */
  @java.lang.Override
  public java.lang.String getRequestId() {
    java.lang.Object ref = requestId_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      requestId_ = s;
      return s;
    }
  }
  /**
   *
   *
   *

   * A unique id associated with this call.
   * This id is logged for tracking purposes.
   *

   *
   * string request_id = 1;
   *
   * @return The bytes for requestId.
   */
  @java.lang.Override
  public com.google.protobuf.ByteString getRequestIdBytes() {
    java.lang.Object ref = requestId_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
      requestId_ = b;
      return b;
    } else {
      return (com.google.protobuf.ByteString) ref;
    }
  }

  private byte memoizedIsInitialized = -1;

  @java.lang.Override
  public final boolean isInitialized() {
    byte isInitialized = memoizedIsInitialized;
    if (isInitialized == 1) return true;
    if (isInitialized == 0) return false;

    memoizedIsInitialized = 1;
    return true;
  }

  @java.lang.Override
  public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) {
      com.google.protobuf.GeneratedMessageV3.writeString(output, 1, requestId_);
    }
    getUnknownFields().writeTo(output);
  }

  @java.lang.Override
  public int getSerializedSize() {
    int size = memoizedSize;
    if (size != -1) return size;

    size = 0;
    if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) {
      size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, requestId_);
    }
    size += getUnknownFields().getSerializedSize();
    memoizedSize = size;
    return size;
  }

  @java.lang.Override
  public boolean equals(final java.lang.Object obj) {
    if (obj == this) {
      return true;
    }
    if (!(obj instanceof com.google.cloud.talent.v4beta1.ResponseMetadata)) {
      return super.equals(obj);
    }
    com.google.cloud.talent.v4beta1.ResponseMetadata other =
        (com.google.cloud.talent.v4beta1.ResponseMetadata) obj;

    if (!getRequestId().equals(other.getRequestId())) return false;
    if (!getUnknownFields().equals(other.getUnknownFields())) return false;
    return true;
  }

  @java.lang.Override
  public int hashCode() {
    if (memoizedHashCode != 0) {
      return memoizedHashCode;
    }
    int hash = 41;
    hash = (19 * hash) + getDescriptor().hashCode();
    hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER;
    hash = (53 * hash) + getRequestId().hashCode();
    hash = (29 * hash) + getUnknownFields().hashCode();
    memoizedHashCode = hash;
    return hash;
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata parseFrom(java.nio.ByteBuffer data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata parseFrom(
      java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata parseFrom(
      com.google.protobuf.ByteString data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata parseFrom(
      com.google.protobuf.ByteString data,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata parseFrom(byte[] data)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data);
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata parseFrom(
      byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws com.google.protobuf.InvalidProtocolBufferException {
    return PARSER.parseFrom(data, extensionRegistry);
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata parseFrom(
      java.io.InputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata parseFrom(
      java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
        PARSER, input, extensionRegistry);
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata parseDelimitedFrom(
      java.io.InputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata parseDelimitedFrom(
      java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
        PARSER, input, extensionRegistry);
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata parseFrom(
      com.google.protobuf.CodedInputStream input) throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata parseFrom(
      com.google.protobuf.CodedInputStream input,
      com.google.protobuf.ExtensionRegistryLite extensionRegistry)
      throws java.io.IOException {
    return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
        PARSER, input, extensionRegistry);
  }

  @java.lang.Override
  public Builder newBuilderForType() {
    return newBuilder();
  }

  public static Builder newBuilder() {
    return DEFAULT_INSTANCE.toBuilder();
  }

  public static Builder newBuilder(com.google.cloud.talent.v4beta1.ResponseMetadata prototype) {
    return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
  }

  @java.lang.Override
  public Builder toBuilder() {
    return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
  }

  @java.lang.Override
  protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
    Builder builder = new Builder(parent);
    return builder;
  }
  /**
   *
   *
   *

   * Additional information returned to client, such as debugging information.
   *

   *
   * Protobuf type {@code google.cloud.talent.v4beta1.ResponseMetadata}
   */
  public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
      implements
      // @@protoc_insertion_point(builder_implements:google.cloud.talent.v4beta1.ResponseMetadata)
      com.google.cloud.talent.v4beta1.ResponseMetadataOrBuilder {
    public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
      return com.google.cloud.talent.v4beta1.CommonProto
          .internal_static_google_cloud_talent_v4beta1_ResponseMetadata_descriptor;
    }

    @java.lang.Override
    protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.google.cloud.talent.v4beta1.CommonProto
          .internal_static_google_cloud_talent_v4beta1_ResponseMetadata_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.google.cloud.talent.v4beta1.ResponseMetadata.class,
              com.google.cloud.talent.v4beta1.ResponseMetadata.Builder.class);
    }

    // Construct using com.google.cloud.talent.v4beta1.ResponseMetadata.newBuilder()
    private Builder() {}

    private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
      super(parent);
    }

    @java.lang.Override
    public Builder clear() {
      super.clear();
      requestId_ = "";

      return this;
    }

    @java.lang.Override
    public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
      return com.google.cloud.talent.v4beta1.CommonProto
          .internal_static_google_cloud_talent_v4beta1_ResponseMetadata_descriptor;
    }

    @java.lang.Override
    public com.google.cloud.talent.v4beta1.ResponseMetadata getDefaultInstanceForType() {
      return com.google.cloud.talent.v4beta1.ResponseMetadata.getDefaultInstance();
    }

    @java.lang.Override
    public com.google.cloud.talent.v4beta1.ResponseMetadata build() {
      com.google.cloud.talent.v4beta1.ResponseMetadata result = buildPartial();
      if (!result.isInitialized()) {
        throw newUninitializedMessageException(result);
      }
      return result;
    }

    @java.lang.Override
    public com.google.cloud.talent.v4beta1.ResponseMetadata buildPartial() {
      com.google.cloud.talent.v4beta1.ResponseMetadata result =
          new com.google.cloud.talent.v4beta1.ResponseMetadata(this);
      result.requestId_ = requestId_;
      onBuilt();
      return result;
    }

    @java.lang.Override
    public Builder clone() {
      return super.clone();
    }

    @java.lang.Override
    public Builder setField(
        com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
      return super.setField(field, value);
    }

    @java.lang.Override
    public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
      return super.clearField(field);
    }

    @java.lang.Override
    public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
      return super.clearOneof(oneof);
    }

    @java.lang.Override
    public Builder setRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
      return super.setRepeatedField(field, index, value);
    }

    @java.lang.Override
    public Builder addRepeatedField(
        com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
      return super.addRepeatedField(field, value);
    }

    @java.lang.Override
    public Builder mergeFrom(com.google.protobuf.Message other) {
      if (other instanceof com.google.cloud.talent.v4beta1.ResponseMetadata) {
        return mergeFrom((com.google.cloud.talent.v4beta1.ResponseMetadata) other);
      } else {
        super.mergeFrom(other);
        return this;
      }
    }

    public Builder mergeFrom(com.google.cloud.talent.v4beta1.ResponseMetadata other) {
      if (other == com.google.cloud.talent.v4beta1.ResponseMetadata.getDefaultInstance())
        return this;
      if (!other.getRequestId().isEmpty()) {
        requestId_ = other.requestId_;
        onChanged();
      }
      this.mergeUnknownFields(other.getUnknownFields());
      onChanged();
      return this;
    }

    @java.lang.Override
    public final boolean isInitialized() {
      return true;
    }

    @java.lang.Override
    public Builder mergeFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      if (extensionRegistry == null) {
        throw new java.lang.NullPointerException();
      }
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            case 10:
              {
                requestId_ = input.readStringRequireUtf8();

                break;
              } // case 10
            default:
              {
                if (!super.parseUnknownField(input, extensionRegistry, tag)) {
                  done = true; // was an endgroup tag
                }
                break;
              } // default:
          } // switch (tag)
        } // while (!done)
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.unwrapIOException();
      } finally {
        onChanged();
      } // finally
      return this;
    }

    private java.lang.Object requestId_ = "";
    /**
     *
     *
     *

     * A unique id associated with this call.
     * This id is logged for tracking purposes.
     *

     *
     * string request_id = 1;
     *
     * @return The requestId.
     */
    public java.lang.String getRequestId() {
      java.lang.Object ref = requestId_;
      if (!(ref instanceof java.lang.String)) {
        com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        requestId_ = s;
        return s;
      } else {
        return (java.lang.String) ref;
      }
    }
    /**
     *
     *
     *

     * A unique id associated with this call.
     * This id is logged for tracking purposes.
     *

     *
     * string request_id = 1;
     *
     * @return The bytes for requestId.
     */
    public com.google.protobuf.ByteString getRequestIdBytes() {
      java.lang.Object ref = requestId_;
      if (ref instanceof String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
        requestId_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }
    /**
     *
     *
     *

     * A unique id associated with this call.
     * This id is logged for tracking purposes.
     *

     *
     * string request_id = 1;
     *
     * @param value The requestId to set.
     * @return This builder for chaining.
     */
    public Builder setRequestId(java.lang.String value) {
      if (value == null) {
        throw new NullPointerException();
      }

      requestId_ = value;
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * A unique id associated with this call.
     * This id is logged for tracking purposes.
     *

     *
     * string request_id = 1;
     *
     * @return This builder for chaining.
     */
    public Builder clearRequestId() {

      requestId_ = getDefaultInstance().getRequestId();
      onChanged();
      return this;
    }
    /**
     *
     *
     *

     * A unique id associated with this call.
     * This id is logged for tracking purposes.
     *

     *
     * string request_id = 1;
     *
     * @param value The bytes for requestId to set.
     * @return This builder for chaining.
     */
    public Builder setRequestIdBytes(com.google.protobuf.ByteString value) {
      if (value == null) {
        throw new NullPointerException();
      }
      checkByteStringIsUtf8(value);

      requestId_ = value;
      onChanged();
      return this;
    }

    @java.lang.Override
    public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.setUnknownFields(unknownFields);
    }

    @java.lang.Override
    public final Builder mergeUnknownFields(
        final com.google.protobuf.UnknownFieldSet unknownFields) {
      return super.mergeUnknownFields(unknownFields);
    }

    // @@protoc_insertion_point(builder_scope:google.cloud.talent.v4beta1.ResponseMetadata)
  }

  // @@protoc_insertion_point(class_scope:google.cloud.talent.v4beta1.ResponseMetadata)
  private static final com.google.cloud.talent.v4beta1.ResponseMetadata DEFAULT_INSTANCE;

  static {
    DEFAULT_INSTANCE = new com.google.cloud.talent.v4beta1.ResponseMetadata();
  }

  public static com.google.cloud.talent.v4beta1.ResponseMetadata getDefaultInstance() {
    return DEFAULT_INSTANCE;
  }

  private static final com.google.protobuf.Parser<ResponseMetadata> PARSER =
      new com.google.protobuf.AbstractParser<ResponseMetadata>() {
        @java.lang.Override
        public ResponseMetadata parsePartialFrom(
            com.google.protobuf.CodedInputStream input,
            com.google.protobuf.ExtensionRegistryLite extensionRegistry)
            throws com.google.protobuf.InvalidProtocolBufferException {
          Builder builder = newBuilder();
          try {
            builder.mergeFrom(input, extensionRegistry);
          } catch (com.google.protobuf.InvalidProtocolBufferException e) {
            throw e.setUnfinishedMessage(builder.buildPartial());
          } catch (com.google.protobuf.UninitializedMessageException e) {
            throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
          } catch (java.io.IOException e) {
            throw new com.google.protobuf.InvalidProtocolBufferException(e)
                .setUnfinishedMessage(builder.buildPartial());
          }
          return builder.buildPartial();
        }
      };

  public static com.google.protobuf.Parser<ResponseMetadata> parser() {
    return PARSER;
  }

  @java.lang.Override
  public com.google.protobuf.Parser<ResponseMetadata> getParserForType() {
    return PARSER;
  }

  @java.lang.Override
  public com.google.cloud.talent.v4beta1.ResponseMetadata getDefaultInstanceForType() {
    return DEFAULT_INSTANCE;
  }
}


text:
package org.shaf.lib.io;

import java.io.IOException;

import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.shaf.core.anno.Option;
import org.shaf.core.anno.Tag;
import org.shaf.core.io.Location;

import com.google.common.collect.ObjectArrays;

/**
 * The process for copying files or directories within the based.
 *
 * @author Mykola Galushka
 */
@Tag(cmd = "cp", group="io", descr = "Copies files or directories.")
public class Copy extends IOProcess {

	@Option(name = "s", arg = "FILE|DIR", descr = "sets path to source entity")
	private Path source;

	@Option(name = "f", arg = "WILDCARD", descr = "sets wildcard for selecting files and directories", value = "NULL", required = false)
	private String wildcard;

	@Option(name = "t", arg = "FILE|DIR", descr = "sets path to target entity")
	private Path target;

	@Option(name = "r", descr = "removes the source after the data transferring", value = "false", required = false)
	private boolean remove;

	/**
	 * Construct a new process for copying data.
	 */
	public Copy() {
		super("copy");
	}

	/**
	 * Performs transferring data from one location to another.
	 */
	@Override
	public String logic() throws IOException {
		Location src = new Location(super.getFileSystem(), super.getBasePath(),
				this.source, this.wildcard.equals("NULL") ? null
						: this.wildcard).setQualifier("source disk entity");
		Location trg = new Location(super.getFileSystem(), super.getBasePath(),
				this.target, null).setQualifier("target disk entity");

		if (src.isFile() && trg.isDirectory()) {
			this.file2dir(src, trg);
		} else if (src.isFile() && (trg.isFile() || trg.getParent().exists())) {
			this.file2file(src, trg);
		} else if (src.isDirectory() && trg.isDirectory()) {
			this.dir2dir(src, trg);
		} else {
			throw new IOException("Invalid copy opearation: " + src.getPath()
					+ " cannot be copied to " + trg.getPath());
		}

		return null;
	}

	/**
	 * Copies file to file.
	 *
	 * @param src
	 *            the information about source file.
	 * @param trg
	 *            the information about target file.
	 *
	 * @throws IOException
	 *             if an I/O error occurs during transferring.
	 */
	private final void file2file(final Location src, final Location trg)
			throws IOException {
		src.shouldBeFile();

		try (FSDataInputStream in = src.getDataInputStream();
				FSDataOutputStream out = trg.getDataOutputStream();) {
			super.copyBlock(in, out, src.getSize());
		} catch (Exception exc) {
			throw new IOException("Failed to copy data form file " + src
					+ " to file " + trg, exc);
		}

		try {
			if (this.remove) {
				src.remove(false);
			}
		} catch (Exception exc) {
			throw new IOException("Failed to remove source.", exc);
		}
	}

	/**
	 * Copies file to directory.
	 *
	 * @param src
	 *            the information about source file.
	 * @param trg
	 *            the information about target directory.
	 * @throws IOException
	 *             if an I/O error occurs during transferring.
	 */
	private final void file2dir(final Location src, final Location trg)
			throws IOException {
		this.file2file(src, trg.resolve(src.getName()));
	}

	/**
	 * Copies directory to directory.
	 *
	 * @param src
	 *            the information about source directory.
	 * @param trg
	 *            the information about target directory.
	 * @throws IOException
	 *             if an I/O error occurs during transferring.
	 */
	private final void dir2dir(final Location src, final Location trg)
			throws IOException {
		src.shouldBeDirectory();

		Location dist = (src.isFilterDefined()) ? trg : trg.resolve(src
				.getName());
		dist.mkdirs();

		Path[] dirs = new Path[0];
		for (Location loc : src.getContent()) {
			if (loc.isFile()) {
				this.file2file(loc, dist.resolve(loc.getPath()));
			} else {
				dirs = ObjectArrays.concat(dirs, loc.getPath());
			}
		}

		try {
			if (this.remove) {
				for (Path dir : dirs) {
					src.resolve(dir).remove(true);
				}
				if (!src.isFilterDefined()) {
					src.remove(false);
				}
			}
		} catch (Exception exc) {
			throw new IOException("Failed to remove source.", exc);
		}
	}
}


text:
.fileInput {
  display: none !important;
}

.button,
.button:hover,
.button:active,
.button:focus {
  padding: 5px 11px;
  border: 5px solid transparent;
  overflow: hidden;
  color: black;
}

.fileChosen, .fileChosen:focus {
  border-color: #5cb85c;
}

.fileChosen:hover {
  border-color: #449d44;
}


text:
title:  Alene
date:  20/04/2019
---

### Bakgrunnsstoff
Fork 4,9–12, Fil 4,11–13, 1 Kor 7,25–34, Matt 19,8, 1 Mos 37,34, Jes 54,5

>
Minnevers

> Da sa Herren Gud: «Det er ikke godt for mennesket å være alene. Jeg vil lage en hjelper av samme slag» (1 Mos 2,18).

En fascinerende, men vond historie kom for dagen. En ung kvinne ble funnet død i leiligheten sin. Det som gjorde historien så tragisk, var at kvinnen hadde vært død i ti år før hun ble funnet. Ti år! Mange stilte seg spørsmålet: Hvordan var det mulig i en storby som denne, at en kvinne, som ikke levde på gaten, kunne ha vært død så lenge uten at noen visste det?

Historien skildrer en realitet: Mange lider av ensomhet. I 2016 hadde en artikkel i _New York Times_ tittelen: «Forskere står overfor en ensomhetsepidemi». Problemet er reelt nok.

Vi mennesker var ikke ment å skulle være alene. Fra Edens hage av skulle vi leve i fellesskap med andre. Men synden kom og snudde alt opp ned. Denne uken vil vi se på spørsmålet om selskap og ensomhet på ulike stadier av livet. Det har nok noen hver opplevd. Hvis ikke, er du heldig.


text:
schnigglesjs
============

A micro-contest management system


text:
#ifndef AbstractSQLTransactionBackend_h
#define AbstractSQLTransactionBackend_h

#include "modules/webdatabase/sqlite/SQLValue.h"
#include "modules/webdatabase/AbstractSQLStatement.h"
#include "modules/webdatabase/SQLError.h"
#include "modules/webdatabase/SQLTransactionState.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/ThreadSafeRefCounted.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"

namespace WebCore {

class AbstractSQLTransactionBackend : public ThreadSafeRefCounted<AbstractSQLTransactionBackend> {
public:
    virtual ~AbstractSQLTransactionBackend() { }

    virtual void requestTransitToState(SQLTransactionState) = 0;

    virtual PassRefPtr<SQLError> transactionError() = 0;
    virtual AbstractSQLStatement* currentStatement() = 0;
    virtual void setShouldRetryCurrentStatement(bool) = 0;

    virtual void executeSQL(PassOwnPtr<AbstractSQLStatement>, const String& statement,
        const Vector<SQLValue>& arguments, int permissions) = 0;

};

} // namespace WebCore

#endif // AbstractSQLTransactionBackend_h


text:
package org.unitedinternet.cosmo.dav.impl;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jackrabbit.server.io.IOUtil;
import org.apache.jackrabbit.webdav.DavResourceIterator;
import org.apache.jackrabbit.webdav.DavResourceIteratorImpl;
import org.apache.jackrabbit.webdav.MultiStatusResponse;
import org.apache.jackrabbit.webdav.io.InputContext;
import org.apache.jackrabbit.webdav.io.OutputContext;
import org.apache.jackrabbit.webdav.property.DavPropertyIterator;
import org.apache.jackrabbit.webdav.property.DavPropertyName;
import org.apache.jackrabbit.webdav.property.DavPropertySet;
import org.apache.jackrabbit.webdav.version.report.ReportType;
import org.unitedinternet.cosmo.dav.CosmoDavException;
import org.unitedinternet.cosmo.dav.DavCollection;
import org.unitedinternet.cosmo.dav.DavContent;
import org.unitedinternet.cosmo.dav.WebDavResource;
import org.unitedinternet.cosmo.dav.DavResourceFactory;
import org.unitedinternet.cosmo.dav.DavResourceLocator;
import org.unitedinternet.cosmo.dav.ForbiddenException;
import org.unitedinternet.cosmo.dav.ProtectedPropertyModificationException;
import org.unitedinternet.cosmo.dav.acl.DavAce;
import org.unitedinternet.cosmo.dav.acl.DavAcl;
import org.unitedinternet.cosmo.dav.acl.DavPrivilege;
import org.unitedinternet.cosmo.dav.acl.resource.DavUserPrincipal;
import org.unitedinternet.cosmo.dav.caldav.CaldavConstants;
import org.unitedinternet.cosmo.dav.property.WebDavProperty;
import org.unitedinternet.cosmo.dav.property.DisplayName;
import org.unitedinternet.cosmo.dav.property.Etag;
import org.unitedinternet.cosmo.dav.property.IsCollection;
import org.unitedinternet.cosmo.dav.property.ResourceType;
import org.unitedinternet.cosmo.model.User;
import org.unitedinternet.cosmo.util.DomWriter;
import org.w3c.dom.Element;

/**
 *

 * Models a WebDAV Inbox collection
 * (as described in http://tools.ietf.org/html/draft-desruisseaux-caldav-sched-05) that
 * contains a contains incoming scheduling messages. These may be requests
 * sent by an "Organizer", or replies sent by an "Attendee" in response to a request. The
 * principal collection itself is not backed by a persistent entity.
 *

 *
 * @see DavResourceBase
 * @see DavCollection
 */
public class DavInboxCollection extends DavResourceBase
    implements DavCollection, CaldavConstants {
    private static final Log LOG = LogFactory.getLog(DavInboxCollection.class);
    private static final Set<ReportType> REPORT_TYPES =
        new HashSet<ReportType>();

    private DavAcl acl;

    static {
        registerLiveProperty(DavPropertyName.DISPLAYNAME);
        registerLiveProperty(DavPropertyName.ISCOLLECTION);
        registerLiveProperty(DavPropertyName.RESOURCETYPE);
        registerLiveProperty(DavPropertyName.GETETAG);
    }

    public DavInboxCollection(DavResourceLocator locator,
                                      DavResourceFactory factory)
        throws CosmoDavException {
        super(locator, factory);
        acl = makeAcl();
    }

    // Jackrabbit WebDavResource

    public String getSupportedMethods() {
        return "OPTIONS, GET, HEAD, TRACE, PROPFIND, PROPPATCH, REPORT";
    }

    public boolean isCollection() {
        return true;
    }

    public long getModificationTime() {
        return -1;
    }

    public boolean exists() {
        return true;
    }

    public String getDisplayName() {
        return "Inbox";
    }

    public String getETag() {
        return "";
    }

    public void writeTo(OutputContext outputContext)
        throws CosmoDavException, IOException {
        writeHtmlDirectoryIndex(outputContext);
    }

    public void addMember(org.apache.jackrabbit.webdav.DavResource member,
                          InputContext inputContext)
        throws org.apache.jackrabbit.webdav.DavException {
        throw new UnsupportedOperationException();
    }

    public DavResourceIterator getMembers() {
        // while it would be ideal to throw an UnsupportedOperationException,
        // MultiStatus tries to add a MultiStatusResponse for every member
        // of a WebDavResource regardless of whether or not it's a collection,
        // so we need to return an empty iterator.
        return DavResourceIteratorImpl.EMPTY;
    }

    @Override
    public DavResourceIterator getCollectionMembers() {
        return DavResourceIteratorImpl.EMPTY;
    }

    public void removeMember(org.apache.jackrabbit.webdav.DavResource member)
        throws org.apache.jackrabbit.webdav.DavException {
        throw new UnsupportedOperationException();
    }

    public WebDavResource getCollection() {
        throw new UnsupportedOperationException();
    }

    public void move(org.apache.jackrabbit.webdav.DavResource destination)
        throws org.apache.jackrabbit.webdav.DavException {
        throw new UnsupportedOperationException();
    }

    public void copy(org.apache.jackrabbit.webdav.DavResource destination,
                     boolean shallow)
        throws org.apache.jackrabbit.webdav.DavException {
        throw new UnsupportedOperationException();
    }

    // WebDavResource

    public DavCollection getParent()
        throws CosmoDavException {
        return null;
    }

    // DavCollection

    public void addContent(DavContent content,
                           InputContext context)
        throws CosmoDavException {
        throw new UnsupportedOperationException();
    }

    public MultiStatusResponse addCollection(DavCollection collection,
                                             DavPropertySet properties)
        throws CosmoDavException {
        throw new UnsupportedOperationException();
    }

    public DavUserPrincipal findMember(String uri)
        throws CosmoDavException {
        DavResourceLocator locator = getResourceLocator().getFactory().
            createResourceLocatorByUri(getResourceLocator().getContext(),
                                       uri);
        return (DavUserPrincipal) getResourceFactory().resolve(locator);
    }

    // our methods

    protected Set<QName> getResourceTypes() {
        HashSet<QName> rt = new HashSet<QName>(2);
        rt.add(RESOURCE_TYPE_COLLECTION);
        rt.add(RESOURCE_TYPE_SCHEDULE_INBOX);
        return rt;
    }

    public Set<ReportType> getReportTypes() {
        return REPORT_TYPES;
    }

    /**
     * Returns the resource's access control list. The list contains the
     * following ACEs:
     *
     *

     *
 DAV:unauthenticated: deny DAV:all

     *
 DAV:all: allow
     * DAV:read, DAV:read-current-user-privilege-set

     *
 DAV:all: deny DAV:all

     *

     */
    protected DavAcl getAcl() {
        return acl;
    }

    private DavAcl makeAcl() {
        DavAcl acl = new DavAcl();

        DavAce unauthenticated = new DavAce.UnauthenticatedAce();
        unauthenticated.setDenied(true);
        unauthenticated.getPrivileges().add(DavPrivilege.ALL);
        unauthenticated.setProtected(true);
        acl.getAces().add(unauthenticated);

        DavAce allAllow = new DavAce.AllAce();
        allAllow.getPrivileges().add(DavPrivilege.READ);
        allAllow.getPrivileges().add(DavPrivilege.READ_CURRENT_USER_PRIVILEGE_SET);
        allAllow.setProtected(true);
        acl.getAces().add(allAllow);

        DavAce allDeny = new DavAce.AllAce();
        allDeny.setDenied(true);
        allDeny.getPrivileges().add(DavPrivilege.ALL);
        allDeny.setProtected(true);
        acl.getAces().add(allDeny);

        return acl;
    }

    /**
     *

     * Extends the superclass method to return {@link DavPrivilege#READ} if
     * the the current principal is a non-admin user.
     *

     */
    protected Set<DavPrivilege> getCurrentPrincipalPrivileges() {
        Set<DavPrivilege> privileges = super.getCurrentPrincipalPrivileges();
        if (! privileges.isEmpty()) {
            return privileges;
        }

        User user = getSecurityManager().getSecurityContext().getUser();
        if (user != null) {
            privileges.add(DavPrivilege.READ);
        }

        return privileges;
    }

    protected void loadLiveProperties(DavPropertySet properties) {
        properties.add(new DisplayName(getDisplayName()));
        properties.add(new ResourceType(getResourceTypes()));
        properties.add(new IsCollection(isCollection()));
        properties.add(new Etag(getETag()));
    }

    protected void setLiveProperty(WebDavProperty property, boolean create)
        throws CosmoDavException {
        throw new ProtectedPropertyModificationException(property.getName());
    }

    protected void removeLiveProperty(DavPropertyName name)
        throws CosmoDavException {
        throw new ProtectedPropertyModificationException(name);
    }

    protected void loadDeadProperties(DavPropertySet properties) {
    }

    protected void setDeadProperty(WebDavProperty property)
        throws CosmoDavException {
        throw new ForbiddenException("Dead properties are not supported on this collection");
    }

    protected void removeDeadProperty(DavPropertyName name)
        throws CosmoDavException {
        throw new ForbiddenException("Dead properties are not supported on this collection");
    }

    private void writeHtmlDirectoryIndex(OutputContext context)
        throws CosmoDavException, IOException {
        if (LOG.isDebugEnabled()) {
            LOG.debug("writing html directory index for  " +
                      getDisplayName());
        }
        context.setContentType(IOUtil.buildContentType("text/html", "UTF-8"));
        // no modification time or etag

        if (! context.hasStream()) {
            return;
        }

        PrintWriter writer =
            new PrintWriter(new OutputStreamWriter(context.getOutputStream(),
                                                   "utf8"));
        try{
            writer.write("\n<title>");
            writer.write(StringEscapeUtils.escapeHtml(getDisplayName()));
            writer.write("</title>\n");
            writer.write("\n");
            writer.write("
");
            writer.write(StringEscapeUtils.escapeHtml(getDisplayName()));
            writer.write("
\n");

            writer.write("
Properties
\n");
            writer.write("
\n");
            for (DavPropertyIterator i=getProperties().iterator(); i.hasNext();) {
                WebDavProperty prop = (WebDavProperty) i.nextProperty();
                Object value = prop.getValue();
                String text = null;
                if (value instanceof Element) {
                    try {
                        text = DomWriter.write((Element)value);
                    } catch (XMLStreamException e) {
                        LOG.warn("Error serializing value for property " + prop.getName());
                    }
                }
                if (text == null) {
                    text = prop.getValueText();
                }
                writer.write("
");
                writer.write(StringEscapeUtils.escapeHtml(prop.getName().toString()));
                writer.write("

");
                writer.write(StringEscapeUtils.escapeHtml(text));
                writer.write("
\n");
            }
            writer.write("
\n");

            User user = getSecurityManager().getSecurityContext().getUser();
            if (user != null) {
                writer.write("
\n");
                DavResourceLocator homeLocator =
                    getResourceLocator().getFactory().
                    createHomeLocator(getResourceLocator().getContext(), user);
                writer.write("");
                writer.write("Home collection");
                writer.write("
\n");

                DavResourceLocator principalLocator =
                    getResourceLocator().getFactory().
                    createPrincipalLocator(getResourceLocator().getContext(),
                                           user);
                writer.write("");
                writer.write("Principal resource");
                writer.write("
\n");
            }

            writer.write("");
            writer.write("\n");
        }finally{
            writer.close();
        }
    }
}


text:
import os
import sys

HEADER = """<!--

DO NOT MODIFY.

This file is generated by
third_party/libaddressinput/chromium/tools/update-strings.py from
src/third_party/libaddressinput/src/cpp/res/messages.grdp. Submit modifications
to the upstream library at https://github.com/googlei18n/libaddressinput.

-->
"""

script_dir = os.path.dirname(os.path.realpath(__file__))
from_file = os.path.abspath(os.path.join(
    script_dir, os.pardir, os.pardir, 'src', 'cpp', 'res', 'messages.grdp'))
to_file = os.path.abspath(os.path.join(
    script_dir, os.pardir, os.pardir, 'chromium', 'address_input_strings.grdp'))

with open(from_file, 'r') as source:
  with open(to_file, 'w') as destination:
    destination.write(source.readline())  # XML declaration.
    destination.write(HEADER)
    destination.write(source.read())


text:
A general-use base project for building fully functional sites on ASP.NET
- [wwwplatform.net](#wwwplatform46net)
    - [Requirements](#requirements)
    - [Clone the Repo (or fork it)](#clone-the-repo-or-fork-it)
    - [Setup](#setup)
    - [Features](#features)
    - [Customization](#customization)

## Requirements
* [Visual Studio 2013 Community Edition](https://www.visualstudio.com/) or later

## Clone the Repo (or fork it)
```
git clone ssh://git@github.com/brondavies/wwwplatform.net.git
```

## Setup
wwwplatform.net uses [ASP.NET MVC](https://www.asp.net/mvc) and [Entity Framework](https://docs.microsoft.com/en-us/ef/) along with many other third-party components and packages.  You should be familiar with these technologies before continuing.

Read [SETUP](SETUP.md) For a guide to getting your project started.

## Features
For a complete list of the built-in features of wwwplatform.net, see [FEATURES](FEATURES.md)

## Customization
For in-depth documentation on customizing and developing new functionality in wwwplatform.net, read [CUSTOMIZING](CUSTOMIZING.md)


text:
package org.apache.flink.streaming.runtime.operators.sink.committables;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.connector.sink2.Sink.InitContext;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.connector.sink2.CommittableMessage;
import org.apache.flink.streaming.api.connector.sink2.CommittableSummary;
import org.apache.flink.streaming.api.connector.sink2.CommittableWithLineage;

import javax.annotation.Nullable;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.stream.Collectors;

import static org.apache.flink.util.Preconditions.checkNotNull;

/**
 * This class is responsible to book-keep the committing progress across checkpoints and subtasks.
 * It handles the emission of committables and the {@link CommittableSummary}.
 *
 * @param <CommT> type of committable
 */
@Internal
public class CommittableCollector<CommT> {
    private static final long EOI = Long.MAX_VALUE;
    /** Mapping of checkpoint id to {@link CheckpointCommittableManagerImpl}. */
    private final NavigableMap<Long, CheckpointCommittableManagerImpl<CommT>>
            checkpointCommittables;
    /** Denotes the subtask id the collector is running. */
    private final int subtaskId;

    private final int numberOfSubtasks;

    public CommittableCollector(int subtaskId, int numberOfSubtasks) {
        this.subtaskId = subtaskId;
        this.numberOfSubtasks = numberOfSubtasks;
        this.checkpointCommittables = new TreeMap<>();
    }

    /** For deep-copy. */
    CommittableCollector(
            Map<Long, CheckpointCommittableManagerImpl<CommT>> checkpointCommittables,
            int subtaskId,
            int numberOfSubtasks) {
        this.checkpointCommittables = new TreeMap<>(checkNotNull(checkpointCommittables));
        this.subtaskId = subtaskId;
        this.numberOfSubtasks = numberOfSubtasks;
    }

    /**
     * Creates a {@link CommittableCollector} based on the current runtime information. This method
     * should be used for to instantiate a collector for all Sink V2.
     *
     * @param context holding runtime of information
     * @param <CommT> type of the committable
     * @return {@link CommittableCollector}
     */
    public static <CommT> CommittableCollector<CommT> of(RuntimeContext context) {
        return new CommittableCollector<>(
                context.getIndexOfThisSubtask(), context.getNumberOfParallelSubtasks());
    }

    /**
     * Creates a {@link CommittableCollector} for a list of committables. This method is mainly used
     * to create a collector from the state of Sink V1.
     *
     * @param committables list of committables
     * @param <CommT> type of committables
     * @return {@link CommittableCollector}
     */
    static <CommT> CommittableCollector<CommT> ofLegacy(List<CommT> committables) {
        CommittableCollector<CommT> committableCollector = new CommittableCollector<>(0, 1);
        // add a checkpoint with the lowest checkpoint id, this will be merged into the next
        // checkpoint data, subtask id is arbitrary
        CommittableSummary<CommT> summary =
                new CommittableSummary<>(
                        0,
                        1,
                        InitContext.INITIAL_CHECKPOINT_ID,
                        committables.size(),
                        committables.size(),
                        0);
        committableCollector.addSummary(summary);
        committables.forEach(
                c -> {
                    final CommittableWithLineage<CommT> committableWithLineage =
                            new CommittableWithLineage<>(c, InitContext.INITIAL_CHECKPOINT_ID, 0);
                    committableCollector.addCommittable(committableWithLineage);
                });
        return committableCollector;
    }

    /**
     * Adds a {@link CommittableMessage} to the collector to hold it until emission.
     *
     * @param message either {@link CommittableSummary} or {@link CommittableWithLineage}
     */
    public void addMessage(CommittableMessage<CommT> message) {
        if (message instanceof CommittableSummary) {
            addSummary((CommittableSummary<CommT>) message);
        } else if (message instanceof CommittableWithLineage) {
            addCommittable((CommittableWithLineage<CommT>) message);
        }
    }

    /**
     * Returns all {@link CheckpointCommittableManager} until the requested checkpoint id.
     *
     * @param checkpointId counter
     * @return collection of {@link CheckpointCommittableManager}
     */
    public Collection<? extends CheckpointCommittableManager<CommT>> getCheckpointCommittablesUpTo(
            long checkpointId) {
        // clean up fully committed previous checkpoints
        // this wouldn't work with concurrent unaligned checkpoints
        Collection<CheckpointCommittableManagerImpl<CommT>> checkpoints =
                checkpointCommittables.headMap(checkpointId, true).values();
        checkpoints.removeIf(CheckpointCommittableManagerImpl::isFinished);
        return checkpoints;
    }

    /**
     * Returns {@link CheckpointCommittableManager} that is currently hold by the collector and
     * associated with the {@link CommittableCollector#EOI} checkpoint id.
     *
     * @return {@link CheckpointCommittableManager}
     */
    @Nullable
    public CommittableManager<CommT> getEndOfInputCommittable() {
        return checkpointCommittables.get(EOI);
    }

    /**
     * Returns whether all {@link CheckpointCommittableManager} currently hold by the collector are
     * either committed or failed.
     *
     * @return state of the {@link CheckpointCommittableManager}
     */
    public boolean isFinished() {
        return checkpointCommittables.values().stream()
                .allMatch(CheckpointCommittableManagerImpl::isFinished);
    }

    /**
     * Merges all information from an external collector into this collector.
     *
     * <p>This method is important during recovery from existing state.
     *
     * @param cc other {@link CommittableCollector}
     */
    public void merge(CommittableCollector<CommT> cc) {
        for (Entry<Long, CheckpointCommittableManagerImpl<CommT>> checkpointEntry :
                cc.checkpointCommittables.entrySet()) {
            checkpointCommittables.merge(
                    checkpointEntry.getKey(),
                    checkpointEntry.getValue(),
                    CheckpointCommittableManagerImpl::merge);
        }
    }

    /**
     * Returns number of subtasks.
     *
     * @return number of subtasks
     */
    public int getNumberOfSubtasks() {
        return numberOfSubtasks;
    }

    /**
     * Returns subtask id.
     *
     * @return subtask id.
     */
    public int getSubtaskId() {
        return subtaskId;
    }

    /**
     * Returns a new committable collector that deep copies all internals.
     *
     * @return {@link CommittableCollector}
     */
    public CommittableCollector<CommT> copy() {
        return new CommittableCollector<>(
                checkpointCommittables.entrySet().stream()
                        .map(e -> Tuple2.of(e.getKey(), e.getValue().copy()))
                        .collect(Collectors.toMap((t) -> t.f0, (t) -> t.f1)),
                subtaskId,
                numberOfSubtasks);
    }

    Collection<CheckpointCommittableManagerImpl<CommT>> getCheckpointCommittables() {
        return checkpointCommittables.values();
    }

    private void addSummary(CommittableSummary<CommT> summary) {
        checkpointCommittables
                .computeIfAbsent(
                        summary.getCheckpointId().orElse(EOI),
                        key ->
                                new CheckpointCommittableManagerImpl<>(
                                        subtaskId,
                                        numberOfSubtasks,
                                        summary.getCheckpointId().orElse(EOI)))
                .upsertSummary(summary);
    }

    private void addCommittable(CommittableWithLineage<CommT> committable) {
        getCheckpointCommittables(committable).addCommittable(committable);
    }

    private CheckpointCommittableManagerImpl<CommT> getCheckpointCommittables(
            CommittableMessage<CommT> committable) {
        CheckpointCommittableManagerImpl<CommT> committables =
                this.checkpointCommittables.get(committable.getCheckpointId().orElse(EOI));
        return checkNotNull(committables, "Unknown checkpoint for %s", committable);
    }
}


text: Java 8 library for functional programming


text:
package addressbook.appmanager;

import addressbook.model.ContactData;
import addressbook.model.Contacts;
import addressbook.model.GroupData;
import addressbook.model.Groups;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import java.util.List;

public class DbHelper {

    private final SessionFactory sessionFactory;

    public DbHelper(){
        // A SessionFactory is set up once for an application!
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure() // configures settings from hibernate.cfg.xml
                .build();
        sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
    }

    public Groups groups(){
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        List<GroupData> result = session.createQuery("from GroupData where deprecated ='0000-00-00'").list();
        for (GroupData group : result) {
            System.out.println(group);
        }
        session.getTransaction().commit();
        session.close();
        return new Groups(result);
    }

    public Contacts contacts() {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        List<ContactData> result = session.createQuery("from ContactData where deprecated ='0000-00-00'").list();
        session.getTransaction().commit();
        session.close();
        return new Contacts(result);
    }

    public ContactData contactById(int id) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        List<ContactData> result = session.createQuery("from ContactData where id = " + id + " and deprecated ='0000-00-00'").list();
        session.getTransaction().commit();
        session.close();
        return result.iterator().next();
    }
}


text:
/*
 * Double.cpp
 *
 *  Created on: Feb 23, 2015
 *      Author: mailmindlin
 */

#include "Double.h"

Double::Double() {
	// TODO Auto-generated constructor stub

}

Double::~Double() {
	// TODO Auto-generated destructor stub
}


text:
package Dec2020Leetcode;

public class _0227BasicCalculatorII {

	public static void main(String[] args) {
		System.out.println(calculate("3+2*2"));
		System.out.println(calculate(" 3/2 "));
		System.out.println(calculate(" 3+5 / 2 "));
	}

	public static int calculate(String s) {

	}
}


text:
(function(Utils, API) {
  'use strict';

  window.OSjs = window.OSjs || {};
  OSjs.API    = OSjs.API    || {};
  OSjs.Core   = OSjs.Core   || {};

  /////////////////////////////////////////////////////////////////////////////
  // GLOBALS
  /////////////////////////////////////////////////////////////////////////////

  var _PROCS = [];        // Running processes

  function _kill(pid, force) {
    if ( pid >= 0 ) {
      if ( _PROCS[pid] ) {
        console.warn('Killing application', pid);
        if ( _PROCS[pid].destroy(true, force) === false ) {
          return;
        }
        _PROCS[pid] = null;
      }
    }
  }

  /////////////////////////////////////////////////////////////////////////////
  // API METHODS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Kills all processes
   *
   * @param   Mixed     match     String/RegExp to match with (optional)
   * @param   boolean   force     Force killing (optional, default=false)
   *
   * @return  void
   * @api     OSjs.API.killAll()
   */
  function doKillAllProcesses(match, force) {
    if ( match ) {
      var isMatching;
      if ( match instanceof RegExp && _PROCS ) {
        isMatching = function(p) {
          return p.__pname && p.__pname.match(match);
        };
      } else if ( typeof match === 'string' ) {
        isMatching = function(p) {
          return p.__pname === match;
        };
      }

      if ( isMatching ) {
        _PROCS.forEach(function(p) {
          if ( p && isMatching(p) ) {
            _kill(p.__pid, force);
          }
        });
      }
      return;
    }

    _PROCS.forEach(function(proc, i) {
      if ( proc ) {
        proc.destroy(false, true);
      }
      _PROCS[i] = null;
    });
    _PROCS = [];
  }

  /**
   * Kills a process
   *
   * @param   int     pid       Process ID
   *
   * @return  void
   * @api     OSjs.API.kill()
   */
  function doKillProcess(pid) {
    _kill(pid, false);
  }

  /**
   * Sends a message to all processes
   *
   * Example: VFS uses this to signal file changes etc.
   *
   * @param   String    msg     Message name
   * @param   Object    opts    Options
   *
   * @return  void
   * @see     Process::_onMessage()
   * @api     OSjs.API.message()
   */
  function doProcessMessage(msg, opts) {
    console.info('doProcessMessage', msg, opts);
    _PROCS.forEach(function(p, i) {
      if ( p && (p instanceof OSjs.Core.Application || p instanceof Process) ) {
        p._onMessage(null, msg, opts);
      }
    });
  }

  /**
   * Get a process by name
   *
   * @param   String    name    Process Name (or by number)
   * @param   boolean   first   Return the first found
   *
   * @return  Process           Or an Array of Processes
   * @api     OSjs.API.getProcess()
   */
  function doGetProcess(name, first) {
    var p;
    var result = first ? null : [];

    if ( typeof name === 'number' ) {
      return _PROCS[name];
    }

    _PROCS.every(function(p, i) {
      if ( p ) {
        if ( p.__pname === name ) {
          if ( first ) {
            result = p;
            return false;
          }
          result.push(p);
        }
      }

      return true;
    });

    return result;
  }

  /**
   * Get all processes
   *
   * @return  Array
   *
   * @api     OSjs.API.getProcesses()
   */
  function doGetProcesses() {
    return _PROCS;
  }

  /////////////////////////////////////////////////////////////////////////////
  // PROCESS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * Process Template Class
   *
   * @param   String    name    Process Name
   *
   * @api     OSjs.Core.Process
   * @class
   */
  function Process(name, args, metadata) {
    this.__pid        = _PROCS.push(this) - 1;
    this.__pname      = name;
    this.__args       = args || {};
    this.__metadata   = metadata || {};
    this.__started    = new Date();
    this.__destroyed  = false;

    this.__label    = this.__metadata.name;
    this.__path     = this.__metadata.path;
    this.__scope    = this.__metadata.scope || 'system';
    this.__iter     = this.__metadata.className;

    console.group('Process::constructor()');
    console.log('pid', this.__pid);
    console.log('pname', this.__pname);
    console.log('started', this.__started);
    console.log('args', this.__args);
    console.groupEnd();
  }

  /**
   * Destroys the process
   *
   * @param   boolean   kill    Force kill ?
   *
   * @return  boolean
   *
   * @method  Process::destroy()
   */
  Process.prototype.destroy = function(kill) {
    kill = (typeof kill === 'undefined') ? true : (kill === true);
    if ( !this.__destroyed ) {

      console.log('OSjs::Core::Process::destroy()', this.__pid, this.__pname);

      if ( kill ) {
        if ( this.__pid >= 0 ) {
          _PROCS[this.__pid] = null;
        }
      }

      this.__destroyed = true;

      return true;
    }
    return false;
  };

  /**
   * Placeholder for messages sendt via API
   *
   * @return  void
   *
   * @method  Process::_onMessage()
   */
  Process.prototype._onMessage = function(obj, msg, args) {
  };

  /**
   * Call the ApplicationAPI
   *
   * This is used for calling 'api.php' or 'api.js' in your Application.
   *
   * On Lua or Arduino it is called 'server.lua'
   *
   * @param   String      method      Name of method
   * @param   Object      args        Arguments in JSON
   * @param   Function    callback    Callback method => fn(error, result)
   * @param   boolean     showLoading Show loading indication (default=true)
   *
   * @return  boolean
   *
   * @method  Process::_api()
   */
  Process.prototype._api = function(method, args, callback, showLoading) {
    var self = this;

    function cb(err, res) {
      if ( self.__destroyed ) {
        console.warn('Process::_api()', 'INGORED RESPONSE: Process was closed');
        return;
      }
      callback(err, res);
    }

    return OSjs.API.call('application', {
      application: this.__iter,
      path: this.__path,
      method: method,
      'arguments': args, __loading: showLoading
    }, cb);
  };

  /**
   * Call the ApplicationAPI
   *
   * This is used for calling 'api.php' or 'api.js' in your Application.
   *
   * On Lua or Arduino it is called 'server.lua'
   *
   * WARNING: THIS METHOD WILL BE DEPRECATED
   *
   * @param   String      method      Name of method
   * @param   Object      args        Arguments in JSON
   * @param   Function    onSuccess   When request is done callback fn(result)
   * @param   Function    onError     When an error occured fn(error)
   * @param   boolean     showLoading Show loading indication (default=true)
   *
   * @return  boolean
   *
   * @method  Process::_call()
   */
  Process.prototype._call = function(method, args, onSuccess, onError, showLoading) {
    var self = this;

    function _defaultError(err) {
      err = err || 'Unknown error';
      OSjs.API.error(OSjs.API._('ERR_APP_API_ERROR'),
                     OSjs.API._('ERR_APP_API_ERROR_DESC_FMT', self.__pname, method),
                     err);
    }

    console.warn('********************************* WARNING *********************************');
    console.warn('THE METHOD Process:_call() IS DEPRECATED AND WILL BE REMOVED IN THE FUTURE');
    console.warn('PLEASE USE Process::_api() INSTEAD!');
    console.warn('***************************************************************************');

    this._api(method, args, function(err, res) {
      if ( err ) {
        (onError || _defaultError)(err);
      } else {
        (onSuccess || function() {})(res);
      }
    }, showLoading);
  };

  /**
   * Get a launch/session argument
   *
   * @return  Mixed     Argument value or null
   *
   * @method  Process::_getArgument()
   */
  Process.prototype._getArgument = function(k) {
    return typeof this.__args[k] === 'undefined' ? null : this.__args[k];
  };

  /**
   * Get all launch/session argument
   *
   * @return  Array
   *
   * @method  Process::_getArguments()
   */
  Process.prototype._getArguments = function() {
    return this.__args;
  };

  /**
   * Get full path to a resorce belonging to this process (package)
   *
   * This is a shortcut for API.getApplicationResource()
   *
   * @param   String      src       Resource name (path)
   *
   * @return  String
   *
   * @method  Process::_getResource()
   * @see     API::getApplicationResource()
   */
  Process.prototype._getResource = function(src) {
    return API.getApplicationResource(this, src);
  };

  /**
   * Set a launch/session argument
   *
   * @param   String    k             Key
   * @param   String    v             Value
   *
   * @return  void
   *
   * @method  Process::_setArgument()
   */
  Process.prototype._setArgument = function(k, v) {
    this.__args[k] = v;
  };

  /////////////////////////////////////////////////////////////////////////////
  // EXPORTS
  /////////////////////////////////////////////////////////////////////////////

  OSjs.Core.Process          = Object.seal(Process);

  OSjs.API.killAll           = doKillAllProcesses;
  OSjs.API.kill              = doKillProcess;
  OSjs.API.message           = doProcessMessage;
  OSjs.API.getProcess        = doGetProcess;
  OSjs.API.getProcesses      = doGetProcesses;

})(OSjs.Utils, OSjs.API);


text:
MOCHA_OPTS=
REPORTER = dot

test: test-unit

test-unit:
	@NODE_ENV=test ./node_modules/.bin/mocha \
			--reporter $(REPORTER) \
			--require test/lib/test_helper.js \
			--colors
			$(MOCHA_OPTS)


text:
/* @flow */

"use strict";

var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"];

var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"];

exports.__esModule = true;

var _babelHelperExplodeAssignableExpression = require("babel-helper-explode-assignable-expression");

var _babelHelperExplodeAssignableExpression2 = _interopRequireDefault(_babelHelperExplodeAssignableExpression);

var _babelTypes = require("babel-types");

var t = _interopRequireWildcard(_babelTypes);

exports["default"] = function (exports /*: Object*/, opts /*: {
                                                              build: Function;
                                                              is: Function;
                                                            }*/) {
  var buildAssignment = function buildAssignment(left, right) {
    return t.assignmentExpression("=", left, right);
  };

  exports.ExpressionStatement = function (path, file) {
    // hit the `AssignmentExpression` one below
    if (path.isCompletionRecord()) return;

    var expr = path.node.expression;
    if (!opts.is(expr, file)) return;

    var nodes = [];

    var exploded = _babelHelperExplodeAssignableExpression2["default"](expr.left, nodes, file, path.scope);

    nodes.push(t.ifStatement(opts.build(exploded.uid, file), t.expressionStatement(buildAssignment(exploded.ref, expr.right))));

    return nodes;
  };

  exports.AssignmentExpression = function (path, file) {
    var node = path.node;
    if (!opts.is(node, file)) return;

    var nodes = [];
    var exploded = _babelHelperExplodeAssignableExpression2["default"](node.left, nodes, file, path.scope);

    nodes.push(t.logicalExpression("&&", opts.build(exploded.uid, file), buildAssignment(exploded.ref, node.right)));

    // todo: duplicate expression node
    nodes.push(exploded.ref);

    return nodes;
  };
};

module.exports = exports["default"];


text:
class CreateStats < ActiveRecord::Migration
  def change
    create_table :stats do |t|
      t.integer :new_users
      t.integer :new_upgrades
      t.float :percent_pro

      t.timestamps
    end
  end
end


text:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>JSONErrorLine</title>

JSONErrorLine()

语法

Result = JSONErrorLine()

概要

Returns the line number within the JSON input of the last failed JSON parsing operation with
ParseJSON(), CatchJSON() or LoadJSON().

参数

无.

返回值

The line number (1-based) of the last JSON parser error.

参阅

JSONErrorPosition(), JSONErrorMessage(), ParseJSON(), CatchJSON(), LoadJSON()

已支持操作系统
所有

<- JSONArraySize() - Json Index - JSONErrorMessage() ->


text:
..
      Copyright 2011-2012 OpenStack Foundation
      All Rights Reserved.

      Licensed under the Apache License, Version 2.0 (the "License"); you may
      not use this file except in compliance with the License. You may obtain
      a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
      WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
      License for the specific language governing permissions and limitations
      under the License.

========================
Developing with Keystone
========================

Setup
-----

Get your development environment set up according to :doc:`setup`. The
instructions from here will assume that you have installed keystone into a
virtualenv. If you chose not to, simply exclude "tools/with_venv.sh" from the
example commands below.

Configuring Keystone
--------------------

keystone requires a configuration file.  There is a sample configuration file
that can be used to get started::

    $ cp etc/keystone.conf.sample etc/keystone.conf

The defaults are enough to get you going, but you can make any changes if
needed.

Running Keystone
----------------

To run the keystone Admin and API server instances, use::

    $ tools/with_venv.sh bin/keystone-all

this runs keystone with the configuration the etc/ directory of the project.
See :doc:`configuration` for details on how Keystone is configured. By default,
keystone is configured with SQL backends.

Interacting with Keystone
-------------------------

You can interact with Keystone through the command line using
:doc:`man/keystone-manage` which allows you to initialize keystone, etc.

You can also interact with Keystone through its REST API. There is a python
keystone client library `python-keystoneclient`_ which interacts exclusively
through the REST API, and which keystone itself uses to provide its
command-line interface.

When initially getting set up, after you've configured which databases to use,
you're probably going to need to run the following to your database schema in
place::

    $ bin/keystone-manage db_sync

.. _`python-keystoneclient`: https://github.com/openstack/python-keystoneclient

Database Schema Migrations
--------------------------

Keystone uses SQLAlchemy-migrate_ to migrate
the SQL database between revisions. For core components, the migrations are
kept in a central repository under ``keystone/common/sql/migrate_repo``.

.. _SQLAlchemy-migrate: http://code.google.com/p/sqlalchemy-migrate/

Extensions should be created as directories under ``keystone/contrib``. An
extension that requires SQL migrations should not change the common repository,
but should instead have its own repository. This repository must be in the
extension's directory in ``keystone/contrib/<extension>/migrate_repo``. In
addition, it needs a subdirectory named ``versions``. For example, if the
extension name is ``my_extension`` then the directory structure would be
``keystone/contrib/my_extension/migrate_repo/versions/``. For the migration to
work, both the ``migrate_repo`` and ``versions`` subdirectories must have
``__init__.py`` files. SQLAlchemy-migrate will look for a configuration file in
the ``migrate_repo`` named ``migrate.cfg``. This conforms to a key/value `ini`
file format. A sample configuration file with the minimal set of values is::

    [db_settings]
    repository_id=my_extension
    version_table=migrate_version
    required_dbs=[]

The directory ``keystone/contrib/example`` contains a sample extension
migration.

Migrations must be explicitly run for each extension individually. To run a
migration for a specific extension, run ``keystone-manage --extension <name>
db_sync``.

Initial Sample Data
-------------------

There is an included script which is helpful in setting up some initial sample
data for use with keystone::

    $ OS_SERVICE_TOKEN=ADMIN tools/with_venv.sh tools/sample_data.sh

Notice it requires a service token read from an environment variable for
authentication.  The default value "ADMIN" is from the ``admin_token``
option in the ``[DEFAULT]`` section in ``etc/keystone.conf``.

Once run, you can see the sample data that has been created by using the
`python-keystoneclient`_ command-line interface::

    $ tools/with_venv.sh keystone --os-token ADMIN --os-endpoint http://127.0.0.1:35357/v2.0/ user-list

Running Tests
=============

Before running tests, you should have ``tox`` installed and available in your
environment (in addition to the other external dependencies in :doc:`setup`)::

    $ pip install tox

.. NOTE::

    You may need to perform both the above operation and the next inside a
    python virtualenv, or prefix the above command with ``sudo``, depending on
    your preference.

To execute the full suite of tests maintained within Keystone, simply run::

    $ tox

This iterates over multiple configuration variations, and uses external
projects to do light integration testing to verify the Identity API against
other projects.

.. NOTE::

    The first time you run ``tox``, it will take additional time to build
    virtualenvs. You can later use the ``-r`` option with ``tox`` to rebuild
    your virtualenv in a similar manner.

To run tests for one or more specific test environments (for example, the most
common configuration of Python 2.7 and PEP-8), list the environments with the
``-e`` option, separated by spaces::

    $ tox -e py27,pep8

See ``tox.ini`` for the full list of available test environments.

Test Structure
--------------

Not all of the tests in the tests directory are strictly unit tests. Keystone
intentionally includes tests that run the service locally and drives the entire
configuration to achieve basic functional testing.

For the functional tests, an in-memory key-value store is used to keep the
tests fast.

Within the tests directory, the general structure of the tests is a basic
set of tests represented under a test class, and then subclasses of those
tests under other classes with different configurations to drive different
backends through the APIs.

For example, ``test_backend.py`` has a sequence of tests under the class
``IdentityTests`` that will work with the default drivers as configured in
this projects etc/ directory. ``test_backend_sql.py`` subclasses those tests,
changing the configuration by overriding with configuration files stored in
the tests directory aimed at enabling the SQL backend for the Identity module.

Likewise, ``test_keystoneclient.py`` takes advantage of the tests written
against ``KeystoneClientTests`` to verify the same tests function through
different drivers and releases of the Keystone client.

The class ``CompatTestCase`` does the work of checking out a specific version
of python-keystoneclient, and then verifying it against a temporarily running
local instance to explicitly verify basic functional testing across the API.

Testing Schema Migrations
-------------------------

The application of schema migrations can be tested using SQLAlchemy Migrate's
built-in test runner, one migration at a time.

.. WARNING::

    This may leave your database in an inconsistent state; attempt this in non-production environments only!

This is useful for testing the *next* migration in sequence (both forward &
backward) in a database under version control::

    python keystone/common/sql/migrate_repo/manage.py test \
    --url=sqlite:///test.db \
    --repository=keystone/common/sql/migrate_repo/

This command references to a SQLite database (test.db) to be used. Depending on
the migration, this command alone does not make assertions as to the integrity
of your data during migration.

Writing Tests
-------------

To add tests covering all drivers, update the relevant base test class
(``test_backend.py``, ``test_legacy_compat.py``, and
``test_keystoneclient.py``).

To add new drivers, subclass the ``test_backend.py`` (look towards
``test_backend_sql.py`` or ``test_backend_kvs.py`` for examples) and update the
configuration of the test class in ``setUp()``.

Further Testing
---------------

devstack_ is the *best* way to quickly deploy keystone with the rest of the
OpenStack universe and should be critical step in your development workflow!

You may also be interested in either the
`OpenStack Continuous Integration Project`_ or the
`OpenStack Integration Testing Project`_.

.. _devstack: http://devstack.org/
.. _OpenStack Continuous Integration Project: https://github.com/openstack/openstack-ci
.. _OpenStack Integration Testing Project: https://github.com/openstack/tempest

LDAP
----
LDAP has a fake backend that performs rudimentary operations.  If you
are building more significant LDAP functionality, you should test against
a live LDAP server.  Devstack has an option to set up a directory server for
Keystone to use.  Add ldap to the ``ENABLED_SERVICES`` environment variable,
and set environment variables ``KEYSTONE_IDENTITY_BACKEND=ldap`` and
``KEYSTONE_CLEAR_LDAP=yes`` in your ``localrc`` file.

The unit tests can be run against a live server with
``keystone/tests/_ldap_livetest.py``.  The default password is ``test`` but if you have
installed devstack with a different LDAP password, modify the file
``keystone/tests/backend_liveldap.conf`` to reflect your password.

Translated responses
--------------------

The Keystone server can provide error responses translated into the language in
the ``Accept-Language`` header of the request. In order to test this in your
development environment, there's a couple of things you need to do.

1. Build the message files. Run the following command in your keystone
   directory::

 $ python setup.py compile_catalog

This will generate .mo files like keystone/locale/[lang]/LC_MESSAGES/[lang].mo

2. When running Keystone, set the ``KEYSTONE_LOCALEDIR`` environment variable
   to the keystone/locale directory. For example::

  $ KEYSTONE_LOCALEDIR=/opt/stack/keystone/keystone/locale keystone-all

Now you can get a translated error response::

 $ curl -s -H "Accept-Language: zh" http://localhost:5000/notapath | python -mjson.tool
 {
     "error": {
         "code": 404,
         "message": "\u627e\u4e0d\u5230\u8cc7\u6e90\u3002",
         "title": "Not Found"
     }
 }

Caching Layer
-------------

The caching layer is designed to be applied to any ``manager`` object within Keystone
via the use of the ``on_arguments`` decorator provided in the ``keystone.common.cache``
module.  This decorator leverages `dogpile.cache`_ caching system to provide a flexible
caching backend.

It is recommended that each of the managers have an independent toggle within the config
file to enable caching.  The easiest method to utilize the toggle within the
configuration file is to define a ``caching`` boolean option within that manager's
configuration section (e.g. ``identity``).  Once that option is defined you can
pass function to the ``on_arguments`` decorator with the named argument ``should_cache_fn``.
In the ``keystone.common.cache`` module, there is a function called ``should_cache_fn``,
which will provide a reference, to a function, that will consult the global cache
``enabled`` option as well as the specific manager's caching enable toggle.

    .. NOTE::
        If a section-specific boolean option is not defined in the config section specified when
        calling ``should_cache_fn``, the returned function reference will default to enabling
        caching for that ``manager``.

Example use of cache and ``should_cache_fn`` (in this example, ``token`` is the manager)::

    from keystone.common import cache
    SHOULD_CACHE = cache.should_cache_fn('token')

    @cache.on_arguments(should_cache_fn=SHOULD_CACHE)
    def cacheable_function(arg1, arg2, arg3):
        ...
        return some_value

With the above example, each call to the ``cacheable_function`` would check to see if
the arguments passed to it matched a currently valid cached item.  If the return value
was cached, the caching layer would return the cached value; if the return value was
not cached, the caching layer would call the function, pass the value to the ``SHOULD_CACHE``
function reference, which would then determine if caching was globally enabled and enabled
for the ``token`` manager.  If either caching toggle is disabled, the value is returned but
not cached.

It is recommended that each of the managers have an independent configurable time-to-live (TTL).
If a configurable TTL has been defined for the manager configuration section, it is possible to
pass it to the ``cache.on_arguments`` decorator with the named-argument ``expiration_time``.  For
consistency, it is recommended that this option be called ``cache_time`` and default to ``None``.
If the ``expiration_time`` argument passed to the decorator is set to ``None``, the expiration
time will be set to the global default (``expiration_time`` option in the ``[cache]``
configuration section.

Example of using a section specific ``cache_time`` (in this example, ``identity`` is the manager)::

    from keystone.common import cache
    SHOULD_CACHE = cache.should_cache_fn('identity')

    @cache.on_arguments(should_cache_fn=SHOULD_CACHE,
                        expiration_time=CONF.identity.cache_time)
    def cachable_function(arg1, arg2, arg3):
        ...
        return some_value

For cache invalidation, the ``on_arguments`` decorator will add an ``invalidate`` method
(attribute) to your decorated function.  To invalidate the cache, you pass the same arguments
to the ``invalidate`` method as you would the normal function.

Example (using the above cacheable_function)::

    def invalidate_cache(arg1, arg2, arg3):
        cacheable_function.invalidate(arg1, arg2, arg3)

.. WARNING::
    The ``on_arguments`` decorator does not accept keyword-arguments/named arguments.  An
    exception will be raised if keyword arguments are passed to a caching-decorated function.

.. NOTE::
    In all cases methods work the same as functions except if you are attempting to invalidate
    the cache on a decorated bound-method, you need to pass  ``self`` to the ``invalidate``
    method as the first argument before the arguments.

.. _`dogpile.cache`: http://dogpilecache.readthedocs.org/

Building the Documentation
==========================

The documentation is all generated with Sphinx from within the docs directory.
To generate the full set of HTML documentation::

    cd docs
    make autodoc
    make html
    make man

the results are in the docs/build/html and docs/build/man directories
respectively.