text:
#include "Wt/WBrush"
#include "Wt/WException"
#include "Wt/WFontMetrics"
#include "Wt/WLogger"
#include "Wt/WPainter"
#include "Wt/WPen"
#include "Wt/WRasterImage"
#include "Wt/WTransform"
#include "Wt/Http/Response"

#include "Wt/FontSupport.h"
#include "WebUtils.h"
#include "UriUtils.h"

#include <cstdio>
#include <cmath>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

#include <SkBitmap.h>
#include <SkBitmapDevice.h>
#include <SkDashPathEffect.h>
#include <SkImageDecoder.h>
#include <SkImageEncoder.h>
#include <SkStream.h>
#include <SkTypeface.h>

//#include <SkForceLinking.h>

namespace {
  inline SkColor fromWColor(const Wt::WColor &color)
  {
    return SkColorSetARGB(color.alpha(),
			  color.red(), color.green(), color.blue());
  }
}

namespace Wt {

LOGGER("WRasterImage");

class WRasterImage::Impl {
public:
  Impl():
    w_(0),
    h_(0),
    bitmap_(0),
    device_(0),
    canvas_(0)
  {}
  unsigned w_, h_;
  std::string type_;
  SkBitmap *bitmap_;
  SkBitmapDevice *device_;
  SkCanvas *canvas_;
  SkPaint strokePaint_;
  SkPaint fillPaint_;
  SkPaint textPaint_;

  void applyTransform(const WTransform& t);
  void setTransform(const WTransform& t);
  void drawPlainPath(SkPath &p, const WPainterPath& path);
};

WRasterImage::WRasterImage(const std::string& type,
			   const WLength& width, const WLength& height,
			   WObject *parent)
  : WResource(parent),
    width_(width),
    height_(height),
    painter_(0),
    impl_(new Impl)
{
  impl_->type_ = type;
  impl_->w_ = static_cast<unsigned long>(width.toPixels());
  impl_->h_ = static_cast<unsigned long>(height.toPixels());

  if (!impl_->w_ || !impl_->h_) {
    impl_->bitmap_ = 0;
    return;
  }

  impl_->bitmap_ = new SkBitmap();
  impl_->bitmap_->setConfig(SkBitmap::kARGB_8888_Config, impl_->w_, impl_->h_);
  impl_->bitmap_->allocPixels();
  impl_->bitmap_->eraseARGB(0, 0, 0, 0);
  impl_->device_ = new SkBitmapDevice(*impl_->bitmap_);
  impl_->canvas_ = new SkCanvas(impl_->device_);

  impl_->textPaint_.setStyle(SkPaint::kStrokeAndFill_Style);
  impl_->textPaint_.setTextEncoding(SkPaint::kUTF8_TextEncoding);
  impl_->strokePaint_.setStyle(SkPaint::kStroke_Style);
  impl_->fillPaint_.setStyle(SkPaint::kFill_Style);

}

void WRasterImage::clear()
{
  impl_->canvas_->clear(0);
}

WRasterImage::~WRasterImage()
{
  beingDeleted();
  delete impl_->canvas_;
  delete impl_->device_;
  delete impl_->bitmap_;
  delete impl_;
}

void WRasterImage::addFontCollection(const std::string& directory,
				     bool recursive)
{
#if 0
  fontSupport_->addFontCollection(directory, recursive);
#endif
}

WFlags<WPaintDevice::FeatureFlag> WRasterImage::features() const
{
  return HasFontMetrics;
}

void WRasterImage::init()
{
  if (!impl_->w_ || !impl_->h_)
    throw WException("Raster image should have non-0 width and height");

  // save unit matrix & empty clipping
  impl_->canvas_->save();

  setChanged(Clipping | Transform | Pen | Brush | Font | Hints);
}

void WRasterImage::done()
{
  impl_->canvas_->restore();
}

void WRasterImage::Impl::applyTransform(const WTransform& t)
{
  SkMatrix sm;
  sm.setAll(SkDoubleToScalar(t.m11()),
	    SkDoubleToScalar(t.m12()),
	    SkDoubleToScalar(t.dx()),
	    SkDoubleToScalar(t.m21()),
	    SkDoubleToScalar(t.m22()),
	    SkDoubleToScalar(t.dy()),
	    0,
	    0,
	    SkDoubleToScalar(1.0));
  canvas_->concat(sm);
}

void WRasterImage::Impl::setTransform(const WTransform& t)
{
  /*
  std::cout << "WRasterImage::setTransform "
	    << t.m11() << ", "
	    << t.m12() << ", "
	    << t.m21() << ", "
	    << t.m22() << ", "
	    << t.dx() << ", "
	    << t.dy() << ", "
	    << std::endl;
  */
  canvas_->resetMatrix();
  applyTransform(t);
}

void WRasterImage::setChanged(WFlags<ChangeFlag> flags)
{
  if (flags & Clipping) {

    if (painter()->hasClipping()) {
      impl_->setTransform(painter()->clipPathTransform());
      SkPath clipPath;
      impl_->drawPlainPath(clipPath, painter()->clipPath());
      impl_->canvas_->clipPath(clipPath, SkRegion::kReplace_Op);
    } else {
      impl_->canvas_->restore();
      impl_->canvas_->save();
    }
    impl_->setTransform(painter()->combinedTransform());
  }

  if (flags & Transform) {
    impl_->setTransform(painter()->combinedTransform());
    flags = Pen | Brush | Font | Hints;
  }

  if (flags & Hints) {
    if (!(painter()->renderHints() & WPainter::Antialiasing)) {
      impl_->strokePaint_.setAntiAlias(false);
      impl_->fillPaint_.setAntiAlias(false);
      impl_->textPaint_.setAntiAlias(false);
    } else {
      impl_->strokePaint_.setAntiAlias(true);
      impl_->fillPaint_.setAntiAlias(true);
      impl_->textPaint_.setAntiAlias(true);
    }
  }

  if (flags & Pen) {
    const WPen& pen = painter()->pen();

    if (pen.style() != NoPen) {
      const WColor& color = pen.color();

      impl_->strokePaint_.setColor(fromWColor(color));

      WLength w = pen.width();
      impl_->strokePaint_.setStrokeWidth(SkIntToScalar(w.toPixels()));

      switch (pen.capStyle()) {
      case FlatCap:
	impl_->strokePaint_.setStrokeCap(SkPaint::kButt_Cap);
	break;
      case SquareCap:
	impl_->strokePaint_.setStrokeCap(SkPaint::kSquare_Cap);
	break;
      case RoundCap:
	impl_->strokePaint_.setStrokeCap(SkPaint::kRound_Cap);
	break;
      }

      switch (pen.joinStyle()) {
      case MiterJoin:
	impl_->strokePaint_.setStrokeJoin(SkPaint::kMiter_Join);
	break;
      case BevelJoin:
	impl_->strokePaint_.setStrokeJoin(SkPaint::kBevel_Join);
	break;
      case RoundJoin:
	impl_->strokePaint_.setStrokeJoin(SkPaint::kRound_Join);
	break;
      }

      SkPathEffect *pe = impl_->strokePaint_.setPathEffect(0);
      if (pe)
	pe->unref();
      switch (pen.style()) {
      case NoPen:
	break;
      case SolidLine:
	break;
      case DashLine: {
	const SkScalar dasharray[] = { SkIntToScalar(4), SkIntToScalar(2) };
	impl_->strokePaint_.setPathEffect(new SkDashPathEffect(dasharray, 2,
							false))->unref();
	break;
      }
      case DotLine: {
	const SkScalar dasharray[] = { SkIntToScalar(1), SkIntToScalar(2) };
	impl_->strokePaint_.setPathEffect(new SkDashPathEffect(dasharray, 2,
							false))->unref();
	break;
      }
      case DashDotLine: {
	const SkScalar dasharray[] = {
	  SkIntToScalar(4),
	  SkIntToScalar(2),
	  SkIntToScalar(1),
	  SkIntToScalar(2)
	};
	impl_->strokePaint_.setPathEffect(new SkDashPathEffect(dasharray, 4,
							false))->unref();
	break;
      }
      case DashDotDotLine: {
	const SkScalar dasharray[] = {
	  SkIntToScalar(4),
	  SkIntToScalar(2),
	  SkIntToScalar(1),
	  SkIntToScalar(2),
	  SkIntToScalar(1),
	  SkIntToScalar(2)
	};
	impl_->strokePaint_.setPathEffect(new SkDashPathEffect(dasharray, 6,
							false))->unref();
	break;
      }
      }

    }
  }

  if (flags & Brush) {
    const WBrush& brush = painter()->brush();
    if (brush.style() != NoBrush) {
      const WColor& color = painter()->brush().color();
      impl_->fillPaint_.setColor(fromWColor(color));
    }
  }

  if (flags & Font) {
    const WFont& font = painter()->font();

    const char *base = 0;
    switch (font.genericFamily()) {
    case WFont::Default:
    case WFont::Serif:
      base = "Times";
      break;
    case WFont::SansSerif:
      base = "Helvetica";
      break;
    case WFont::Monospace:
      base = "Courier";
      break;
    case WFont::Fantasy: // Not really !
      base = "Symbol";
      break;
    case WFont::Cursive: // Not really !
      base = "ZapfDingbats";
    }

    int style = SkTypeface::kNormal;
    if (font.style() != WFont::NormalStyle)
      style |= SkTypeface::kItalic;
    if (font.weight() == WFont::Bold ||
	font.weight() == WFont::Bolder)
      style |= SkTypeface::kBold;

    impl_->textPaint_.setTypeface(SkTypeface::CreateFromName(base,
				    (SkTypeface::Style)style))->unref();
    impl_->textPaint_.setTextSize(SkIntToScalar(font.sizeLength(12).toPixels()));
  }
}

void WRasterImage::drawArc(const WRectF& rect,
			   double startAngle, double spanAngle)
{
  SkRect r = SkRect::MakeLTRB(SkDoubleToScalar(rect.left()),
			      SkDoubleToScalar(rect.top()),
			      SkDoubleToScalar(rect.right()),
			      SkDoubleToScalar(rect.bottom()));
  if (painter()->brush().style() != NoBrush) {
    impl_->canvas_->drawArc(r,
      SkDoubleToScalar(-startAngle),
      SkDoubleToScalar(-spanAngle),
      false, impl_->fillPaint_);
  }
  if (painter()->pen().style() != NoPen) {
    impl_->canvas_->drawArc(r,
      SkDoubleToScalar(-startAngle),
      SkDoubleToScalar(-spanAngle),
      false, impl_->strokePaint_);
  }
}

void WRasterImage::drawImage(const WRectF& rect, const std::string& imgUri,
			     int imgWidth, int imgHeight,
			     const WRectF& srect)
{
  SkBitmap bitmap;
  bool success = false;
  if (DataUri::isDataUri(imgUri)) {
    DataUri uri(imgUri);
    success =
      SkImageDecoder::DecodeMemory(&uri.data[0], uri.data.size(),
				   &bitmap, SkBitmap::kARGB_8888_Config,
				   SkImageDecoder::kDecodePixels_Mode, 0);
    if (!success)
      throw WException("WRasterImage: could not decode data URL (mime type "
		       + uri.mimeType);
  } else {
    success =
      SkImageDecoder::DecodeFile(imgUri.c_str(),
				 &bitmap, SkBitmap::kARGB_8888_Config,
				 SkImageDecoder::kDecodePixels_Mode, 0);
    if (!success)
      throw WException("WRasterImage: could not load file " + imgUri);
  }

  SkRect src = SkRect::MakeLTRB(SkDoubleToScalar(srect.left()),
				SkDoubleToScalar(srect.top()),
				SkDoubleToScalar(srect.right()),
				SkDoubleToScalar(srect.bottom()));
  SkRect dst = SkRect::MakeLTRB(SkDoubleToScalar(rect.left()),
				SkDoubleToScalar(rect.top()),
				SkDoubleToScalar(rect.right()),
				SkDoubleToScalar(rect.bottom()));
  impl_->canvas_->drawBitmapRectToRect(bitmap, &src, dst);
}

void WRasterImage::drawLine(double x1, double y1, double x2, double y2)
{
  impl_->canvas_->drawLine(SkDoubleToScalar(x1), SkDoubleToScalar(y1),
    SkDoubleToScalar(x2), SkDoubleToScalar(y2), impl_->strokePaint_);
}

void WRasterImage::drawPath(const WPainterPath& path)
{
  if (!path.isEmpty()) {
    SkPath p;
    impl_->drawPlainPath(p, path);

    if (painter()->brush().style() != NoBrush) {
      impl_->canvas_->drawPath(p, impl_->fillPaint_);
    }
    if (painter()->pen().style() != NoPen) {
      impl_->canvas_->drawPath(p, impl_->strokePaint_);
    }
  }
}

void WRasterImage::setPixel(int x, int y, const WColor& c)
{
  if (painter_)
    throw WException("WRasterImage::setPixel(): cannot be used while a "
		     "painter is active");
  uint8_t* addr = (uint8_t *)impl_->bitmap_->getAddr(x, y);
  addr[0] = c.blue();
  addr[1] = c.green();
  addr[2] = c.red();
  addr[3] = c.alpha();
}

void WRasterImage::getPixels(void *data)
{
  impl_->canvas_->flush();
  uint32_t *pixel = impl_->bitmap_->getAddr32(0, 0);
  unsigned char *d = (unsigned char *)data;
  if (pixel) {
    int i = 0;
    for (int p = 0; p < impl_->w_ * impl_->h_; ++p) {
      d[i++] = SkColorGetR(*pixel);
      d[i++] = SkColorGetG(*pixel);
      d[i++] = SkColorGetB(*pixel);
      d[i++] = SkColorGetA(*pixel);
      pixel++;
    }
  } else {
    throw WException("WRasterImage::getPixels(): error: no data");
  }
}

WColor WRasterImage::getPixel(int x, int y)
{
  impl_->canvas_->flush();
  SkColor c = impl_->bitmap_->getColor(x, y);
  return WColor(SkColorGetR(c), SkColorGetG(c), SkColorGetB(c), SkColorGetA(c));
}

void WRasterImage::Impl::drawPlainPath(SkPath &p, const WPainterPath& path)
{
  const std::vector<WPainterPath::Segment>& segments = path.segments();

  if (segments.size() > 0
      && segments[0].type() != WPainterPath::Segment::MoveTo)
    p.moveTo(SkDoubleToScalar(0), SkDoubleToScalar(0));

  for (unsigned i = 0; i < segments.size(); ++i) {
    const WPainterPath::Segment s = segments[i];

    switch (s.type()) {
    case WPainterPath::Segment::MoveTo:
      p.moveTo(SkDoubleToScalar(s.x()), SkDoubleToScalar(s.y()));
      break;
    case WPainterPath::Segment::LineTo:
      p.lineTo(SkDoubleToScalar(s.x()), SkDoubleToScalar(s.y()));
      break;
    case WPainterPath::Segment::CubicC1: {
      const double x1 = s.x();
      const double y1 = s.y();
      const double x2 = segments[i+1].x();
      const double y2 = segments[i+1].y();
      const double x3 = segments[i+2].x();
      const double y3 = segments[i+2].y();
      p.cubicTo(SkDoubleToScalar(x1), SkDoubleToScalar(y1),
                SkDoubleToScalar(x2), SkDoubleToScalar(y2),
                SkDoubleToScalar(x3), SkDoubleToScalar(y3));
      i += 2;
      break;
    }
    case WPainterPath::Segment::CubicC2:
    case WPainterPath::Segment::CubicEnd:
      assert(false);
    case WPainterPath::Segment::ArcC: {
      const double x = s.x();
      const double y = s.y();
      const double width = segments[i+1].x();
      const double height = segments[i+1].y();
      const double startAngle = segments[i+2].x();
      const double sweepAngle = segments[i+2].y();
      SkRect rect = SkRect::MakeXYWH(SkDoubleToScalar(x - width),
				     SkDoubleToScalar(y - height),
				     SkDoubleToScalar(width * 2.0),
				     SkDoubleToScalar(height * 2.0));
      if (sweepAngle != 360)
	p.arcTo(rect,
		SkDoubleToScalar(-startAngle), SkDoubleToScalar(-sweepAngle),
		false);
      else
	p.addOval(rect, SkPath::kCCW_Direction);

      i += 2;
      break;
    }
    case WPainterPath::Segment::ArcR:
    case WPainterPath::Segment::ArcAngleSweep:
      assert(false);
    case WPainterPath::Segment::QuadC: {
      const double x1 = s.x();
      const double y1 = s.y();
      const double x2 = segments[i+1].x();
      const double y2 = segments[i+1].y();

      p.quadTo(SkDoubleToScalar(x1), SkDoubleToScalar(y1),
              SkDoubleToScalar(x2), SkDoubleToScalar(y2));

      i += 1;

      break;
    }
    case WPainterPath::Segment::QuadEnd:
      assert(false);
    }
  }
}

void WRasterImage::drawText(const WRectF& rect,
			    WFlags<AlignmentFlag> flags,
			    TextFlag textFlag,
			    const WString& text,
			    const WPointF *clipPoint)
{
#if 0
  SkRect r = SkRect::MakeLTRB(SkDoubleToScalar(rect.left()),
			      SkDoubleToScalar(rect.top()),
			      SkDoubleToScalar(rect.right()),
			      SkDoubleToScalar(rect.bottom()));
  canvas_->drawRect(r, strokePaint_);
#endif
  if (clipPoint && painter()) {
    if (!painter()->clipPathTransform().map(painter()->clipPath())
	  .isPointInPath(painter()->worldTransform().map(*clipPoint)))
      return;
  }

  std::string txt = text.toUTF8();

  AlignmentFlag horizontalAlign = flags & AlignHorizontalMask;
  AlignmentFlag verticalAlign = flags & AlignVerticalMask;

  const WTransform& t = painter()->combinedTransform();

  WPointF p;

  struct SkPaint::FontMetrics metrics;
  impl_->textPaint_.getFontMetrics(&metrics);
  double ascent = SkScalarToFloat(metrics.fAscent);
  double descent = SkScalarToFloat(metrics.fDescent);

  switch (verticalAlign) {
  case AlignTop:
    p = rect.topLeft();
    p.setY(p.y() - ascent);
    break;
  case AlignMiddle:
    p = rect.center();
    //p.setY(p.y() + SkScalarToFloat(textPaint_.getTextSize())/2);
    p.setY(p.y() - ascent/2);
    break;
  case AlignBottom:
    p = rect.bottomLeft();
    p.setY(p.y() - descent);
    break;
  default:
    break;
  }

  switch (horizontalAlign) {
  case AlignLeft:
    impl_->textPaint_.setTextAlign(SkPaint::kLeft_Align);
    p.setX(rect.left());
    break;
  case AlignCenter:
    impl_->textPaint_.setTextAlign(SkPaint::kCenter_Align);
    p.setX(rect.center().x());
    break;
  case AlignRight:
    impl_->textPaint_.setTextAlign(SkPaint::kRight_Align);
    p.setX(rect.right());
    break;
  default:
    break;
  }

  impl_->canvas_->drawText(txt.c_str(), txt.size(),
		    SkDoubleToScalar(p.x()), SkDoubleToScalar(p.y()),
		    impl_->textPaint_);
}

WTextItem WRasterImage::measureText(const WString& text, double maxWidth,
				    bool wordWrap)
{
  SkScalar w =
    impl_->textPaint_.measureText(text.toUTF8().c_str(), text.toUTF8().size());
  return WTextItem(text, SkScalarToFloat(w), -1);

  // TODO: what about wordwrap?
}

WFontMetrics WRasterImage::fontMetrics()
{
  struct SkPaint::FontMetrics metrics;
  impl_->textPaint_.getFontMetrics(&metrics);
  // assumed all are to be positive - ascent of skia is negative
  double ascent = -SkScalarToFloat(metrics.fAscent);
  double descent = SkScalarToFloat(metrics.fDescent);
  double leading = SkScalarToFloat(metrics.fLeading);

  return WFontMetrics(painter_->font(), leading, ascent, descent);
}

class RasterStream : public SkWStream {
public:
  RasterStream(std::ostream &os):
    os_(os)
  {
  }

  virtual bool write(const void* buffer, size_t size) {
    os_.write((const char *)buffer, size);
    return os_.good();
  }

private:
  std::ostream &os_;
};

void WRasterImage::handleRequest(const Http::Request& request,
				 Http::Response& response)
{
  response.setMimeType("image/" + impl_->type_);

  RasterStream s(response.out());

  if (impl_->type_ == "png")
    SkImageEncoder::EncodeStream(&s, *impl_->bitmap_, SkImageEncoder::kPNG_Type, 100);
  else if (impl_->type_ == "jpg")
    SkImageEncoder::EncodeStream(&s, *impl_->bitmap_, SkImageEncoder::kJPEG_Type, 100);

}

}


text:
package net.avalara.avatax.rest.client.enums;
import java.util.HashMap;

/**
 * Status for this exempt certificate
 */
public enum ExemptCertStatusId {
    /**
     * Inactive certificate
     */
    Inactive(0),

    /**
     * Active certificate
     */
    Active(1),

    /**
     * Expired certificate
     */
    Expired(2),

    /**
     * Revoked certificate
     */
    Revoked(3);

    private int value;
	private static HashMap map = new HashMap<>();

	private ExemptCertStatusId(int value) {
		this.value = value;
	}

	static {
		for (ExemptCertStatusId enumName : ExemptCertStatusId.values()) {
			map.put(enumName.value, enumName);
		}
	}

	public static ExemptCertStatusId valueOf(int intValue) {
		return (ExemptCertStatusId) map.get(intValue);
	}

	public int getValue() {
		return value;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.lens.cube.parse;

import org.apache.hadoop.hive.ql.parse.ASTNode;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = true)
class SelectPhraseContext extends QueriedPhraseContext {
  private String actualAlias;
  private String selectAlias;
  private String finalAlias;
  private String exprWithoutAlias;

  SelectPhraseContext(ASTNode selectExpr) {
    super(selectExpr);
  }

  String getExprWithoutAlias() {
    if (exprWithoutAlias == null) {
      //Order of Children of select expression AST Node => Index 0: Select Expression Without Alias, Index 1: Alias */
      exprWithoutAlias = HQLParser.getString((ASTNode) getExprAST().getChild(0)).trim();
    }
    return exprWithoutAlias;
  }

  void updateExprs() {
    super.updateExprs();
    exprWithoutAlias = HQLParser.getString((ASTNode) getExprAST().getChild(0)).trim();
  }

}


text:
@interface NSString (HTML)

// Strips HTML tags & comments, removes extra whitespace and decodes HTML character entities.
- (NSString *)stringByConvertingHTMLToPlainText;

// Decode all HTML entities using GTM.
- (NSString *)stringByDecodingHTMLEntities;

// Encode all HTML entities using GTM.
- (NSString *)stringByEncodingHTMLEntities;

// Minimal unicode encoding will only cover characters from table
// A.2.2 of http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_Special_characters
// which is what you want for a unicode encoded webpage.
- (NSString *)stringByEncodingHTMLEntities:(BOOL)isUnicode;

// Replace newlines with
 tags.
- (NSString *)stringWithNewLinesAsBRs;

// Remove newlines and white space from string.
- (NSString *)stringByRemovingNewLinesAndWhitespace;

// Wrap plain URLs in ...
//  - Ignores URLs inside tags (any URL beginning with =")
//  - HTTP & HTTPS schemes only
//  - Only works in iOS 4+ as we use NSRegularExpression (returns self if not supported so be careful with NSMutableStrings)
//  - Expression: (?<!=")\b((http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)
//  - Adapted from http://regexlib.com/REDetails.aspx?regexp_id=96
- (NSString *)stringByLinkifyingURLs;

// DEPRECIATED - Please use NSString stringByConvertingHTMLToPlainText
- (NSString *)stringByStrippingTags __attribute__((deprecated));

@end


text:
package org.apache.hadoop.tools.posum.simulation.core.dispatcher;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.mapreduce.v2.api.records.JobId;
import org.apache.hadoop.mapreduce.v2.util.MRBuilderUtils;
import org.apache.hadoop.tools.posum.client.data.Database;
import org.apache.hadoop.tools.posum.common.records.call.FindByIdCall;
import org.apache.hadoop.tools.posum.common.records.call.FindByQueryCall;
import org.apache.hadoop.tools.posum.common.records.call.StoreAllCall;
import org.apache.hadoop.tools.posum.common.records.call.StoreCall;
import org.apache.hadoop.tools.posum.common.records.call.TransactionCall;
import org.apache.hadoop.tools.posum.common.records.call.query.QueryUtils;
import org.apache.hadoop.tools.posum.common.records.dataentity.AppProfile;
import org.apache.hadoop.tools.posum.common.records.dataentity.CountersProxy;
import org.apache.hadoop.tools.posum.common.records.dataentity.JobConfProxy;
import org.apache.hadoop.tools.posum.common.records.dataentity.JobProfile;
import org.apache.hadoop.tools.posum.common.records.dataentity.TaskProfile;
import org.apache.hadoop.tools.posum.simulation.core.SimulationContext;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.event.EventHandler;

import java.text.MessageFormat;
import java.util.List;

import static org.apache.hadoop.tools.posum.common.records.dataentity.DataEntityCollection.APP;
import static org.apache.hadoop.tools.posum.common.records.dataentity.DataEntityCollection.COUNTER;
import static org.apache.hadoop.tools.posum.common.records.dataentity.DataEntityCollection.JOB;
import static org.apache.hadoop.tools.posum.common.records.dataentity.DataEntityCollection.JOB_CONF;
import static org.apache.hadoop.tools.posum.common.records.dataentity.DataEntityCollection.TASK;
import static org.apache.hadoop.tools.posum.common.util.GeneralUtils.orZero;
import static org.apache.hadoop.tools.posum.common.util.cluster.ClusterUtils.parseApplicationId;

public class ApplicationMonitor implements EventHandler<ApplicationEvent> {
  private static final Log LOG = LogFactory.getLog(ApplicationMonitor.class);
  private SimulationContext simulationContext;
  private final Database db;
  private Database sourceDb;

  public ApplicationMonitor(SimulationContext simulationContext, Database db, Database sourceDb) {
    this.simulationContext = simulationContext;
    this.db = db;
    this.sourceDb = sourceDb;
  }

  @Override
  public void handle(ApplicationEvent event) {
    switch (event.getType()) {
      case APPLICATION_SUBMITTED:
        applicationSubmitted(event.getOldAppId(), event.getNewAppId());
        break;
    }
  }

  private void applicationSubmitted(String oldAppIdString, ApplicationId appId) {
    LOG.trace(MessageFormat.format("Sim={0} T={1}: Handling application submitted for {2}", simulationContext.getSchedulerClass().getSimpleName(), simulationContext.getCurrentTime(), oldAppIdString));
    String appIdString = appId.toString();

    TransactionCall transaction = TransactionCall.newInstance();
    AppProfile app = sourceDb.execute(FindByIdCall.newInstance(APP, oldAppIdString)).getEntity();
    if (app != null) {
      app.setId(appIdString);
      app.setStartTime(simulationContext.getCurrentTime());
      transaction.addCall(StoreCall.newInstance(APP, app));
    }
    ApplicationId oldAppId = parseApplicationId(oldAppIdString);

    // calculate job id in case the app was not registered in the database (e.g. for an old trace)
    JobId oldJobId = MRBuilderUtils.newJobId(oldAppId, oldAppId.getId());
    String oldJobIdString = oldJobId.toString();
    JobProfile job = sourceDb.execute(FindByIdCall.newInstance(JOB, oldJobIdString)).getEntity();
    job.setAppId(appIdString);

    long clusterTimeAtStart = simulationContext.getClusterTimeAtStart();
    job.setSubmitTime(job.getSubmitTime() - clusterTimeAtStart);
    job.setFinishTime(null);
    if (simulationContext.isOnlineSimulation() && job.getHostName() != null) {
      job.setStartTime(job.getStartTime() - clusterTimeAtStart);
    } else {
      job.setStartTime(null);
      job.setHostName(null);
    }
    if (orZero(job.getDeadline()) != 0) {
      long newDeadline = job.getDeadline() - clusterTimeAtStart;
      if (newDeadline == 0)
        newDeadline = 1; // to avoid considering this job a batch job due to deadline=0
      job.setDeadline(newDeadline);
    }

    transaction.addCall(StoreCall.newInstance(JOB, job));

    JobConfProxy jobConf = sourceDb.execute(FindByIdCall.newInstance(JOB_CONF, oldJobIdString)).getEntity();
    if (jobConf != null) {
      transaction.addCall(StoreCall.newInstance(JOB_CONF, jobConf));
    }

    CountersProxy jobCounters = sourceDb.execute(FindByIdCall.newInstance(COUNTER, oldJobIdString)).getEntity();
    if (jobCounters != null) {
      transaction.addCall(StoreCall.newInstance(COUNTER, jobCounters));
    }

    List<TaskProfile> tasks =
        sourceDb.execute(FindByQueryCall.newInstance(TASK, QueryUtils.is("jobId", oldJobIdString))).getEntities();
    transaction.addCall(StoreAllCall.newInstance(TASK, tasks));
    for (TaskProfile task : tasks) {
      task.setAppId(appIdString);
      if (simulationContext.isOnlineSimulation() && task.getHostName() != null) {
        task.setStartTime(task.getStartTime() - clusterTimeAtStart);
        if (task.isFinished())
          task.setFinishTime(task.getFinishTime() - clusterTimeAtStart);
      } else {
        task.setStartTime(null);
        task.setFinishTime(null);
        task.setHostName(null);
      }
      CountersProxy taskCounters = sourceDb.execute(FindByIdCall.newInstance(COUNTER, task.getId())).getEntity();
      if (taskCounters != null) {
        transaction.addCall(StoreCall.newInstance(COUNTER, taskCounters));
      }
    }
    synchronized (db) {
      db.execute(transaction);
    }
    db.notifyUpdate();
    LOG.trace(MessageFormat.format("Sim={0} T={1}: App submitted. {1} becomes {2}", simulationContext.getSchedulerClass().getSimpleName(), simulationContext.getCurrentTime(), oldAppId, appId));
  }
}


text:
=====
APIs
=====

.. toctree::
   :maxdepth: 1

   creating-a-cmk.md
   enabling-a-cmk.md
   disabling-a-cmk.md
   scheduling-the-deletion-of-a-cmk.md
   canceling-the-scheduled-deletion-of-a-cmk.md
   querying-the-list-of-cmks.md
   querying-the-information-about-a-cmk.md
   creating-a-random-number.md
   creating-a-dek.md
   creating-a-plaintext-free-dek.md
   encrypting-a-dek.md
   decrypting-a-dek.md
   querying-the-number-of-instances.md
   querying-the-quota-of-a-user.md
   changing-the-alias-of-a-cmk.md
   changing-the-description-of-a-cmk.md
   creating-a-grant.md
   revoking-a-grant.md
   retiring-a-grant.md
   querying-grants-on-a-cmk.md
   querying-grants-that-can-be-retired.md
   obtaining-cmk-import-parameters.md
   importing-cmk-material.md
   deleting-cmk-material.md
   enabling-rotation-for-a-cmk.md
   changing-the-rotation-interval-for-a-cmk.md
   disabling-rotation-for-a-cmk.md
   querying-the-rotation-status-of-a-cmk.md
   querying-cmk-instances.md
   querying-cmk-tags.md
   querying-project-tags.md
   adding-or-deleting-cmk-tags-in-batches.md
   adding-a-cmk-tag.md
   deleting-a-cmk-tag.md
   querying-all-api-versions.md
   querying-a-specified-api-version.md


text:
#ifndef __net_ports_UMP_H
#define __net_ports_UMP_H 1

/*
 * UMP interconnect driver
 */

#include <barrelfish/ump_chan.h>
#include <flounder/flounder_support_ump.h>

struct net_ports_ump_binding {
    struct net_ports_binding b;
    struct flounder_ump_state ump_state;

    /* bind params for the new monitor continuation */
    iref_t iref;
    size_t inchanlen;
    size_t outchanlen;

    /* flag indicating that transfers of caps are not supported */
    uint8_t no_cap_transfer;
    uint8_t is_client;
};

extern  void net_ports_ump_destroy(struct net_ports_ump_binding *b);
extern  errval_t net_ports_ump_bind(struct net_ports_ump_binding *b, iref_t iref, net_ports_bind_continuation_fn *_continuation, void *st, struct waitset *waitset, idc_bind_flags_t flags, size_t inchanlen, size_t outchanlen);
extern  errval_t net_ports_ump_connect_handler(void *st, struct monitor_binding *mb, uintptr_t mon_id, struct capref frame, size_t inchanlen, size_t outchanlen, struct capref notify_cap);
extern  void net_ports_ump_rx_handler(void *arg);
extern  errval_t net_ports_ump_accept(struct net_ports_frameinfo *_frameinfo, void *st, net_ports_bind_continuation_fn *_continuation, struct waitset *ws, idc_export_flags_t flags);
extern  errval_t net_ports_ump_connect(struct net_ports_frameinfo *_frameinfo, net_ports_bind_continuation_fn *_continuation, void *st, struct waitset *ws, idc_bind_flags_t flags);
extern  errval_t net_ports_ump_init(struct net_ports_ump_binding *b, struct waitset *waitset, volatile void *inbuf, size_t inbufsize, volatile void *outbuf, size_t outbufsize);

#endif // __net_ports_UMP_H


text:
Shindo.tests('Fog::DNS[:rackspace] | DNS requests', ['rackspace', 'dns']) do

  pending if Fog.mocking?
  domain_name = uniq_id + '.com'

  tests('success on simple domain') do
    domain_tests(Fog::DNS[:rackspace], {:name => domain_name, :email => 'hostmaster@' + domain_name, :records => [{:ttl => 300, :name => domain_name, :type => 'A', :data => '192.168.1.1'}]}) do

      tests('list_domains').formats(LIST_DOMAIN_FORMAT.reject {|key,value| key == 'links'}) do
        Fog::DNS[:rackspace].list_domains.body
      end

      tests("list_domains :limit => 5, :offset => 10, :domain => #{@domain_details.first['name']} --> All possible attributes").formats(LIST_DOMAIN_FORMAT) do
        Fog::DNS[:rackspace].list_domains(:limit => 5, :offset => 10, :domain => @domain_details.first['name']).body
      end

      tests("list_domain_details('#{@domain_id}')").formats(LIST_DOMAIN_DETAILS_WITH_RECORDS) do
        Fog::DNS[:rackspace].list_domain_details(@domain_id).body
      end

      tests("modify_domain('#{@domain_id}', :ttl => 500, :comment => 'woot', :email => 'randomemail@randomhost.com')").succeeds do
        response = Fog::DNS[:rackspace].modify_domain @domain_id, :ttl => 500, :comment => 'woot', :email => 'randomemail@randomhost.com'
        wait_for Fog::DNS[:rackspace], response
      end
    end
  end

  tests('success for domain with multiple records') do
    domain_tests(Fog::DNS[:rackspace],
      {
        :name => domain_name,
        :email => 'hostmaster@' + domain_name,
        :records =>
          [
            {
              :ttl => 300,
              :name => domain_name,
              :type => 'A',
              :data => '192.168.1.1'
            },
            {
              :ttl => 3600,
              :name => domain_name,
              :type => 'MX',
              :data => 'mx.' + domain_name,
              :priority => 10
            }
          ]
     })
  end

  tests('success for multiple domains') do
    domain1_name = uniq_id + '-1.com'
    domain2_name = uniq_id + '-2.com'

    domains_tests(Fog::DNS[:rackspace],
      [
        {:name => domain1_name, :email => 'hostmaster@' + domain1_name, :records => [{:ttl => 300, :name => domain1_name, :type => 'A', :data => '192.168.1.1'}]},
        {:name => domain2_name, :email => 'hostmaster@' + domain2_name, :records => [{:ttl => 300, :name => domain2_name, :type => 'A', :data => '192.168.1.1'}]}
      ])
  end

  tests('success for domain with subdomain') do
    domains_tests(Fog::DNS[:rackspace],
      [
        {:name => domain_name, :email => 'hostmaster@' + domain_name, :records => [{:ttl => 300, :name => domain_name, :type => 'A', :data => '192.168.1.1'}]},
        {:name => 'subdomain.' + domain_name, :email => 'hostmaster@subdomain.' + domain_name, :records => [{:ttl => 300, :name =>'subdomain.' + domain_name, :type => 'A', :data => '192.168.1.1'}]}
      ], true) do

      @root_domain_id = @domain_details.find { |domain| domain['name'] == domain_name }['id']

      tests("list_domain_details('#{@root_domain_id}', :show_records => false, :show_subdomains => false)") do
        response = Fog::DNS[:rackspace].list_domain_details(@root_domain_id, :show_records => false, :show_subdomains => false)

        formats(LIST_DOMAIN_DETAILS_WITHOUT_RECORDS_AND_SUBDOMAINS_FORMAT) { response.body }
        returns(nil) { response.body['recordsList'] }
        returns(nil) { response.body['subdomains'] }
      end

      tests("list_domain_details('#{@root_domain_id}', :show_records => true, :show_subdomains => true)") do
        response = Fog::DNS[:rackspace].list_domain_details(@root_domain_id, :show_records => true, :show_subdomains => true)

        formats(LIST_DOMAIN_DETAILS_WITH_RECORDS_AND_SUBDOMAINS_FORMAT) { response.body }
        returns(false) { response.body['recordsList'].nil? }
        returns(false) { response.body['subdomains'].nil? }
      end

      tests("list_subdomains('#{@root_domain_id}')").formats(LIST_SUBDOMAINS_FORMAT) do
        Fog::DNS[:rackspace].list_subdomains(@root_domain_id).body
      end

      tests("remove_domain('#{@root_domain_id}', :delete_subdomains => true)") do
        wait_for Fog::DNS[:rackspace], Fog::DNS[:rackspace].remove_domain(@root_domain_id, :delete_subdomains => true)

        test('domain and subdomains were really deleted') do
          (Fog::DNS[:rackspace].list_domains.body['domains'].collect { |domain| domain['name'] } & [domain_name, 'subdomain.' + domain_name]).empty?
        end
      end
    end
  end

  tests( 'failure') do

    tests('create_domain(invalid)').returns('ERROR') do
      response = wait_for Fog::DNS[:rackspace], Fog::DNS[:rackspace].create_domains([{:name => 'badtestdomain.com', :email => '', :records => [{:ttl => 300, :name => 'badtestdomain.com', :type => 'A', :data => '192.168.1.1'}]}])

      response.body['status']
    end

    tests('list_domains :limit => 5, :offset => 8').raises(Fog::Rackspace::Errors::BadRequest) do
      Fog::DNS[:rackspace].list_domains :limit => 5, :offset => 8
    end

    tests('list_domain_details 34335353').raises(Fog::DNS::Rackspace::NotFound) do
      Fog::DNS[:rackspace].list_domain_details 34335353
    end

    #tests('create_domains(#{domains})').raises(Fog::Rackspace::Errors::Conflict) do
    #  wait_for Fog::DNS[:rackspace].create_domains(domains)
    #end
    #tests('remove_domain(34343435)').raises(Fog::DNS::Rackspace::DeleteFault) do
    #  Fog::DNS[:rackspace].remove_domain 34343435
    #end
  end
end


text:
:man_page: bson_get_version

bson_get_version()
==================

Synopsis
--------

.. code-block:: c

  const char *
  bson_get_version (void);

Description
-----------

A string representation of Libbson's version, formatted something like "1.2.3" or "1.2.3-dev".

Returns
-------

A string you must not modify or free.


text:
📱 Activities

        Date

        User
        Content
        Verb
        UUID

        {{formatDate(activity.created)}}

        {{activity.actor.displayName}}
        {{activity.content}}
        {{activity.verb}}
        {{activity.uuid}}


text:
<link href='cache.php?css=theme,default,alerts' rel="stylesheet" />

			<?php echo __('Select objects to operate upon'); ?>

				<?php echo __('Either the database is empty, or there was an error retrieving list of database objects'); ?>.

				<?php echo __('Please try closing and re-opening this dialog again'); ?>.

		<fieldset>
			<legend><?php echo __('Operations to perform'); ?></legend>

					<?php echo __('Delete prefix string from name'); ?><input type='text' name='old_prefix' id='old_prefix' maxlength="10" style="width:70px" />

					<?php echo __('Add prefix string to name'); ?><input type='text' name='new_prefix' id='new_prefix' maxlength="10" style="width:70px" />

				<input type='checkbox' name='dropcmd' id='dropcmd' /><?php echo __('DROP selected database objects'); ?>

		</fieldset>

		<fieldset>
			<legend><?php echo __('Generate SQL'); ?></legend>

					<?php echo __('Command text'); ?><input type='text' name='command' id='command' maxlength="100" style="width:180px" />

		</fieldset>

		<fieldset>
			<legend><?php echo __('Options'); ?></legend>

					<input type='checkbox' name='skip_fkey' id='skip_fkey' /><?php echo __('Skip Foreign Key checks'); ?>

		</fieldset>

			<input type='button' id="btn_submit" value='<?php echo __('Submit'); ?>' />

<?php
	echo getGeneratedJS();
?>


text:
FROM ubuntu

RUN apt-get update
RUN apt-get -y install expect redis-server nodejs npm
RUN ln -s /usr/bin/nodejs /usr/bin/node

RUN npm install -g coffee-script
RUN npm install -g yo generator-hubot

# Create hubot user
RUN	useradd -d /hubot -m -s /bin/bash -U hubot

# Log in as hubot user and change directory
USER	hubot
WORKDIR /hubot

# Install hubot
RUN yo hubot --owner="Smarla <home@smarla.com>" --name="Sam" --description="Sam is Smarlas eButler" --defaults

ADD src/scripts ./

RUN npm install hubot-slack --save
RUN npm install

CMD ["bin/hubot", "-a", "slack"]


text:
package org.openid4java.message;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.List;
import java.net.URLDecoder;

/**
 * A list of parameters that are part of an OpenID message. Please note that you can have multiple parameters with
 * the same name.
 *
 * @author Marius Scurtescu, Johnny Bufu
 */
public class ParameterList implements Serializable
{
    private static Log _log = LogFactory.getLog(ParameterList.class);
    private static final boolean DEBUG = _log.isDebugEnabled();

    Map _parameterMap;

    public ParameterList()
    {
        _parameterMap  = new LinkedHashMap();

        if (DEBUG) _log.debug("Created empty parameter list.");
    }

    public ParameterList(ParameterList that)
    {
        if (DEBUG) _log.debug("Cloning parameter list:\n" + that);

        this._parameterMap = new LinkedHashMap(that._parameterMap);
    }

    public ParameterList(Map parameterMap)
    {
        _parameterMap  = new LinkedHashMap();

        Iterator keysIter = parameterMap.keySet().iterator();
        while (keysIter.hasNext())
        {
            String name = (String) keysIter.next();
            Object v = parameterMap.get(name);

            String value;
            if (v instanceof Object[])
            {
                Object[] values = (Object[]) v;
                if (values.length > 1 && name.startsWith("openid."))
                    throw new IllegalArgumentException(
                            "Multiple parameters with the same name: " + values);

                value = values.length > 0 ? (String) values[0] : null;
            }
            else
            {
                value = (String) v;
            }

            set(new Parameter(name, value));
        }

        if (DEBUG) _log.debug("Creating parameter list:\n" + this);
    }

    public void copyOf(ParameterList that)
    {
        if (DEBUG) _log.debug("Copying parameter list:\n" + that);

        this._parameterMap = new LinkedHashMap(that._parameterMap);
    }

    public boolean equals(Object obj)
    {
        if (this == obj)
            return true;

        if (obj == null || getClass() != obj.getClass())
            return false;

        final ParameterList that = (ParameterList) obj;

        return _parameterMap.equals(that._parameterMap);
    }

    public int hashCode()
    {
        return _parameterMap.hashCode();
    }

    public void set(Parameter parameter)
    {
        _parameterMap.put(parameter.getKey(), parameter);
    }

    public void addParams(ParameterList params)
    {
        Iterator iter = params.getParameters().iterator();

        while (iter.hasNext())
            set((Parameter) iter.next());
    }

    public Parameter getParameter(String name)
    {
        return (Parameter) _parameterMap.get(name);
    }

    public String getParameterValue(String name)
    {
        Parameter param = getParameter(name);

        return param != null ? param.getValue() : null;
    }

    public List getParameters()
    {
        return new ArrayList(_parameterMap.values());
    }

    public void removeParameters(String name)
    {
        _parameterMap.remove(name);
    }

    public boolean hasParameter(String name)
    {
        return _parameterMap.containsKey(name);
    }

    /**
     * Create a parameter list based on a URL encoded HTTP query string.
     */
    public static ParameterList createFromQueryString(String queryString) throws MessageException
    {
        if (DEBUG) _log.debug("Creating parameter list from query string: " + queryString);

        ParameterList parameterList = new ParameterList();

        StringTokenizer tokenizer = new StringTokenizer(queryString, "&");
        while (tokenizer.hasMoreTokens())
        {
            String keyValue = tokenizer.nextToken();
            int posEqual = keyValue.indexOf('=');

            if (posEqual == -1)
                throw new MessageException("Invalid query parameter, = missing: " + keyValue);

            try
            {
                String key   = URLDecoder.decode(keyValue.substring(0, posEqual), "UTF-8");
                String value = URLDecoder.decode(keyValue.substring(posEqual + 1), "UTF-8");

                parameterList.set(new Parameter(key, value));
            }
            catch (UnsupportedEncodingException e)
            {
                throw new MessageException("Cannot URL decode query parameter: " + keyValue, e);
            }
        }

        return parameterList;
    }

    public static ParameterList createFromKeyValueForm(String keyValueForm) throws MessageException
    {
        if (DEBUG) _log.debug("Creating parameter list from key-value form:\n" + keyValueForm);

        ParameterList parameterList = new ParameterList();

        StringTokenizer tokenizer = new StringTokenizer(keyValueForm, "\n");
        while (tokenizer.hasMoreTokens())
        {
            String keyValue = tokenizer.nextToken();
            int posColon = keyValue.indexOf(':');

            if (posColon == -1)
                throw new MessageException("Invalid Key-Value form, colon missing: " + keyValue);

            String key   = keyValue.substring(0, posColon);
            String value = keyValue.substring(posColon + 1);

            parameterList.set(new Parameter(key, value));
        }

        return parameterList;
    }

    // todo: same as Message.keyValueFormEncoding()
    public String toString()
    {
        StringBuffer allParams = new StringBuffer("");

        List parameters = getParameters();
        Iterator iterator = parameters.iterator();
        while (iterator.hasNext())
        {
            Parameter parameter = (Parameter) iterator.next();
            allParams.append(parameter.getKey());
            allParams.append(':');
            allParams.append(parameter.getValue());
            allParams.append('\n');
        }

        return allParams.toString();
    }
}


text:
<script>
    var base_url = "{{base_url()}}";
    var registry_url = "{{registry_url()}}";
    var registry_api_url = {{json_encode(get_config_item('vocab_config')['registry_api_url'])}};
    var recaptcha_site_key = "{{get_config_item('reCAPTCHA')['site_key']}}";
@yield('script')
</script>

@if(get_config_item('tracking'))
    <?php $tracking = get_config_item('tracking'); ?>
    @if($tracking['googleGA']['enabled'])
        <!-- Global site tag (gtag.js) - Google Analytics -->
        <script async src="https://www.googletagmanager.com/gtag/js?id={{ $tracking['googleGA']['keys']['id'] }}"></script>
        <script>
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', '{{ $tracking['googleGA']['keys']['id'] }}', {
            cookie_domain: '{{ $tracking['googleGA']['keys']['cookie_domain'] }}',
            cookie_flags: 'SameSite=None;Secure',
          });
        </script>
    @endif
    @if($tracking['luckyOrange']['enabled'])
        <script type='text/javascript'>
        window.__wtw_lucky_site_id = {{ $tracking['luckyOrange']['keys']['id'] }};

        (function() {
            var wa = document.createElement('script'); wa.type = 'text/javascript'; wa.async = true;
            wa.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://cdn') + '.luckyorange.com/w.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wa, s);
          })();
        </script>
    @endif
@endif

<!-- fancytree requires JQuery, so include here. -->
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js'></script>

<!-- JQuery UI used for draggable modal dialogs on CMS, and on
     ARDC-branded login page. Must be included before Bootstrap;
see https://stackoverflow.com/questions/30190437/uncaught-error-cannot-call-methods-on-button-prior-to-initialization-attempted
-->
<script src='//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js'></script>
<!-- But including JQuery UI at this point doesn't seem to work;
     the methods get "lost" (due to overwriting by AngularJS?).
     Keep a copy of the original $, so we can use it later in
     the modal dialogs.
-->
<script>
     var jQueryWithUI = $;
</script>

@if(is_dev())
    <script src="{{ asset_url('js/ie-polyfill.js') }} "></script>
    <script src="{{ asset_url('js/lib/angular/angular.min.js') }} "></script>
    <script src="{{ asset_url('js/lib/angular-route/angular-route.min.js') }}"></script>
    <script src="{{ asset_url('js/lib/angular-sanitize/angular-sanitize.min.js') }}"></script>
    <script src="{{ asset_url('js/lib/angular-animate/angular-animate.min.js') }}"></script>
    <script src="{{ asset_url('js/lib/angular-ui-utils/ui-utils.min.js' )}}"></script>
    <script src="{{ asset_url('js/lib/angular-bootstrap/ui-bootstrap.min.js') }}"></script>
    <script src="{{ asset_url('js/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' )}}"></script>
    <script src="{{ asset_url('js/lib/angular-loading-bar/build/loading-bar.min.js')}}"></script>
    <script type="text/javascript" src="{{ asset_url('js/lib/ng-file-upload/ng-file-upload-all.min.js') }}"></script>
    <script src="{{ asset_url('ands-green/js/packages.min.js','templates') }}"></script>
    <script src="{{ asset_url('js/lib/angular-recaptcha/release/angular-recaptcha.min.js') }} "></script>
    <!-- fancytree must be loaded after JQuery. -->
    <script type="text/javascript" src="{{ asset_url('js/lib/fancytree/dist/jquery.fancytree-all-deps.js') }} "></script>
    <script type="text/javascript" src="{{ asset_url('js/lib/fancytree/dist/modules/jquery.fancytree.clones.js') }} "></script>
@else
    <script src="{{ asset_url('js/lib.js').'?'.getReleaseVersion() }}"></script>
@endif

<script src="{{asset_url('lib/qtip2/jquery.qtip.js', 'core').'?'.getReleaseVersion() }}"></script>
<script type="text/javascript" src="{{ base_url() }}apps/assets/vocab_widget/js/vocab_widget_v2.js?{{ getReleaseVersion() }}"></script>

<!-- TinyMCE wants to load other things, so let it. -->
<script src="{{ asset_url('js/lib/tinymce/tinymce.min.js').'?'.getReleaseVersion() }}"></script>
<script src="{{ asset_url('js/lib/angular-ui-tinymce/dist/tinymce.min.js').'?'.getReleaseVersion() }}"></script>

@if(is_dev())
    <!-- ui-select must be loaded after JQuery. -->
    <script type="text/javascript" src="{{ asset_url('js/lib/ui-select/dist/select.js') }}"></script>
    <script type="text/javascript" src="{{ asset_url('js/vocabs_app.js') }}"></script>
    <script type="text/javascript" src="{{ asset_url('js/filters.js') }}"></script>
    <script type="text/javascript" src="{{ asset_url('js/directives.js') }}"></script>
    <script type="text/javascript" src="{{ asset_url('js/vocabs_factory.js') }}"></script>
    <script type="text/javascript" src="{{ asset_url('js/vocabs_search_controller.js') }}"></script>
@else
    <script type="text/javascript" src="{{ asset_url('js/scripts.js').'?'.getReleaseVersion() }}"></script>
@endif

<script type="text/javascript" src="{{ asset_url('js/vocabs-registry-client-bundle.js').'?'.getReleaseVersion() }}"></script>

@if(isset($scripts))
    @foreach($scripts as $script)
        <script src="{{asset_url('js/'.$script.'.js').'?'.getReleaseVersion()}}"></script>
    @endforeach
@endif
<!--<script type="text/javascript" src="https://jira.ands.org.au/s/d41d8cd98f00b204e9800998ecf8427e/en_AUc8oc9c-1988229788/6265/77/1.4.7/_/download/batch/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector.js?collectorId=d9610dcf"></script>
-->
<script type="text/javascript" src="https://jira.ands.org.au/s/7539600e7269f53cb15d4d97de6e8a32-T/en_US-bq4gqu/64021/60/1.4.25/_/download/batch/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector.js?locale=en-US&collectorId=0d307b22"></script>
@if(is_dev())
    <!-- LESS.JS for development only-->
    <script>
      less = {
        env: "development",
        async: false,
        fileAsync: false,
        poll: 1000,
        logLevel:0
      };
    </script>
    <script src="{{ asset_url('js/lib/less.js/dist/less.min.js') }}"></script>
@endif


text:
<?xml version="1.0" encoding="UTF-8" ?>
<module>
	<name>homeslider</name>
	<displayName><![CDATA[Slider de imagens para sua página inicial]]></displayName>
	<version><![CDATA[1.4.5]]></version>
	<description><![CDATA[Inserir na sua pagina inicial o Image Slider]]></description>
	<author><![CDATA[PrestaShop]]></author>
	<tab><![CDATA[front_office_features]]></tab>
	<is_configurable>1</is_configurable>
	<need_instance>0</need_instance>
	<limited_countries></limited_countries>
</module>


text:
package org.template.rest.model;

/**
 * @author Victor Mezrin
 */
public class ServerResponse {

    boolean result;

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }
}


text:
package com.grovr.kittenfaces;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.Time;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class KittenFacesActivity extends com.zemariamm.appirater.AppiraterBase {

	private static final int SELECT_PICTURE = 1;
	private static final int TAKE_PHOTO = 2;
	private static final int KITTENIFY_PHOTO = 3;

	public static final String TAG = "KITTEN_FACES";
	public static final String originalPhotoLocationID = "ORIGINAL_PHOTO_LOCATION";
	public static final String doWeScaleID = "DO_WE_SCALE";

	private String iKittenPhotoLocation;

	private Intent galleryInent;

	private Intent cameraIntent;

	private Intent shareIntent;

	private Uri photoFileUri;

	private Intent photoViewIntent;

	private Intent iKittenifyPhotoIntent;

	private boolean doWeScale;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		setupDoWeScale();
		hideOrSetupProButton();

		setupGalleryIntentAndButton();
		setupCameraIntentAndButton();
		setupPhotoViewIntentAndButton();
		setupShareIntentAndButton();

		iKittenifyPhotoIntent = new Intent(this, KittenifyPicture.class);
	}

	private void setupDoWeScale() {
		doWeScale = true;
	}

	private void hideOrSetupProButton() {
		Button proButton = (Button) findViewById(R.id.getprobutton);
		if (doWeScale) {
			proButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					System.gc();
					goToMarket();
				}
			});
		} else {
			proButton.setVisibility(Button.INVISIBLE);
		}
	}

	private void goToMarket() {
		Intent goToMarket = null;
		goToMarket = new Intent(Intent.ACTION_VIEW,
				Uri.parse("market://details?id=com.grovr.kittenfacespro"));
		startActivity(goToMarket);
		finish();
	}

	private void setupGalleryIntentAndButton() {
		setupGalleryIntent();
		setupGalleryButton();
	}

	private void setupGalleryIntent() {
		galleryInent = new Intent(Intent.ACTION_GET_CONTENT);
		galleryInent.setType("image/*");
	}

	private void setupGalleryButton() {
		Button galleryButton = (Button) findViewById(R.id.gallerybutton);
		galleryButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				System.gc();
				startActivityForResult(galleryInent, SELECT_PICTURE);
			}
		});
	}

	private void setupShareIntentAndButton() {
		setupShareIntent();
		setupShareButton();
	}

	private void setupShareIntent() {
			shareIntent = new Intent(Intent.ACTION_SEND);
			shareIntent.setType("image/*");
	}

	private void setupShareButton() {
		Button shareButton = (Button) findViewById(R.id.sharebutton);
		shareButton.setVisibility(Button.INVISIBLE);
		shareButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Uri uri = Uri.fromFile(new File(iKittenPhotoLocation));
				shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
				startActivity(shareIntent);
			}
		});
	}

	private void setupCameraIntentAndButton() {
		setupCameraIntent();
		if (cameraIntent != null) {
			setupCameraButton();
		} else {
			Button cameraButton = (Button) findViewById(R.id.camerabutton);
			cameraButton.setVisibility(Button.INVISIBLE);
		}
	}

	private void setupCameraIntent() {
		if (sDCardIsPresent()) {
			cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		} else {
			new AlertDialog.Builder(this)
					.setMessage(
							"External Storage (SD Card) is required to use camera.")
					.setCancelable(true).create().show();
		}

	}

	private boolean sDCardIsPresent() {
		String storageState = Environment.getExternalStorageState();
		return storageState.equals(Environment.MEDIA_MOUNTED);
	}

	private void setNewFileForCameraIntent() {
		String photoPath = generateRandomJpgPathOnSDCard();
		File photoFile = createAndReturnFileAt(photoPath);
		photoFileUri = Uri.fromFile(photoFile);
		cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFileUri);
	}

	private File createAndReturnFileAt(String path) {
		File photoFile = new File(path);
		try {
			if (photoFile.exists() == false) {
				photoFile.getParentFile().mkdirs();
				photoFile.createNewFile();
			}

		} catch (IOException e) {
		}
		return photoFile;
	}

	private String generateRandomJpgPathOnSDCard() {
		String randomPath = Environment.getExternalStorageDirectory().getName()
				+ File.separatorChar + "DCIM" + File.separatorChar
				+ getRandomString() + ".jpg";
		return randomPath;
	}

	private String getRandomString() {
		Time theTime = new Time();
		theTime.setToNow();
		String time = theTime.toString();
		return md5(time);
	}

	public String md5(String s) {
		try {
			MessageDigest digest = java.security.MessageDigest
					.getInstance("MD5");
			digest.update(s.getBytes());
			byte messageDigest[] = digest.digest();

			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++)
				hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	private void setupCameraButton() {
		Button cameraButton = (Button) findViewById(R.id.camerabutton);
		cameraButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				System.gc();
				setNewFileForCameraIntent();
				System.gc();
				startActivityForResult(cameraIntent, TAKE_PHOTO);
			}
		});
	}

	private void setupPhotoViewIntentAndButton() {
		setupPhotoViewIntent();
		setupPhotoViewButton();
	}

	private void setupPhotoViewIntent() {
		photoViewIntent = new Intent(Intent.ACTION_VIEW);
	}

	private void setupPhotoViewButton() {
		final ImageView imageView = (ImageView) findViewById(R.id.facedimage);
		imageView.setVisibility(ImageView.INVISIBLE);
		imageView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (imageView.getVisibility() == ImageView.VISIBLE) {
					Uri uri = Uri.fromFile(new File(iKittenPhotoLocation));
					photoViewIntent.setDataAndType(uri, "image/*");
					startActivity(photoViewIntent);
				}
			}
		});
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			System.gc();
			if (requestCode == SELECT_PICTURE) {
				kittenifyPhotoFromDataIn(data);
			} else if (requestCode == TAKE_PHOTO) {
				kittenifyPhotoFromPhotoDataIn(data);
			}
			emptyImageView();
			if (requestCode == KITTENIFY_PHOTO) {
				iKittenPhotoLocation = data
						.getStringExtra(KittenifyPicture.kittenifiedPhotoLocationID);
				displayKittenPhotoInImageView();
			}
		} else if (resultCode == RESULT_FIRST_USER) {
			new AlertDialog.Builder(this)
					.setMessage(
							"Sorry, something went wrong, please try again.")
					.setCancelable(true).create().show();
		}
	}

	private void kittenifyPhotoFromDataIn(Intent getPictureIntent) {
		Uri selectedImageUri = getPictureIntent.getData();
		String selectedImagePath = getPath(selectedImageUri);
		String filemanagerstring = selectedImageUri.getPath();

		kittenifyPhotoFromFirstLocationIfNotNullElseSecond(selectedImagePath,
				filemanagerstring);
	}

	private void kittenifyPhotoFromPhotoDataIn(Intent getPhotoIntent) {
		String selectedImagePath = getPath(photoFileUri);
		String filemanagerstring = photoFileUri.getPath();

		kittenifyPhotoFromFirstLocationIfNotNullElseSecond(selectedImagePath,
				filemanagerstring);
	}

	private void kittenifyPhotoFromFirstLocationIfNotNullElseSecond(
			String firstLocation, String secondLocation) {
		if (firstLocation != null) {
			kittenifyPhotoAtLocation(firstLocation);
		} else {
			kittenifyPhotoAtLocation(secondLocation);
		}
	}

	private void kittenifyPhotoAtLocation(String location) {
		Bundle bundle = new Bundle();
		bundle.putString(originalPhotoLocationID, location);
		bundle.putBoolean(doWeScaleID, doWeScale);
		iKittenifyPhotoIntent.putExtras(bundle);
		startActivityForResult(iKittenifyPhotoIntent, KITTENIFY_PHOTO);
	}

	private void emptyImageView() {
		ImageView ourView = (ImageView) findViewById(R.id.facedimage);
		ourView.invalidate();
		ourView.setImageResource(0);
		ourView.invalidate();
		ourView.setVisibility(ImageView.INVISIBLE);
		TextView ourText = (TextView) findViewById(R.id.touchtext);
		ourText.setText("");
	}

	private void displayKittenPhotoInImageView() {
		File kittenFile = new File(iKittenPhotoLocation);

		Button shareButton = (Button) findViewById(R.id.sharebutton);
		shareButton.setVisibility(Button.VISIBLE);

		ImageView ourView = (ImageView) findViewById(R.id.facedimage);
		ourView.setImageURI(Uri.fromFile(kittenFile));
		ourView.setVisibility(ImageView.VISIBLE);

		TextView ourText = (TextView) findViewById(R.id.touchtext);
		ourText.setText("Touch picture to view");
		ourText.invalidate();
	}

	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		if (cursor != null) {
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} else {
			return null;
		}
	}

}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Piney Island, Bt-11 Bombing Range, NC</location>
	<station_id>KNBT</station_id>
	<latitude>35.02222</latitude>
	<longitude>-76.4625</longitude>
	<observation_time>Last Updated on Jan 4 2016, 9:56 pm EST</observation_time>
        <observation_time_rfc822>Mon, 04 Jan 2016 21:56:00 -0500</observation_time_rfc822>
	<weather>Partly Cloudy and Breezy</weather>
	<wind_string>from the North at 23.0 gusting to 29.9 MPH (20 gusting to 26 KT)</wind_string>
	<wind_dir>North</wind_dir>
	<wind_degrees>340</wind_degrees>
	<wind_mph>23.0</wind_mph>
	<wind_gust_mph>29.9</wind_gust_mph>
	<wind_kt>20</wind_kt>
	<wind_gust_kt>26</wind_gust_kt>
	<pressure_string>1025.6 mb</pressure_string>
	<pressure_mb>1025.6</pressure_mb>
	<pressure_in>30.27</pressure_in>
	<windchill_string>39 F (4 C)</windchill_string>
      	<windchill_f>39</windchill_f>
      	<windchill_c>4</windchill_c>
 	<icon_url_base>http://forecast.weather.gov/images/wtf/small/</icon_url_base>
	<two_day_history_url>http://www.weather.gov/data/obhistory/KNBT.html</two_day_history_url>
	<icon_url_name>nsct.png</icon_url_name>
	<ob_url>http://www.weather.gov/data/METAR/KNBT.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
package nl.eernie.jmoribus.matcher;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class StepParser
{
	/**
	 * The default prefix to identify parameter names
	 */
	private static final String DEFAULT_PREFIX = "$";
	/**
	 * The default character class to match the parameter names.
	 */
	private static final String DEFAULT_CHARACTER_CLASS = "[\\p{L}\\p{N}\\p{Pc}]";

	private final String prefix;
	private final String characterClass;

	public StepParser()
	{
		this(DEFAULT_PREFIX);
	}

	public StepParser(String defaultPrefix)
	{
		this(defaultPrefix, DEFAULT_CHARACTER_CLASS);
	}

	public StepParser(String prefix, String characterClass)
	{
		this.prefix = prefix;
		this.characterClass = characterClass;
	}

	public RegexStepMatcher parseStep(String stepPattern)
	{
		String escapingPunctuation = escapingPunctuation(stepPattern);
		List<Parameter> parameters = findParameters(escapingPunctuation);
		Pattern regexPattern = buildPattern(escapingPunctuation, parameters);
		return new RegexStepMatcher(regexPattern);
	}

	private Pattern buildPattern(String stepPattern, List<Parameter> parameters)
	{
		String regex = parameterCapturingRegex(stepPattern, parameters);
		return Pattern.compile(regex, Pattern.DOTALL);
	}

	private List<Parameter> findParameters(String pattern)
	{
		List<Parameter> parameters = new ArrayList<>();
		Matcher findingAllParameterNames = findingAllParameterNames().matcher(pattern);
		while (findingAllParameterNames.find())
		{
			parameters.add(new Parameter(findingAllParameterNames.start(), findingAllParameterNames.end(), findingAllParameterNames.group(2)));
		}
		return parameters;
	}

	private Pattern findingAllParameterNames()
	{
		return Pattern.compile("(\\" + prefix + characterClass + "*)(\\W|\\Z)", Pattern.DOTALL);
	}

	private String escapingPunctuation(String pattern)
	{
		return pattern.replaceAll("([\\[\\]\\{\\}\\?\\^\\.\\*\\(\\)\\+\\\\])", "\\\\$1");
	}

	private String ignoringWhitespace(String pattern)
	{
		return pattern.replaceAll("\\s+", "\\\\s+");
	}

	private String parameterCapturingRegex(String stepPattern, List<Parameter> parameters)
	{
		String regex = stepPattern;
		String capture = "(.*)";
		for (int i = parameters.size(); i > 0; i--)
		{
			Parameter parameter = parameters.get(i - 1);
			String start = regex.substring(0, parameter.getStart());
			String end = regex.substring(parameter.getEnd());
			String whitespaceIfAny = parameter.getWhitespaceIfAny();
			regex = start + capture + whitespaceIfAny + end;
		}
		return ignoringWhitespace(regex);
	}
}


text:
package core.inject

import play.api.{ Configuration, Environment }
import play.api.inject.{ Binding, Module }
import com.lvxingpai.yunkai.Userservice.{ FinagledClient => YunkaiClient }

/**
 * Created by zephyre on 1/11/16.
 */
class ThriftClientModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] =
    Seq(bind[YunkaiClient] to new ThriftClientProvider[YunkaiClient])
}


text:
<ons-page id="setting">
    <ons-toolbar>

            <ons-toolbar-button onclick="nav.popPage();">
                <ons-icon icon="ion-android-arrow-back"> back</ons-icon>
            </ons-toolbar-button>

設定

    </ons-toolbar>

      <ons-input id="username" modifier="underbar" placeholder="Username" float></ons-input>

      <ons-input id="password" modifier="underbar" type="password" placeholder="Password" float></ons-input>

      <ons-button >パスワード再設定</ons-button>

  <ons-list>
    <ons-list-header>所属部</ons-list-header>
  <ons-select id="choose-sel" onchange="">
    <option value="basic">XXXX部</option>
    <option value="basic">YYYY部</option>
    <option value="basic">ZZZZ部</option>
  </ons-select>
  </ons-list>

    <ons-button id="btnLogout" modifier="large" onclick="nav.popPage();">設定する</ons-button>

</ons-page>


text:
import collections

def convert(data):
    """ Convert dict in unicode to dict in str.
    """
    if isinstance(data, basestring):
        return str(data)
    elif isinstance(data, collections.Mapping):
        return dict(map(convert, data.iteritems()))
    elif isinstance(data, collections.Iterable):
        return type(data)(map(convert, data))
    else:
        return data

def getWholeName(domain_name, node_name):
    return "%s_%s" % (domain_name, node_name)

def splitWholeName(frontEndName):
    return frontEndName.split("_")[:2]


text:
package ikube.action.index.handler.enrich.geocode;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import ikube.AbstractTest;
import ikube.IConstants;
import ikube.action.index.handler.strategy.geocode.Geocoder;
import ikube.model.Coordinate;
import ikube.model.Search;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;

import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;

/**
 * @author Michael Couck
 * @version 01.00
 * @since 06-03-2011
 */
@RunWith(MockitoJUnitRunner.class)
public class GeocoderTest extends AbstractTest {

    private Search search;

    @Spy
    @InjectMocks
    private Geocoder geocoder;
    @Mock
    private Client client;
    @Mock
    private WebResource webResource;
    @Mock
    private WebResource.Builder webResourceBuilder;
    @Mock
    private ClientResponse clientResponse;

    @Before
    public void before() {
        search = new Search();
        ArrayList<HashMap<String, String>> results = new ArrayList<>();

        HashMap<String, String> result = new HashMap<>();
        // Add the results that we are looking for
        result.put(IConstants.LATITUDE, "-33.9693580");
        result.put(IConstants.LONGITUDE, "18.4622110");
        results.add(result);
        // Add the statistics too
        result = new HashMap<>();
        results.add(result);

        search.setSearchResults(results);
    }

    @Test
    public void getCoordinate() throws Exception {
        when(client.resource(Matchers.anyString())).thenReturn(webResource);
        when(webResource.accept(any(MediaType.APPLICATION_JSON.getClass()))).thenReturn(webResourceBuilder);
        when(webResourceBuilder.post(any(Class.class), anyString())).thenReturn(clientResponse);
        when(clientResponse.getEntity(any(Class.class))).thenReturn(IConstants.GSON.toJson(search));

        geocoder.setSearchUrl("http://localhost:8080/ikube/service/search/json");
        geocoder.setSearchField("name");
        geocoder.setUserid("userid");
        geocoder.setPassword("password");

        Coordinate coordinate = geocoder.getCoordinate("9 avenue road, cape town, south africa");
        assertNotNull(coordinate);
        double lat = coordinate.getLatitude();
        double lon = coordinate.getLongitude();
        assertEquals(-33.9693580, lat, 1.0);
        assertEquals(18.4622110, lon, 1.0);
    }

}


text:
const Action = require('./Action');
const Constants = require('../../util/Constants');

class MessageUpdateAction extends Action {
  handle(data) {
    const client = this.client;

    const channel = client.channels.get(data.channel_id);
    if (channel) {
      const message = channel.messages.get(data.id);
      if (message) {
        message.patch(data);
        client.emit(Constants.Events.MESSAGE_UPDATE, message._edits[0], message);
        return {
          old: message._edits[0],
          updated: message,
        };
      }

      return {
        old: message,
        updated: message,
      };
    }

    return {
      old: null,
      updated: null,
    };
  }
}

/**
 * Emitted whenever a message is updated - e.g. embed or content change.
 * @event Client#messageUpdate
 * @param {Message} oldMessage The message before the update
 * @param {Message} newMessage The message after the update
 */

module.exports = MessageUpdateAction;


text:
. $(dirname ${BASH_SOURCE})/../../contrib/shell/util.sh

CLIENT_LABEL="id.client"
SERVER_LABEL="id.server"

SERVER_IP=$(docker inspect --format '{{ .NetworkSettings.Networks.cilium.GlobalIPv6Address }}' server)

run ""

desc "Ping again to trigger events"
run "docker exec -ti client ping6 -c 4 $SERVER_IP"

desc "Not enough information? Enable debug mode!"
desc "This will recompile the BPF programs with debug instructions while the containers keeps running"
run "cilium endpoint list"

SERVER_ID=$(cilium endpoint list | grep $SERVER_LABEL | awk '{ print $1}')
CLIENT_ID=$(cilium endpoint list | grep $CLIENT_LABEL | awk '{ print $1}')
run "cilium endpoint config $CLIENT_ID Debug=true"
run "cilium endpoint config $SERVER_ID Debug=true"

desc "Ping again to see debugging events"
run "docker exec -ti client ping6 -c 4 $SERVER_IP"

clear
desc "Packets get dropped due to policy denial. Trace the policy decision"
run "cilium policy trace -s $CLIENT_LABEL -d $SERVER_LABEL"

desc "No policy has been loaded, import it."
run "cat $(relative policy.json)"
run "cilium policy import $(relative policy.json)"

clear
desc "Trace policy again"
run "cilium policy trace -s $CLIENT_LABEL -d $SERVER_LABEL"

desc "Ping should now work as expected"
run "docker exec -ti client ping6 -c 4 $SERVER_IP"

desc "All good. Compile out debug and drop notifications again for efficiency"

run "cilium endpoint config $CLIENT_ID Debug=false DropNotification=false TraceNotification=false"
run "cilium endpoint config $SERVER_ID Debug=false DropNotification=false TraceNotification=false"

desc "Ping will no longer trigger events for these containers"
run "docker exec -ti client ping6 -c 4 $SERVER_IP"


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Farada.TestDataGeneration.Extensions;
using Farada.TestDataGeneration.ValueProviders.Context;
using JetBrains.Annotations;

namespace Farada.TestDataGeneration.ValueProviders
{
  /// <summary>
  /// Provides a value for a specific type
  /// </summary>
  /// <typeparam name="TMember">The member type for which the value is created</typeparam>
  /// <typeparam name="TContext">The context under which the value is created</typeparam>
  public abstract class ValueProvider<TMember, TContext> : IValueProvider
      where TContext : ValueProviderContext<TMember>
  {
    IEnumerable<object> IValueProvider.CreateMany (IValueProviderContext context, [CanBeNull] IList<object> metadatas, int itemCount)
    {
      return CreateManyValues ((TContext) context, metadatas, itemCount).Cast<object>();
    }

    public virtual bool CanHandle (Type memberType)
    {
      return memberType==typeof(TMember) || memberType.UnwrapIfNullable() == typeof (TMember);
    }

    public virtual bool FillsType (Type memberType)
    {
      //by default all value provider should be able to fill the direct type they were registered for.
      //e.g if you registered a value provider for Vehicle, it should be possible to fill the vehicle type completely
      //however the user can always enforce auto fill by using EnableAutoFill() in the registration.
      return memberType == typeof(TMember) || memberType.UnwrapIfNullable() == typeof (TMember);
    }

    protected abstract TContext CreateContext (ValueProviderObjectContext objectContext);

    IValueProviderContext IValueProvider.CreateContext (ValueProviderObjectContext objectContext)
    {
      return CreateContext (objectContext);
    }

    /// <summary>
    /// Creates a value of the given property type
    /// </summary>
    /// <param name="context">the concrete context to consider.</param>
    [CanBeNull]
    protected abstract TMember CreateValue (TContext context);

    protected virtual IEnumerable<TMember> CreateManyValues (TContext context, [CanBeNull] IList<object> metadatas, int itemCount)
    {
      for (var i = 0; i < itemCount; i++)
        yield return CreateValue (metadatas == null ? context : context.Enrich<TContext> (metadatas[i]));
    }
  }

  public abstract class ValueProvider<TMember> : ValueProvider<TMember, ValueProviderContext<TMember>>
  {
    protected override ValueProviderContext<TMember> CreateContext (ValueProviderObjectContext objectContext)
    {
      return new ValueProviderContext<TMember> (objectContext);
    }
  }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Tweets for the_antlr_guy</title>

Tweets for the_antlr_guy

Median sentiment score: 0.2133 (-1.0 negative to 1.0 positive)

        -0.68: RT @kotlin: Kotlin 1.1.4 is out! Auto-generating Parcelable impls, JS dead code elimination, package-default nullability &amp; more: https://t.…

        0.2003: RT @DataInstituteSF: One year ago today we launched @DataInstituteSF! Academic Director David Uminsky reviews our foundation year: https://…

        0.0: RT @kotlinconf: We've published the list of sessions https://t.co/XHqqE4UzEy

Few more still to be announced!

        0.2732: RT @nikosvg: book review:How To Create Pragmatic, Lightweight Languages https://t.co/C2IsAtPd0N
#antlr #kotlin #perl @johnDCook
@jjmerelo
@…

        0.0: RT @DataInstituteSF: A/B Testing &amp; Beyond: Designed Experiments for Data Scientists starts Sept 6! Apply now! #datascience #abtesting  http…

        0.4939: @golovashkin I was smitten with neural nets for the 2nd round of excitement in 1980s. Small 30yr detour into parsin… https://t.co/33Aimt7Ep1

        0.0: RT @DataInstituteSF: Deep Learning Part 1 w/ @jeremyphoward &amp; @interian starts Oct 30 at our downtown SF campus. Apply now:  https://t.co/v…

        0.0: RT @munificentbob: Oh boy oh boy! The next chapter in my book is done! Functions! Closures! https://t.co/2YBJGtrn5o #craftinginterpreters

        0.6114: Excellent slides on feature engineering! https://t.co/t1OZgdISvq

        0.3802: RT @jeremyphoward: I'm chairing the DL track for the @DataInstituteSF conference. Please send me your talk ideas/proposals!
https://t.co/X3…

        0.5719: RT @DataInstituteSF: Happy to host Deep Learning Book Club tonight with @goodfellow_ian #deeplearning https://t.co/J1DEkdiOBE

        0.3687: RT @WIRED: The new programming language lets you spend more time on the interesting parts of code, and less on routine matters https://t.co…

        0.6249: RT @headinthebox: Come for the food and drinks, stay for the awesome talk by https://t.co/SG7Dz7basL.

https://t.co/fbC7TNNw8I

        0.0: RT @kotlin: KotlinConf – Speaker List Announced
https://t.co/u8CyFa9RYC https://t.co/Zti4Xo9ZQE

        0.4588: @jeremyphoward @me_develops @davegershgorn Do you mean the computational bootcamp for @usfca_analytics ? Contemplating :)

        -0.0772: @ikeough Sorry about that. I don't build that plugin though.

        0.6369: RT @DataInstituteSF: @the_antlr_guy letting the @usfca_analytics students know what super power he would want and why #msan https://t.co/v7…

        0.7003: RT @DataInstituteSF: Vice Provost @HamrickJeff inspiring the new students with his welcome to @usfca_analytics  #msan https://t.co/o4E6IZee…

        0.0: RT @flyosity: C'mon dude, really? https://t.co/SqZZ43exxl

        0.3612: RT @MCubedLondon: Want to get a grip on the basics of #machinelearning &amp; #neuralnetworks? Join @DJCordhose at #MCubed https://t.co/hN8SSmdp…

        0.4588: @LaurRil I'll stick with the vertebrates; the insects are all yours :)

        0.0: University of San Francisco term faculty position in CS available! https://t.co/P89H7wX39V @usfcs

        0.3595: RT @jeremyphoward: Or come join us at @DataInstituteSF in October and study deep learning with me in person! https://t.co/bLd3sEGiyn https:…

        0.0: RT @math_rachel: How fast.ai student @timanglade built "Not Hotdog" for HBO Silicon Valley w/ mobile TensorFlow, Keras &amp; React Native https…

        0.0: RT @pdeva: new @kotlin intellij plugin finally shows the inferred types!!! finally!! https://t.co/u4rIamomQw

        0.3802: RT @kotlin: Kotlin/Native v0.3 is out! Windows and Google Android are supported as execution targets.
Read more in the blog: https://t.co/1…

        0.3595: RT @DataInstituteSF: Early bird tix ends June 30! Get yours to join us Oct 15-17 for 70+ speakers from academia and tech #DSCO17  https://t…

        0.0: RT @DataInstituteSF: Enrolling now for Fast ML Production Systems! Course starts July 18. For more info: https://t.co/zx2JiUvgBT  #MachineL…

        0.8024: Wow. OS X Sierra has crashed 2x on me in last month. Hmm...I was kinda happy with the OS around 10.8.

        0.0: RT @jetbrains: Upsource's integration with @intellijidea means you can do code reviews inside your IDE https://t.co/GIhsK0rxSm https://t.co…

        0.3595: Just registered for @kotlin conference Nov 2-3, 2017. Join me! Keynotes by @abreslav and @headinthebox 🤓  See https://t.co/uuW7Ok1Ppv

        -0.5574: Amazon is a dead dog for last hour at least. https://t.co/O1m50eJnVc

        0.6486: @eisokant Sure, assuming you're in SF bay area :)

        0.0: @Louis_CAD @kotlin @abreslav @jetbrains I started repo https://t.co/FPIRlkkb3g to do Random Forest in Java (with tr… https://t.co/BHxlADAtfL

        0.8203: Been coding some machine learning algorithms in @kotlin last two days. I'm very impressed so far! Kudos to @abreslav and @jetbrains!

        0.5719: RT @DJCordhose: Great insights by @the_antlr_guy

'engineering is constrained by the real, physical world and software is not'

https://t…

        0.2714: RT @orangy: Programming language Kotlin jumps into the TIOBE top 50!
https://t.co/UM72vtGqHC

        0.3595: Join me at our first conference! https://t.co/drb1gu8IEG

        0.4215: @AmineMhedhbi @rustlang I'm not aware of any progress towards such a target

        0.0: RT @rakyll: https://t.co/zz2kOlTVek

        0.0: RT @AndreasStefik: Quorum 5.0 is now officially live (e.g., new site, physics, DSP)! https://t.co/SN9Ohd8f0O

        0.0: RT @gabrielkrieshok: Gah! Your gyroscope can pick up on your voice! https://t.co/rVNL7uW8Kf

        0.4939: @juristr @DJCordhose @samnewman You might enjoy https://t.co/6WbLpnL5Pe

        0.4199: Thanks for your hard translation work Daniel! https://t.co/rOtNNFBSTj

        0.1779: @ezhillang @alexthurow heh, cool. haven't looked at that stuff in a while.

        -0.0516: Damn, @LaurRil that was tasty #steak  Thank for bringing the vino etc... https://t.co/oqUZBWfP0V

        0.7345: RT @usfca_analytics: MSAN is happy to have @math_rachel join us in the classroom! https://t.co/qUOrcMVwoC

        0.0: RT @DataInstituteSF: New section of SQL starting July 24 w/ @usfca_analytics Asst Prof Nick Ross! #sql Apply now:  https://t.co/7vbAocXlNP…

        0.4588: @danfuzz You should close one eye :)

        -0.5423: RT @stevesi: The latest scientific research proves that "open plan" offices destroy your productivity. @Sales_Source https://t.co/OCxsv6A1m…

        0.0: RT @jeremyphoward: The conference website is https://t.co/X377Bm4qaA https://t.co/uVE0cBP5vk

        0.0: RT @DataInstituteSF: A new section of Deep Learning Pt 1 with @jeremyphoward and @interian starting Oct 30! #deeplearning Apply now:  https…

        0.4184: RT @DataInstituteSF: Data Institute SF Conference early bird registration is now open! Join us Oct 15-17! #DSCO17   https://t.co/qA3LGFZZDQ

        0.0: RT @DataInstituteSF: Call for talks in #deeplearning track chaired by @jeremyphoward at our conference Oct 15-17, 2017 #DSCO17 now open: ht…

        0.0: RT @DJCordhose: Demystifing Captchas https://t.co/EYWyNNe0is @pydatalondon https://t.co/2rmEzPunHf

        0.6249: RT @cytora: Great talk and insights from @DJCordhose on building neural networks for image recognition at @pydatalondon #pydataldn https://…

        0.0: RT @DataInstituteSF: Early bird registration now open for the Data Institute SF Conference October 15-17!  #DSCO17  https://t.co/qA3LGFZZDQ

        0.6249: RT @RealLordZoltan: Determined to build @RezolverIOC script proof of concept (https://t.co/Qcjz1qNYqX)
&amp; this'll help: ANTLR4 ref by @the_a…

        0.8217: Drinking from the @cliff_click firehouse yesterday at #plemm. Thanks Cliff! So awesome. https://t.co/2G1HnAhhf3

        0.8718: @headinthebox Thanks for organizing Erik! Excellent way to spend the day. :) #plemm

        0.6688: RT @DataInstituteSF: Scott Kellert @usfca_analytics alum took 2nd place in @kaggle March Machine Learning Mania 17! Congratulations!  https…

        0.0: RT @danfuzz: Retweet if 6502 Assembly was your second programming language.

        -0.3832: RT @pdeva: The Jigsaw module system in Java 9 is a complete mess and I really hope it gets rejected https://t.co/WJIdFmotEo

        0.3612: RT @RedHatNews: What will #AI look like in the future? @math_rachel has an idea to radically alter AI's development: https://t.co/VPAMm8Gem…

        0.0: @vardi @TheNextWeb Why not TypeScript?

        0.7835: RT @MadsTorgersen: @GavinBierman Nice work! Sometimes it feels a bit like we are still working together! ;-)

https://t.co/3IVKoLcRlv

        0.3182: @ruckc Sure. use the interpreter (java mode only)

        0.7269: Wow. Cool 3D neural net on MNIST images https://t.co/L6X6JGYzke

        0.0772: RT @jeremyphoward: I'm chairing DL track at @DataInstituteSF conf. I want to feature under-represented groups/research. Who would you propo…

        0.0: RT @antonarhipov: Java EE is moving to GitHub https://t.co/79vwUlR6Cm

        0.4019: @ranmocy yup. sorry :)

        0.4588: I'll be there all day Thursday Mar 4 :) https://t.co/xZeILT5z8g

        0.0: RT @usfca_analytics: Apple Co-Founder Steve Wozniak to Speak at University of San Francisco https://t.co/0klK7hym88 via @PRWeb

        0.5255: ANTLR 4 plugin 1.8.4 for @intellijidea and friends is out! A few bug fixes and includes ANTLR 4.7.

        0.0: RT @math_rachel: If you're in SF, come hear my talk "How to Learn Deep Learning (when you're not a CS PhD)" next Tues 4/11 https://t.co/JKq…

        -0.2732: RT @abreslav: You can play with a Tech Preview @Kotlin/Native; same language, but no VM. Works on on Linux/Mac/iOS/Raspberry Pi https://t.c…

        0.0: Antlr4 for C++ with CMake: A practical example by @blorente https://t.co/rEsTMFQ0Fl

        0.0: JVM Debugger Memory View for @intellijidea https://t.co/anFSfTwoyV

        0.508: ANTLR 4.7 released! Get it while it's hot! Many fixes + Full Unicode support in all targets https://t.co/HmMNcvBzzp

        -0.6124: RT @celikturgay: I just published "Solving a Performance Problem of a Mission Critical SaaS Application with ANTLR" https://t.co/HhQHUTTbnF

        0.34: RT @kennwhite: People have crowd funded $120K to purchase the browser histories of GOP politicians &amp; their families and "make them easily s…

        0.2263: RT @gsingers: Pretty sure I just unlocked some next level StringTemplate shit in @Lucidworks Fusion for joining results at query time.  @th…

        0.2942: RT @DataInstituteSF: Learn Apache Spark with our certificate program! Apply by March 23. For more info: https://t.co/owk2nQwh6c

        0.2481: @gregsohl heh, cool!

        0.0: "How to Draw Kanye using Captain Picard's Face" by @usfca_analytics student in @jeremyphoward's deep learning course https://t.co/Zpthqrr5MY

        0.0: RT @DataInstituteSF: Data Acquisition certificate w/ Terence Parr @the_antlr_guy enrolling now! Apply by March 14! For details: https://t.c…

        0.0: RT @ftomasse: The ANTLR Mega Tutorial: 34 sections to teach you everything about ANTLR @the_antlr_guy https://t.co/Ng3deyJx3v https://t.co/…

        -0.4215: Heh @AskEquifax, why no two-factor authentication? Also you just let me change my password w/o asking for the previous. #lowsecurity site

        0.0: RT @DataInstituteSF: Week 2 of #deeplearning part 2 w/ @jeremyphoward https://t.co/XlV3MCbIl5

        0.4184: RT @usfca_analytics: Join us for an MS in Analytics Info Session after this Friday's Seminar! Come meet our program director! Details: http…

        0.0: RT @DataInstituteSF: We opened up a bigger room! A few seats open for Deep Learning Pt 2 w/ @jeremyphoward starting Feb 27. Apply now: http…

        0.0: RT @jurgenvinju: Start your language engineering research engines; here's the #sle17 #cfp https://t.co/3pa99rvlwn

        0.0: RT @DataInstituteSF: Deep Learning Part 2 w/ @jeremyphoward starts Feb 27 - apply now:  https://t.co/3OXhAYmpnW  #deeplearning

        0.0: Beer + data science talks at Standard Deviant! 6-8pm 13 Feb in SF. See you there! https://t.co/Ji3AksgYU5

        0.0: RT @usfca_analytics: Spot on! 🤓🤓 https://t.co/TC42W34y8u

        0.4574: RT @DataInstituteSF: Interested in Data Acquisition? We have a certificate with @the_antlr_guy Terence Parr starting March 18! Apply now  h…

        0.3595: RT @DataInstituteSF: Join us for our SF Beer Week event 'Beer + Data Science' at Standard Deviant Brewing on Feb 13 at 6pm!  https://t.co/Z…

        0.6588: RT @math_rachel: Register for Deep Learning 2 w/ @jeremyphoward in SOMA on Mon evenings @DataInstituteSF. It will be awesome! https://t.co/…

        0.0: RT @gafter: C# language design moves to its own repo (with the spec in markdown). •https://t.co/8crPdRlTz2 and VB too •https://t.co/LOlNCbY…

        0.3595: Join me for "Beer + Data Science" 6pm Feb 13, 2017 at Standard Deviant Brewing in San Francisco! https://t.co/M0SPev0idF


text:
// Tally Votes in JavaScript Pairing Challenge.

// I worked on this challenge with:
// This challenge took me [#] hours.

// These are the votes cast by each student. Do not alter these objects here.
var votes = {
  "Alex": { president: "Bob", vicePresident: "Devin", secretary: "Gail", treasurer: "Kerry" },
  "Bob": { president: "Mary", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Cindy": { president: "Cindy", vicePresident: "Hermann", secretary: "Bob", treasurer: "Bob" },
  "Devin": { president: "Louise", vicePresident: "John", secretary: "Bob", treasurer: "Fred" },
  "Ernest": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Fred": { president: "Louise", vicePresident: "Alex", secretary: "Ivy", treasurer: "Ivy" },
  "Gail": { president: "Fred", vicePresident: "Alex", secretary: "Ivy", treasurer: "Bob" },
  "Hermann": { president: "Ivy", vicePresident: "Kerry", secretary: "Fred", treasurer: "Ivy" },
  "Ivy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Gail" },
  "John": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Kerry" },
  "Kerry": { president: "Fred", vicePresident: "Mary", secretary: "Fred", treasurer: "Ivy" },
  "Louise": { president: "Nate", vicePresident: "Alex", secretary: "Mary", treasurer: "Ivy" },
  "Mary": { president: "Louise", vicePresident: "Oscar", secretary: "Nate", treasurer: "Ivy" },
  "Nate": { president: "Oscar", vicePresident: "Hermann", secretary: "Fred", treasurer: "Tracy" },
  "Oscar": { president: "Paulina", vicePresident: "Nate", secretary: "Fred", treasurer: "Ivy" },
  "Paulina": { president: "Louise", vicePresident: "Bob", secretary: "Devin", treasurer: "Ivy" },
  "Quintin": { president: "Fred", vicePresident: "Hermann", secretary: "Fred", treasurer: "Bob" },
  "Romanda": { president: "Louise", vicePresident: "Steve", secretary: "Fred", treasurer: "Ivy" },
  "Steve": { president: "Tracy", vicePresident: "Kerry", secretary: "Oscar", treasurer: "Xavier" },
  "Tracy": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Ullyses": { president: "Louise", vicePresident: "Hermann", secretary: "Ivy", treasurer: "Bob" },
  "Valorie": { president: "Wesley", vicePresident: "Bob", secretary: "Alex", treasurer: "Ivy" },
  "Wesley": { president: "Bob", vicePresident: "Yvonne", secretary: "Valorie", treasurer: "Ivy" },
  "Xavier": { president: "Steve", vicePresident: "Hermann", secretary: "Fred", treasurer: "Ivy" },
  "Yvonne": { president: "Bob", vicePresident: "Zane", secretary: "Fred", treasurer: "Hermann" },
  "Zane": { president: "Louise", vicePresident: "Hermann", secretary: "Fred", treasurer: "Mary" }
}

// Tally the votes in voteCount.
var voteCount = {
  president: {},
  vicePresident: {},
  secretary: {},
  treasurer: {}
}

/* The name of each student receiving a vote for an office should become a property
of the respective office in voteCount.  After Alex's votes have been tallied,
voteCount would be ...
  var voteCount = {
    president: { Bob: 1 },
    vicePresident: { Devin: 1 },
    secretary: { Gail: 1 },
    treasurer: { Kerry: 1 }
  }
*/

/* Once the votes have been tallied, assign each officer position the name of the
student who received the most votes. */
var officers = {
  president: undefined,
  vicePresident: undefined,
  secretary: undefined,
  treasurer: undefined
}

// Pseudocode
// 1. Create a for in loop to iterate over all of the votes in each catagory
// 2. Set that category in voteCount to contain the name and how many times it appears
// 3. iterate through voteCount results
// 4. assign students with the most votes to their corresponding office.

// __________________________________________
// // Initial Solution
// for(var voter in votes){
//   voteCount["president"][votes[voter]["president"]] = 0;
//   voteCount["vicePresident"][votes[voter]["vicePresident"]] = 0;
//   voteCount["secretary"][votes[voter]["secretary"]] = 0;
//   voteCount["treasurer"][votes[voter]["treasurer"]] = 0;
// }
//  for(var voter in votes){
//    voteCount["president"][votes[voter]["president"]] += 1;
//    voteCount["vicePresident"][votes[voter]["vicePresident"]] += 1;
//    voteCount["secretary"][votes[voter]["secretary"]] += 1;
//    voteCount["treasurer"][votes[voter]["treasurer"]] += 1;
//  }
// var currWinner = 0;
// for(var name in voteCount["president"]){
//     if (voteCount["president"][name] > currWinner){
//       currWinner = voteCount["president"][name];
//       officers["president"] = name;
//     }
// }

// for(var name in voteCount["vicePresident"]){
//     if (voteCount["vicePresident"][name] > currWinner){
//       currWinner = voteCount["vicePresident"][name];
//       officers["vicePresident"] = name;
//     }
// }

// for(var name in voteCount["secretary"]){
//     if (voteCount["secretary"][name] > currWinner){
//       currWinner = voteCount["secretary"][name];
//       officers["secretary"] = name;
//     }
// }
// currWinner = 0;
// for(var name in voteCount["treasurer"]){
//     if (voteCount["treasurer"][name] > currWinner){
//       currWinner = voteCount["treasurer"][name];
//       officers["treasurer"] = name;
//     }
// }
//console.log(voteCount);
//console.log(officers);

// console.log(voteCount);
// // __________________________________________
// Refactored Solution

for(var student in votes){
  for(var position in votes[student]){
    voteCount[position][votes[student][position]]=0;
 }
}
for(var student in votes){
  for(var position in votes[student]){
    voteCount[position][votes[student][position]] += 1;
 }
}
for (var position in voteCount){
  var currWinner = 0;
  for(var name in voteCount[position]){
    if (voteCount[position][name] > currWinner){
      currWinner = voteCount[position][name];
      officers[position] = name;
    }
  }
}

// __________________________________________
// Reflection
// What did you learn about iterating over nested objects in JavaScript?
// Everything. Liam was so patient and kind and I really felt like I got things, you know? It's funny when you spend time doing things on your own and pairing makes you learn more. I guess that's why I like it so much. I also got the hang of calling on objects within objects. It wasn't easy but we figured it out.
// Were you able to find useful methods to help you with this?
// I'd never used a for in loop and so it was really great to be able to implement it and understand it. We got it down pretty well.
// What concepts were solidified in the process of working through this challenge?
// How to find things in nested objects. I feel WAY better about that now. I also feel WAY better about constantly console.log -ing things because it REALLY helped. I had fun even if I struggled.

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (voteCount.president["Bob"] === 3),
  "Bob should receive three votes for President.",
  "1. "
)

assert(
  (voteCount.vicePresident["Bob"] === 2),
  "Bob should receive two votes for Vice President.",
  "2. "
)

assert(
  (voteCount.secretary["Bob"] === 2),
  "Bob should receive two votes for Secretary.",
  "3. "
)

assert(
  (voteCount.treasurer["Bob"] === 4),
  "Bob should receive four votes for Treasurer.",
  "4. "
)

assert(
  (officers.president === "Louise"),
  "Louise should be elected President.",
  "5. "
)

assert(
  (officers.vicePresident === "Hermann"),
  "Hermann should be elected Vice President.",
  "6. "
)

assert(
  (officers.secretary === "Fred"),
  "Fred should be elected Secretary.",
  "7. "
)

assert(
  (officers.treasurer === "Ivy"),
  "Ivy should be elected Treasurer.",
  "8. "
)