text:
A work in progress.

For now, check out this literate, streamless MicroKanren implementation in Haskell: [MicroKanren.lhs](doc/MicroKanren.md)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GSocketControlMessage</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="index.html" title="GIO Reference Manual">
<link rel="up" href="networking.html" title="Low-level network support">
<link rel="prev" href="GUnixSocketAddress.html" title="GUnixSocketAddress">
<link rel="next" href="GUnixFDList.html" title="GUnixFDList">
<meta name="generator" content="GTK-Doc V1.19 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

GIO Reference Manual

Top
                   |
                  Description
                   |
                  Object Hierarchy

GSocketControlMessage

GSocketControlMessage — A GSocket control message

Synopsis

                    GSocketControlMessage;
GSocketControlMessage * g_socket_control_message_deserialize
                                                        (int level,
                                                         int type,
                                                         gsize size,
                                                         gpointer data);
int                 g_socket_control_message_get_level  (GSocketControlMessage *message);
int                 g_socket_control_message_get_msg_type
                                                        (GSocketControlMessage *message);
gsize               g_socket_control_message_get_size   (GSocketControlMessage *message);
void                g_socket_control_message_serialize  (GSocketControlMessage *message,
                                                         gpointer data);

Object Hierarchy

  GObject
   +----GSocketControlMessage
         +----GUnixFDMessage
         +----GUnixCredentialsMessage

Description

A GSocketControlMessage is a special-purpose utility message that
can be sent to or received from a GSocket. These types of
messages are often called "ancillary data".

The message can represent some sort of special instruction to or
information from the socket or can represent a special kind of
transfer to the peer (for example, sending a file description over
a UNIX socket).

These messages are sent with g_socket_send_message() and received
with g_socket_receive_message().

To extend the set of control message that can be sent, subclass this
class and override the get_size, get_level, get_type and serialize
methods.

To extend the set of control messages that can be received, subclass
this class and implement the deserialize method. Also, make sure your
class is registered with the GType typesystem before calling
g_socket_receive_message() to read such a message.

Details

GSocketControlMessage

typedef struct _GSocketControlMessage GSocketControlMessage;

Base class for socket-type specific control messages that can be sent and
received over GSocket.

g_socket_control_message_deserialize ()

GSocketControlMessage * g_socket_control_message_deserialize
                                                        (int level,
                                                         int type,
                                                         gsize size,
                                                         gpointer data);

Tries to deserialize a socket control message of a given
level and type. This will ask all known (to GType) subclasses
of GSocketControlMessage if they can understand this kind
of message and if so deserialize it into a GSocketControlMessage.

If there is no implementation for this kind of control message, NULL
will be returned.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

level :

a socket level

type :

a socket control message type for the given level

size :

the size of the data in bytes

data :

pointer to the message data. [<acronym title="Parameter points to an array of items.">array</acronym> length=size][<acronym title="Generics and defining elements of containers and arrays.">element-type</acronym> guint8]

Returns :

the deserialized message or NULL. [<acronym title="Free data after the code is done.">transfer full</acronym>]

Since 2.22

g_socket_control_message_get_level ()

int                 g_socket_control_message_get_level  (GSocketControlMessage *message);

Returns the "level" (i.e. the originating protocol) of the control message.
This is often SOL_SOCKET.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

message :

a GSocketControlMessage

Returns :

an integer describing the level

Since 2.22

g_socket_control_message_get_msg_type ()

int                 g_socket_control_message_get_msg_type
                                                        (GSocketControlMessage *message);

Returns the protocol specific type of the control message.
For instance, for UNIX fd passing this would be SCM_RIGHTS.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

message :

a GSocketControlMessage

Returns :

an integer describing the type of control message

Since 2.22

g_socket_control_message_get_size ()

gsize               g_socket_control_message_get_size   (GSocketControlMessage *message);

Returns the space required for the control message, not including
headers or alignment.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

message :

a GSocketControlMessage

Returns :

The number of bytes required.

Since 2.22

g_socket_control_message_serialize ()

void                g_socket_control_message_serialize  (GSocketControlMessage *message,
                                                         gpointer data);

Converts the data in the message to bytes placed in the
message.

data is guaranteed to have enough space to fit the size
returned by g_socket_control_message_get_size() on this
object.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

message :

a GSocketControlMessage

data :

A buffer to write data to

Since 2.22

See Also

GSocket.

          Generated by GTK-Doc V1.19

redpajama_set_name: RedPajamaGithub


text:
// This file is automatically generated.

package adila.db;

/*
 * LG Optimus Hub
 *
 * DEVICE: lgc800g
 * MODEL: LG-C800G
 */
final class lgc800g {
    public static final String DATA = "LG|Optimus Hub|";
}


text:
import { getEmbeddedVariable } from "@utils/Configuration";

export function getBasePath() {
    return getEmbeddedVariable("basepath");
}


text:
```
protractor --elementExplorer
# Then browser.get('http://mywebsite.com')
# Then element(by.css('div#mySelector')).getText() or whatever you want to do with the element
```

[Protractor Debugging Tips Page](https://github.com/angular/protractor/blob/master/docs/debugging.md)


text:
{% import theme('_menu.html') as menu with context -%}
<!doctype html>
<html lang="en">
<head>
    <base href="{{request.url_root}}">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="theme-color" content="#101212">

    {% block seo_meta %}
    <meta name="description" content="{{Config.get('site', 'site_description')}}">
    <meta name="keywords" content="{{Config.get('site', 'site_keywords')}}">
    {% endblock %}

    {% block meta %}{% endblock %}
    {%if content %}
      <link rel="canonical" href="{{content.get_canonical_url()}}"/>
      <meta name="author" content="{{content.created_by.display_name}}">
    {% elif channel %}
      <meta name="author" content="{{Config.get('site', 'site_author')}}">
      <link rel="canonical" href="{{channel.get_canonical_url()}}"/>
      <link rel="alternate" type="application/atom+xml" title="{{ channel.title|title }} Posts (Atom 0.3)" href="{{url_for('atom_list', long_slug=channel.long_slug)}}">
      <link rel="alternate" type="application/rss+xml" title="{{ channel.title|title }} Posts (RSS 2.0)" href="{{ url_for('rss_list', long_slug=channel.long_slug) }}">
    {% endif %}
    <link rel="icon" type="image/x-icon" href="{{theme_static('favicon.ico')}}" />
    <link rel="shortcut icon" href="{{theme_static('favicon.ico')}}">

    <title>{%block title%}{{Config.get('site', 'site_name', 'The Happiest CMS in the World')}}{% endblock %}</title>
    {% block head %}
    {% endblock head %}

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/pure/0.6.0/pure-min.css">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="{{theme_static('css/pure.css')}}">
    <link rel="stylesheet" href="{{theme_static('css/custom.css')}}">
    {% block head_css %}{% endblock %}
    {% block head_js %}{% endblock %}
    {% include theme('analytics.html') %}

    {% with %}
        {% set g_s_v = Config.get('site', 'google-site-verification')%}
        {% if g_s_v %}
        <meta name="google-site-verification" content="{{g_s_v}}" />
        {% endif %}
    {% endwith %}
</head>

<body>
    {% block content %}
    {% endblock %}

    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    {% block bottom_js %}{% endblock %}
    {% block js_footer %}{% endblock %}
    <script>
        var $top = $('.go-top');

        // Show or hide the sticky footer button
        $(window).scroll(function() {
            if ($(this).scrollTop() > 200) {
                $top.fadeIn(200);
            } else {
                $top.fadeOut(200);
            }
        });

        // Animate the scroll to top
        $top.click(function(event) {
            event.preventDefault();
            $('html, body').animate({scrollTop: 0}, 300);
        })

        // Makes sure that the href="#" attached to the <a> elements
        // don't scroll you back up the page.
        $('body').on('click', 'a[href="#"]', function(event) {
            event.preventDefault();
        });
    </script>
</body>
</html>


text:
#pragma once

#include "physics/rotating_body.hpp"

#include <algorithm>
#include <optional>
#include <vector>

#include "geometry/grassmann.hpp"
#include "geometry/r3_element.hpp"
#include "geometry/rotation.hpp"
#include "physics/oblate_body.hpp"
#include "quantities/constants.hpp"
#include "quantities/si.hpp"

namespace principia {
namespace physics {
namespace internal_rotating_body {

using geometry::Cross;
using geometry::DefinesFrame;
using geometry::EulerAngles;
using geometry::Exp;
using geometry::NormalizeOrZero;
using geometry::RadiusLatitudeLongitude;
using geometry::SphericalCoordinates;
using quantities::SIUnit;
using quantities::si::Radian;

template<typename Frame>
RotatingBody<Frame>::Parameters::Parameters(
    Length const& min_radius,
    Length const& mean_radius,
    Length const& max_radius,
    Angle const& reference_angle,
    Instant const& reference_instant,
    AngularFrequency const& angular_frequency,
    Angle const& right_ascension_of_pole,
    Angle const& declination_of_pole)
    : min_radius_(min_radius),
      mean_radius_(mean_radius),
      max_radius_(max_radius),
      reference_angle_(reference_angle),
      reference_instant_(reference_instant),
      angular_frequency_(angular_frequency),
      right_ascension_of_pole_(right_ascension_of_pole),
      declination_of_pole_(declination_of_pole) {
  CHECK_NE(angular_frequency_, 0.0 * SIUnit<AngularFrequency>())
      << "Rotating body cannot have zero angular velocity";
}

template<typename Frame>
RotatingBody<Frame>::Parameters::Parameters(
    Length const& mean_radius,
    Angle const& reference_angle,
    Instant const& reference_instant,
    AngularFrequency const& angular_frequency,
    Angle const& right_ascension_of_pole,
    Angle const& declination_of_pole)
    : Parameters(mean_radius, mean_radius, mean_radius,
                 reference_angle,
                 reference_instant,
                 angular_frequency,
                 right_ascension_of_pole,
                 declination_of_pole) {}

template<typename Frame>
RotatingBody<Frame>::RotatingBody(
    MassiveBody::Parameters const& massive_body_parameters,
    Parameters const& parameters)
    : MassiveBody(massive_body_parameters),
      parameters_(parameters),
      polar_axis_(RadiusLatitudeLongitude(
                      1.0,
                      parameters.declination_of_pole_,
                      parameters.right_ascension_of_pole_).ToCartesian()),
      biequatorial_(RadiusLatitudeLongitude(
                        1.0,
                        0 * Radian,
                        π / 2 * Radian +
                            parameters.right_ascension_of_pole_).ToCartesian()),
      equatorial_(Wedge(biequatorial_, polar_axis_).coordinates()),
      angular_velocity_(polar_axis_.coordinates() *
                        parameters.angular_frequency_) {}

template<typename Frame>
Length RotatingBody<Frame>::min_radius() const {
  return parameters_.min_radius_;
}

template<typename Frame>
Length RotatingBody<Frame>::mean_radius() const {
  return parameters_.mean_radius_;
}

template<typename Frame>
Length RotatingBody<Frame>::max_radius() const {
  return parameters_.max_radius_;
}

template<typename Frame>
Vector<double, Frame> const& RotatingBody<Frame>::polar_axis() const {
  return polar_axis_;
}

template<typename Frame>
Vector<double, Frame> const& RotatingBody<Frame>::biequatorial() const {
  return biequatorial_;
}

template<typename Frame>
Vector<double, Frame> const& RotatingBody<Frame>::equatorial() const {
  return equatorial_;
}

template<typename Frame>
Angle const& RotatingBody<Frame>::right_ascension_of_pole() const {
  return parameters_.right_ascension_of_pole_;
}

template<typename Frame>
Angle const& RotatingBody<Frame>::declination_of_pole() const {
  return parameters_.declination_of_pole_;
}

template<typename Frame>
AngularFrequency const& RotatingBody<Frame>::angular_frequency() const {
  return parameters_.angular_frequency_;
}

template<typename Frame>
AngularVelocity<Frame> const& RotatingBody<Frame>::angular_velocity() const {
  return angular_velocity_;
}

template<typename Frame>
Angle RotatingBody<Frame>::AngleAt(Instant const& t) const {
  return parameters_.reference_angle_ +
         (t - parameters_.reference_instant_) * parameters_.angular_frequency_;
}

template<typename Frame>
Rotation<Frame, Frame> RotatingBody<Frame>::RotationAt(Instant const& t) const {
  return Exp((t - parameters_.reference_instant_) * angular_velocity_);
}

template<typename Frame>
bool RotatingBody<Frame>::is_massless() const {
  return false;
}

template<typename Frame>
bool RotatingBody<Frame>::is_oblate() const {
  return false;
}

template<typename Frame>
void RotatingBody<Frame>::WriteToMessage(
    not_null<serialization::Body*> const message) const {
  WriteToMessage(message->mutable_massive_body());
}

template<typename Frame>
void RotatingBody<Frame>::WriteToMessage(
    not_null<serialization::MassiveBody*> const message) const {
  MassiveBody::WriteToMessage(message);
  not_null<serialization::RotatingBody*> const rotating_body =
      message->MutableExtension(serialization::RotatingBody::extension);
  Frame::WriteToMessage(rotating_body->mutable_frame());
  parameters_.min_radius_.WriteToMessage(
      rotating_body->mutable_min_radius());
  parameters_.mean_radius_.WriteToMessage(
      rotating_body->mutable_mean_radius());
  parameters_.max_radius_.WriteToMessage(
      rotating_body->mutable_max_radius());
  parameters_.reference_angle_.WriteToMessage(
      rotating_body->mutable_reference_angle());
  parameters_.reference_instant_.WriteToMessage(
      rotating_body->mutable_reference_instant());
  parameters_.angular_frequency_.WriteToMessage(
      rotating_body->mutable_angular_frequency());
  parameters_.right_ascension_of_pole_.WriteToMessage(
      rotating_body->mutable_right_ascension_of_pole());
  parameters_.declination_of_pole_.WriteToMessage(
      rotating_body->mutable_declination_of_pole());
}

template<typename Frame>
not_null<std::unique_ptr<RotatingBody<Frame>>>
RotatingBody<Frame>::ReadFromMessage(
    serialization::RotatingBody const& message,
    MassiveBody::Parameters const& massive_body_parameters) {
  bool is_pre_del_ferro = !message.has_min_radius() &&
                          !message.has_max_radius();
  std::optional<Parameters> parameters;
  if (is_pre_del_ferro) {
    Length const mean_radius = Length::ReadFromMessage(message.mean_radius());
    Length const min_radius = mean_radius;
    Length const max_radius = mean_radius;
    parameters.emplace(
        min_radius,
        mean_radius,
        max_radius,
        Angle::ReadFromMessage(message.reference_angle()),
        Instant::ReadFromMessage(message.reference_instant()),
        AngularFrequency::ReadFromMessage(message.angular_frequency()),
        Angle::ReadFromMessage(message.right_ascension_of_pole()),
        Angle::ReadFromMessage(message.declination_of_pole()));
  } else {
    parameters.emplace(
        Length::ReadFromMessage(message.min_radius()),
        Length::ReadFromMessage(message.mean_radius()),
        Length::ReadFromMessage(message.max_radius()),
        Angle::ReadFromMessage(message.reference_angle()),
        Instant::ReadFromMessage(message.reference_instant()),
        AngularFrequency::ReadFromMessage(message.angular_frequency()),
        Angle::ReadFromMessage(message.right_ascension_of_pole()),
        Angle::ReadFromMessage(message.declination_of_pole()));
  }

  if (message.HasExtension(serialization::OblateBody::extension)) {
    serialization::OblateBody const& extension =
        message.GetExtension(serialization::OblateBody::extension);
    return OblateBody<Frame>::ReadFromMessage(extension,
                                              massive_body_parameters,
                                              *parameters);
  } else {
    return std::make_unique<RotatingBody<Frame>>(massive_body_parameters,
                                                 *parameters);
  }
}

}  // namespace internal_rotating_body
}  // namespace physics
}  // namespace principia


text:
/*
 * BlueBlock.cpp
 *
 *  Created on: Apr 4, 2016
 *      Author: Tobie
 */

#include "../../include/model/BlueBlock.h"

BlueBlock::BlueBlock() {
	this->rectangle = Rect(0,0,0,0);
	this->center.x = 0;
	this->center.y = 0;
	this->area = 0;
}

BlueBlock::~BlueBlock() {
	//Do nothing
}

double BlueBlock::getArea() {
	return area;
}

Point2D BlueBlock::getCenter() {
	return center;
}

Point2D BlueBlock::getCenterDst() {
	return centerDst;
}

Rect BlueBlock::getRectangle() {
	return rectangle;
}

void BlueBlock::setRectangle(Rect rectangle) {
	this->rectangle = rectangle;

	this->center.x = this->rectangle.x
					+ (this->rectangle.width / 2);
	this->center.y = this->rectangle.y
					+ (this->rectangle.height / 2);
	this->area = this->rectangle.area();
}


text:
package com.geth1b.coding.skills.cc150.ood.BookReader;

/**
 * @author geth1b
 */
public enum Category {
  ARTS, BUSINESS, COOKING, HISTORY, SCIENCE;
}


text:
package edu.stanford.graphics.shapenet

import edu.stanford.graphics.shapenet.util.WebUtils
import com.jme3.math._
import java.awt.Color
import jme3dae.utilities.MatrixUtils

/**
 * Wrapper around JME3 engine
 * @author Angel Chang
 */
package object jme3 {
  val ZERO_TOLERANCE = 1e-06f
  val HALF_XYZ = new Vector3f(0.5f, 0.5f, 0.5f)

  implicit def javaColorToColorRGBA(color: Color): ColorRGBA = {
    new ColorRGBA(color.getRed/255.0f, color.getGreen/255.0f, color.getBlue/255.0f, color.getAlpha/255.0f)
  }
  implicit def colorRGBAToJavaColor(color: ColorRGBA): Color = {
    new Color(color.asIntRGBA(), true)
  }

  implicit def vector3fToArray(v: Vector3f): Array[Double] = {
    if (v != null)
      Array[Double](v.getX, v.getY, v.getZ)
    else null
  }
  def arrayToVector3f(v: Array[Double]) = {
    if (v != null)
      new Vector3f(v(0).toFloat, v(1).toFloat, v(2).toFloat)
    else null
  }

  implicit def safeDivide(v1: Vector3f, v2: Vector3f): Vector3f = {
    val x = if (v2.x > 0) v1.x/v2.x else v1.x
    val y = if (v2.y > 0) v1.y/v2.y else v1.y
    val z = if (v2.z > 0) v1.z/v2.z else v1.z
    new Vector3f(x,y,z)
  }

  implicit def stringToVector3f(s: String): Vector3f = {
    if (s == null || s.trim.isEmpty) null
    else {
      var vs = s.trim
      if (vs.charAt(0) == '(') vs = vs.substring(1)
      if (vs.charAt(vs.length-1) == ')') vs = vs.substring(0, vs.length-1)
      val nums = vs.split(",").map( x => x.trim.toFloat )
      if (nums.length == 3) {
        new Vector3f(nums(0), nums(1), nums(2))
      } else {
        throw new IllegalArgumentException("Invalid vector3f format: " + s)
      }
    }
  }

  def stringToMatrix4f(str: String): Matrix4f = {
    if (str == null || str.trim.isEmpty) return  null
    val mat = new Matrix4f()
    val rows = str.split("\\n+").filter( s => s.trim().length > 0 )
    assert(rows.size == 4)
    for (i <- 0 until 4) {
      val cols = rows(i).split("\\s+")
      assert(cols.size == 4)
      for (j <- 0 until 4) {
        mat.set(i,j,cols(j).toFloat)
      }
    }
    mat
  }

  def jsonArrayStringToMatrix4f(str: String): Matrix4f = {
    if (str == null || str.trim.isEmpty) return  null
    val trimmed = str.replaceAll("[\\[\\]]","").trim()
    val elements = trimmed.split("\\s*,\\s*")
    assert(elements.size == 16)
    arrayToMatrix(elements.map( x => x.toFloat))
  }

  def loadMatrix4f(filename: String): Option[Matrix4f] = {
    val matrixStr = WebUtils.loadString(filename)
    matrixStr.map( s => stringToMatrix4f(s) )
  }

  def matrixToTransform( m: Matrix4f ): Transform = {
    // There is a slight bug in the matrix4f.toRotationQuat in that it doesn't normalize
    // so we don't use that function
    MatrixUtils.matrix4fToTransform(m)
    //val quatRot = new Quaternion()
    //quatRot.fromRotationMatrix(m.toRotationMatrix.normalizeLocal())
    //new Transform(m.toTranslationVector,quatRot, m.toScaleVector)
  }

  def transformToMatrix( t: Transform ): Matrix4f = {
    MatrixUtils.transformToMatrix4f(t)
//    val m = new Matrix4f()
//    m.setTransform( t.getTranslation, t.getScale, t.getRotation.toRotationMatrix )
//    m
  }

  def arrayToTransform( ta: Array[Float] ): Transform = matrixToTransform( new Matrix4f(ta) )
  def transformToArray(t: Transform): Array[Float] = {
    val m = transformToMatrix(t)
    val array = Array.ofDim[Float](16)
    // array is columnMajor
    m.get(array, /* rowMajor = */ false)
    array
  }
  def matrixToArray( m: Matrix4f): Array[Float] = {
    val array = Array.ofDim[Float](16)
    // array is columnMajor
    m.get(array, /* rowMajor = */ false)
    array
  }
  def arrayToMatrix( v: Array[Float]): Matrix4f = {
    val m = new Matrix4f()
    // array is columnMajor
    m.set(v, /*rowMajor = */ false)
    m
  }

  def getInverse(t: Transform): Transform = {
    val m = new Matrix4f()

    m.setTransform( t.getTranslation, t.getScale, t.getRotation.toRotationMatrix )
    val inv = m.invert()
    matrixToTransform(inv)
  }

  def abs(v: Vector3f): Vector3f = {
    new Vector3f(math.abs(v.x), math.abs(v.y), math.abs(v.z))
  }

  case class EnrichedVector3f(v: Vector3f) {
    def +(o: Vector3f) = v.add(o)
    def -(o: Vector3f) = v.subtract(o)
    def *(s: Number) = v.mult(s.floatValue())
    def /(s: Number) = v.mult(1.0f / s.floatValue())
    def unitCross(o: Vector3f) = {
      v.cross(o).normalizeLocal()
    }
    def abs() = new Vector3f(math.abs(v.x), math.abs(v.y), math.abs(v.z))
  }
  implicit def Vector3fToEnrichedVector3f(v: Vector3f) = EnrichedVector3f(v)
  implicit def EnrichedVector3fToVector3f(v: EnrichedVector3f) = v.v

  case class EnrichedTriangle(t: Triangle) {
    // Returns the edge between vertices i0 and i1 as a segment
    def getEdgeSegment(i0: Int, i1: Int) = {
      val segment = new LineSegment()
      val dir = t.get(i1) - t.get(i0)
      val length = dir.length()
      segment.setOrigin( (t.get(i0) + t.get(i1)).mult(0.5f) )
      segment.setDirection( dir.normalizeLocal() )
      segment.setExtent( 0.5f*length )
      segment
    }
  }
  implicit def TriangleToEnrichedTriangle(t: Triangle) = EnrichedTriangle(t)
  implicit def EnrichedTriangleToTriangle(t: EnrichedTriangle) = t.t
}


text:
title: Use GoAccess to analyze your Amazon S3 logs
date: 2013-01-08
tags: [tool]
abstract: Just provide the correct format!

[GoAccess](http://goaccess.prosoftcorp.com/) is a neat tool to analyze any kind of web log fastly and even real-time. It supports out-of-the-box logs written in the following log format:

- Common Log Format (CLF) Apache
- Combined Log Format (XLF/ELF) Apache
- W3C format (IIS).
- Apache virtual hosts

Unluckly Amazon S3 uses a different log format, but with GoAccess it's not a problem since it can be configured to any custom format. How?

The [manpage](http://goaccess.prosoftcorp.com/man) lists the available parameters to define a custom log format, but I found nowhere a string compatible with Amazon S3 logs. With a little trial and error, here is a format that works:

`%^ %^ [%d:%^] %h %^ %^ %^ %^ "%^ %r %^" %s %^ %b %^ %^ %^ "%^" "%u" %^`

If you want to make it the default for every GoAccess run, edit (or create) a `~/.goaccessrc` file like this:

<?prettify?>

    date_format %d/%b/%Y
    log_format %^ %^ [%d:%^] %h %^ %^ %^ %^ "%^ %r %^" %s %^ %b %^ %^ %^ "%^" "%u" %^


text:
<?php

namespace phpManufaktur\Event\Data\Setup;

use Silex\Application;
use phpManufaktur\Event\Data\Event\Event;
use phpManufaktur\Event\Data\Event\Group;
use phpManufaktur\Event\Data\Event\Description;
use phpManufaktur\Event\Data\Event\ExtraType;
use phpManufaktur\Event\Data\Event\Extra;
use phpManufaktur\Event\Data\Event\ExtraGroup;
use phpManufaktur\Event\Data\Event\OrganizerTag;
use phpManufaktur\Event\Data\Event\LocationTag;
use phpManufaktur\Event\Data\Event\ParticipantTag;
use phpManufaktur\Basic\Control\CMS\UninstallAdminTool;
use phpManufaktur\Event\Data\Event\Images;
use phpManufaktur\Event\Data\Event\Subscription;
use phpManufaktur\Event\Data\Event\Propose;
use phpManufaktur\Event\Data\Event\RecurringEvent;

class Uninstall
{

    protected $app = null;

    public function exec(Application $app)
    {
        try {
            $Group = new Group($app);
            $Group->dropTable();

            $Event = new Event($app);
            $Event->dropTable();

            $Description = new Description($app);
            $Description->dropTable();

            $ExtraType = new ExtraType($app);
            $ExtraType->dropTable();

            $ExtraGroup = new ExtraGroup($app);
            $ExtraGroup->dropTable();

            $Extra = new Extra($app);
            $Extra->dropTable();

            $OrganizerTag = new OrganizerTag($app);
            $OrganizerTag->dropTable();

            $LocationTag = new LocationTag($app);
            $LocationTag->dropTable();

            $ParticipantTag = new ParticipantTag($app);
            $ParticipantTag->dropTable();

            $Images = new Images($app);
            $Images->dropTable();

            $Subscription = new Subscription($app);
            $Subscription->dropTable();

            $Propose = new Propose($app);
            $Propose->dropTable();

            $RecurringEvent = new RecurringEvent($app);
            $RecurringEvent->dropTable();

            // uninstall kit_framework_event from the CMS
            $admin_tool = new UninstallAdminTool($app);
            $admin_tool->exec(MANUFAKTUR_PATH.'/Event/extension.json');

            $app['monolog']->addInfo('[Event Uninstall] Dropped all tables successfull');
            return $app['translator']->trans('Successfull uninstalled the extension %extension%.',
                array('%extension%' => 'Event'));
        } catch (\Exception $e) {
            throw new \Exception($e);
        }
    }
}


text:
RSpec::Matchers.define :have_subject do |expected_subject|
  match do |mailer|
    mailer_subject(mailer) == expected_subject
  end

  failure_message do |actual|
    <<-MESSAGE.strip_heredoc
    Expected subject: #{mailer_subject(mailer).inspect} to be: #{expected_subject.inspect}.
  MESSAGE
  end

  failure_message_when_negated do |actual|
    <<-MESSAGE.strip_heredoc
    Expected subject: #{mailer_subject(mailer).inspect} to not be: #{expected_subject.inspect}.
  MESSAGE
  end

  description do
    "be the same subject as #{expected_subject.inspect}"
  end

  def mailer_subject(mailer)
    mailer.message['subject']
  end
end


text:
require 'rspec/expectations'

RSpec::Matchers.define :have_a_switch do |name, param, default|
  match do |page|
    param = param.to_s
    btn = page.find_link name

    uri = URI(btn[:href])
    params = Hash[URI.decode_www_form(uri.query)]

    param_matches = default ? !params.has_key?(param) : params[param] == '1'
    param_matches
  end

  failure_message do |page|
    "expected #{page.current_scope.tag_name} to have a switch named #{name} for param #{param}, checked: #{default}"
  end
end

RSpec::Matchers.define :have_a_search_field do |name, param|
  match do |page|
    param = param.to_s
    field = page.find_field name

    field[:name] == param.to_s
  end

  failure_message do |page|
    "expected #{page.current_scope.tag_name} to have a search field #{name} for param #{param}"
  end
end

RSpec::Matchers.define :have_a_page_header do |header|
  match do |page|
    h2 = page.find '.page-heading h2'

    @actual = h2.text
    header == @actual
  end

  diffable
end

RSpec::Matchers.define :have_breadcrumbs do |current, crumbs|
  match do |page|
    breadcrumb = page.find '.page-heading ol.breadcrumb'

    links = breadcrumb.find_all('li a').each_with_object({}) do |link, h|
      name = link.text
      href = link[:href]

      h[name] = URI(href).path
    end
    links[:current] = breadcrumb.find('li.active strong').text

    @actual = links

    links == crumbs.stringify_keys.transform_values { |v| URI(v).path }.merge(current: current)
  end

  diffable
end

RSpec::Matchers.define :have_row_action do |url_args, icon|
  match do |page|
    url = url.is_a?(String) ? url_args : polymorphic_url(url_args, routing_type: :path)
    link = page.find(:xpath, ".//a[@href='#{url}']")
    link.find "i.fa.fa-#{icon.to_s.gsub('_', '-')}"
  end
end

RSpec::Matchers.define :have_columns do |*column_classes|
  match do |page|
    page.within 'thead tr' do
      column_classes.each do |col|
        page.find "th.#{col}"
      end
    end
  end
end


text:
' *****************************************************************************
'
'  Copyright 2004, Weifen Luo
'  All rights reserved. The software and associated documentation
'  supplied hereunder are the proprietary information of Weifen Luo
'  and are supplied subject to licence terms.
'
'  WinFormsUI Library Version 1.0
' *****************************************************************************
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports System.ComponentModel
Imports System.Drawing.Drawing2D
Imports WeifenLuo.WinFormsUI

Namespace UI.Docking
    <ToolboxItem(False)> _
    Public Class AutoHideStripFromBase
        Inherits AutoHideStripBase
        Private Const _ImageHeight As Integer = 16
        Private Const _ImageWidth As Integer = 16
        Private Const _ImageGapTop As Integer = 2
        Private Const _ImageGapLeft As Integer = 4
        Private Const _ImageGapRight As Integer = 4
        Private Const _ImageGapBottom As Integer = 2
        Private Const _TextGapLeft As Integer = 4
        Private Const _TextGapRight As Integer = 10
        Private Const _TabGapTop As Integer = 3
        Private Const _TabGapLeft As Integer = 2
        Private Const _TabGapBetween As Integer = 10
        Private Shared _stringFormatTabHorizontal As StringFormat
        Private Shared _stringFormatTabVertical As StringFormat
        Private Shared _matrixIdentity As Matrix
        Private Shared _dockStates As DockState()
#Region "Customizable Properties"
        Protected Overridable ReadOnly Property StringFormatTabHorizontal() As StringFormat
            Get
                Return _stringFormatTabHorizontal
            End Get
        End Property
        Protected Overridable ReadOnly Property StringFormatTabVertical() As StringFormat
            Get
                Return _stringFormatTabVertical
            End Get
        End Property
        Protected Overridable ReadOnly Property ImageHeight() As Integer
            Get
                Return _ImageHeight
            End Get
        End Property
        Protected Overridable ReadOnly Property ImageWidth() As Integer
            Get
                Return _ImageWidth
            End Get
        End Property
        Protected Overridable ReadOnly Property ImageGapTop() As Integer
            Get
                Return _ImageGapTop
            End Get
        End Property
        Protected Overridable ReadOnly Property ImageGapLeft() As Integer
            Get
                Return _ImageGapLeft
            End Get
        End Property
        Protected Overridable ReadOnly Property ImageGapRight() As Integer
            Get
                Return _ImageGapRight
            End Get
        End Property
        Protected Overridable ReadOnly Property ImageGapBottom() As Integer
            Get
                Return _ImageGapBottom
            End Get
        End Property
        Protected Overridable ReadOnly Property TextGapLeft() As Integer
            Get
                Return _TextGapLeft
            End Get
        End Property
        Protected Overridable ReadOnly Property TextGapRight() As Integer
            Get
                Return _TextGapRight
            End Get
        End Property
        Protected Overridable ReadOnly Property TabGapTop() As Integer
            Get
                Return _TabGapTop
            End Get
        End Property
        Protected Overridable ReadOnly Property TabGapLeft() As Integer
            Get
                Return _TabGapLeft
            End Get
        End Property
        Protected Overridable ReadOnly Property TabGapBetween() As Integer
            Get
                Return _TabGapBetween
            End Get
        End Property
        Protected Overridable Sub BeginDrawTab()
        End Sub
        Protected Overridable Sub EndDrawTab()
        End Sub
        Protected Overridable ReadOnly Property BrushTabBackGround() As Brush
            Get
                Return SystemBrushes.Control
            End Get
        End Property
        Protected Overridable ReadOnly Property PenTabBorder() As Pen
            Get
                Return SystemPens.GrayText
            End Get
        End Property
        Protected Overridable ReadOnly Property BrushTabText() As Brush
            Get
                Return SystemBrushes.FromSystemColor(SystemColors.ControlDarkDark)
            End Get
        End Property
#End Region
        Private ReadOnly Property MatrixIdentity() As Matrix
            Get
                Return _matrixIdentity
            End Get
        End Property
        Private ReadOnly Property DockStates() As DockState()
            Get
                Return _dockStates
            End Get
        End Property
        Shared Sub New()
            _stringFormatTabHorizontal = New StringFormat()
            _stringFormatTabHorizontal.Alignment = StringAlignment.Near
            _stringFormatTabHorizontal.LineAlignment = StringAlignment.Center
            _stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap
            _stringFormatTabVertical = New StringFormat()
            _stringFormatTabVertical.Alignment = StringAlignment.Near
            _stringFormatTabVertical.LineAlignment = StringAlignment.Center
            _stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap Or StringFormatFlags.DirectionVertical
            _matrixIdentity = New Matrix()
            _dockStates = New DockState(4) {}
            _dockStates(0) = DockState.DockLeftAutoHide
            _dockStates(1) = DockState.DockRightAutoHide
            _dockStates(2) = DockState.DockTopAutoHide
            _dockStates(3) = DockState.DockBottomAutoHide
        End Sub
        Protected Friend Sub New(ByVal panel As DockPanel)
            MyBase.New(panel)
            SetStyle(ControlStyles.ResizeRedraw, True)
            SetStyle(ControlStyles.UserPaint, True)
            SetStyle(ControlStyles.AllPaintingInWmPaint, True)
            SetStyle(ControlStyles.OptimizedDoubleBuffer, True)
            BackColor = Color.WhiteSmoke
        End Sub
        Protected Overloads Overrides Sub OnPaint(ByVal e As PaintEventArgs)
            Dim g As Graphics = e.Graphics
            Using brush As LinearGradientBrush = New LinearGradientBrush(ClientRectangle, Color.Navy, Color.WhiteSmoke, LinearGradientMode.BackwardDiagonal)
                g.FillRectangle(brush, ClientRectangle)
            End Using
            DrawTabStrip(g)
        End Sub
        Protected Overloads Overrides Sub OnLayout(ByVal levent As LayoutEventArgs)
            CalculateTabs()
            MyBase.OnLayout(levent)
        End Sub
        Private Sub DrawTabStrip(ByVal g As Graphics)
            DrawTabStrip(g, DockState.DockTopAutoHide)
            DrawTabStrip(g, DockState.DockBottomAutoHide)
            DrawTabStrip(g, DockState.DockLeftAutoHide)
            DrawTabStrip(g, DockState.DockRightAutoHide)
        End Sub
        Private Sub DrawTabStrip(ByVal g As Graphics, ByVal dockState As DockState)
            Dim rectTabStrip As Rectangle = GetLogicalTabStripRectangle(dockState)
            If rectTabStrip.IsEmpty Then
                Return
            End If
            Dim matrixIdentity As Matrix = g.Transform
            If dockState = dockState.DockLeftAutoHide OrElse dockState = dockState.DockRightAutoHide Then
                Dim matrixRotated As Matrix = New Matrix()
                matrixRotated.RotateAt(90, New PointF(CSng(rectTabStrip.X) + CSng(rectTabStrip.Height) / 2, CSng(rectTabStrip.Y) + CSng(rectTabStrip.Height) / 2))
                g.Transform = matrixRotated
            End If
            For Each pane As AutoHidePane In GetPanes(dockState)
                For Each tab As AutoHideTabFromBase In pane.Tabs
                    DrawTab(g, tab)
                Next
            Next
            g.Transform = matrixIdentity
        End Sub
        Private Sub CalculateTabs()
            CalculateTabs(DockState.DockTopAutoHide)
            CalculateTabs(DockState.DockBottomAutoHide)
            CalculateTabs(DockState.DockLeftAutoHide)
            CalculateTabs(DockState.DockRightAutoHide)
        End Sub
        Private Sub CalculateTabs(ByVal dockState As DockState)
            Dim rectTabStrip As Rectangle = GetLogicalTabStripRectangle(dockState)
            Dim imageHeight As Integer = rectTabStrip.Height - ImageGapTop - ImageGapBottom
            Dim imageWidth As Integer = imageWidth
            If imageHeight > Me.ImageHeight Then
                imageWidth = CInt(Me.ImageWidth * (imageHeight / Me.ImageHeight))
            End If
            Using g As Graphics = CreateGraphics()
                Dim x As Integer = TabGapLeft + rectTabStrip.X
                For Each pane As AutoHidePane In GetPanes(dockState)
                    Dim maxWidth As Integer = 0
                    For Each tab As AutoHideTabFromBase In pane.Tabs
                        Dim width As Integer = imageWidth + ImageGapLeft + ImageGapRight + CInt(g.MeasureString(tab.Content.DockHandler.TabText, Font).Width) + 1 + TextGapLeft + TextGapRight
                        If width > maxWidth Then
                            maxWidth = width
                        End If
                    Next
                    For Each tab As AutoHideTabFromBase In pane.Tabs
                        tab.TabX = x
                        If tab.Content Is pane.DockPane.ActiveContent Then
                            tab.TabWidth = maxWidth
                        Else
                            tab.TabWidth = imageWidth + ImageGapLeft + ImageGapRight
                        End If
                        x += tab.TabWidth
                    Next
                    x += TabGapBetween
                Next
            End Using
        End Sub
        Private Sub DrawTab(ByVal g As Graphics, ByVal tab As AutoHideTabFromBase)
            Dim rectTab As Rectangle = GetTabRectangle(tab)
            If rectTab.IsEmpty Then
                Return
            End If
            Dim dockState As DockState = tab.Content.DockHandler.DockState
            Dim content As IDockContent = tab.Content
            BeginDrawTab()
            Dim brushTabBackGround As Brush = Me.BrushTabBackGround
            Dim penTabBorder As Pen = Me.PenTabBorder
            Dim brushTabText As Brush = Me.BrushTabText

            g.SmoothingMode = SmoothingMode.AntiAlias
            If dockState = dockState.DockTopAutoHide OrElse dockState = dockState.DockRightAutoHide Then
                DrawHelper.DrawTab(g, rectTab, Corners.Bottom, GradientType.Flat, Color.FromArgb(244, 242, 232), Color.FromArgb(244, 242, 232), Color.FromArgb(172, 168, 153), True)
            Else
                DrawHelper.DrawTab(g, rectTab, Corners.Top, GradientType.Flat, Color.FromArgb(244, 242, 232), Color.FromArgb(244, 242, 232), Color.FromArgb(172, 168, 153), True)
            End If

            ' Set no rotate for drawing icon and text
            Dim matrixRotate As Matrix = g.Transform
            g.Transform = MatrixIdentity

            ' Draw the icon
            Dim rectImage As Rectangle = rectTab
            rectImage.X += ImageGapLeft
            rectImage.Y += ImageGapTop
            Dim imageHeight As Integer = rectTab.Height - ImageGapTop - ImageGapBottom
            Dim imageWidth As Integer = Me.ImageWidth
            If imageHeight > Me.ImageHeight Then
                imageWidth = CInt(Me.ImageWidth * (imageHeight / Me.ImageHeight))
            End If
            rectImage.Height = imageHeight
            rectImage.Width = imageWidth
            rectImage = GetTransformedRectangle(dockState, rectImage)
            g.DrawIcon(content.DockHandler.Icon, rectImage)

            ' Draw the text
            If content Is content.DockHandler.Pane.ActiveContent Then
                Dim rectText As Rectangle = rectTab
                rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft
                rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft
                rectText = GetTransformedRectangle(dockState, rectText)
                If dockState = dockState.DockLeftAutoHide OrElse dockState = dockState.DockRightAutoHide Then
                    g.DrawString(content.DockHandler.TabText, Font, brushTabText, rectText, StringFormatTabVertical)
                Else
                    g.DrawString(content.DockHandler.TabText, Font, brushTabText, rectText, StringFormatTabHorizontal)
                End If
            End If
            ' Set rotate back
            g.Transform = matrixRotate
            EndDrawTab()
        End Sub
        Private Function GetLogicalTabStripRectangle(ByVal dockState As DockState) As Rectangle
            Return GetLogicalTabStripRectangle(dockState, False)
        End Function
        Private Function GetLogicalTabStripRectangle(ByVal dockState As DockState, ByVal transformed As Boolean) As Rectangle
            If Not DockHelper.IsDockStateAutoHide(dockState) Then
                Return Rectangle.Empty
            End If
            Dim leftPanes As Integer = GetPanes(dockState.DockLeftAutoHide).Count
            Dim rightPanes As Integer = GetPanes(dockState.DockRightAutoHide).Count
            Dim topPanes As Integer = GetPanes(dockState.DockTopAutoHide).Count
            Dim bottomPanes As Integer = GetPanes(dockState.DockBottomAutoHide).Count
            Dim x As Integer, y As Integer, width As Integer, height As Integer
            height = MeasureHeight()
            If dockState = dockState.DockLeftAutoHide AndAlso leftPanes > 0 Then
                x = 0
                If topPanes = 0 Then
                    y = 0
                Else : y = height
                End If
                If topPanes = 0 Then
                    If bottomPanes = 0 Then
                        width = Me.Height
                    Else
                        width = Me.Height - height
                    End If
                Else
                    If bottomPanes = 0 Then
                        width = Me.Height - height
                    Else
                        width = Me.Height - height * 2
                    End If
                End If
            ElseIf dockState = dockState.DockRightAutoHide AndAlso rightPanes > 0 Then
                x = Me.Width - height
                If leftPanes <> 0 AndAlso x < height Then
                    x = height
                End If
                If topPanes = 0 Then
                    y = 0
                Else : y = height
                End If
                If topPanes = 0 Then
                    If bottomPanes = 0 Then
                        width = Me.Height
                    Else
                        width = Me.Height - height
                    End If
                Else
                    If bottomPanes = 0 Then
                        width = Me.Height - height
                    Else
                        width = Me.Height - height * 2
                    End If
                End If
            ElseIf dockState = dockState.DockTopAutoHide AndAlso topPanes > 0 Then
                If leftPanes = 0 Then
                    x = 0
                Else : x = height
                End If
                y = 0
                If leftPanes = 0 Then
                    If rightPanes = 0 Then
                        width = Me.Width
                    Else
                        width = Me.Width - height
                    End If
                Else
                    If rightPanes = 0 Then
                        width = Me.Width - height
                    Else
                        width = Me.Width - height * 2
                    End If
                End If
            ElseIf dockState = dockState.DockBottomAutoHide AndAlso bottomPanes > 0 Then
                If leftPanes = 0 Then
                    x = 0
                Else : x = height
                End If
                y = Me.Height - height
                If topPanes <> 0 AndAlso y < height Then
                    y = height
                End If
                If leftPanes = 0 Then
                    If rightPanes = 0 Then
                        width = Me.Width
                    Else
                        width = Me.Width - height
                    End If
                Else
                    If rightPanes = 0 Then
                        width = Me.Width - height
                    Else
                        width = Me.Width - height * 2
                    End If
                End If

            Else
                Return Rectangle.Empty
            End If
            If Not transformed Then
                Return New Rectangle(x, y, width, height)
            Else
                Return GetTransformedRectangle(dockState, New Rectangle(x, y, width, height))
            End If
        End Function
        Private Function GetTabRectangle(ByVal tab As AutoHideTabFromBase) As Rectangle
            Return GetTabRectangle(tab, False)
        End Function
        Private Function GetTabRectangle(ByVal tab As AutoHideTabFromBase, ByVal transformed As Boolean) As Rectangle
            Dim dockState As DockState = tab.Content.DockHandler.DockState
            Dim rectTabStrip As Rectangle = GetLogicalTabStripRectangle(dockState)
            If rectTabStrip.IsEmpty Then
                Return Rectangle.Empty
            End If
            Dim x As Integer = tab.TabX
            Dim y As Integer

            If (dockState = dockState.DockTopAutoHide OrElse dockState = dockState.DockRightAutoHide) Then
                y = rectTabStrip.Y
            Else
                y = rectTabStrip.Y + TabGapTop
            End If

            Dim width As Integer = (DirectCast(tab, AutoHideTabFromBase)).TabWidth
            Dim height As Integer = rectTabStrip.Height - TabGapTop
            If Not transformed Then
                Return New Rectangle(x, y, width, height)
            Else
                Return GetTransformedRectangle(dockState, New Rectangle(x, y, width, height))
            End If
        End Function
        Private Function GetTransformedRectangle(ByVal dockState As DockState, ByVal rect As Rectangle) As Rectangle
            If dockState <> dockState.DockLeftAutoHide AndAlso dockState <> dockState.DockRightAutoHide Then
                Return rect
            End If
            Dim pts As PointF() = New PointF(1) {}
            ' the center of the rectangle
            pts(0).X = CSng(rect.X) + CSng(rect.Width) / 2
            pts(0).Y = CSng(rect.Y) + CSng(rect.Height) / 2
            Dim rectTabStrip As Rectangle = GetLogicalTabStripRectangle(dockState)
            Dim matrix As Matrix = New Matrix()
            matrix.RotateAt(90, New PointF(CSng(rectTabStrip.X) + CSng(rectTabStrip.Height) / 2, CSng(rectTabStrip.Y) + CSng(rectTabStrip.Height) / 2))
            matrix.TransformPoints(pts)
            Return New Rectangle(CInt((pts(0).X - CSng(rect.Height) / 2 + 0.5F)), CInt((pts(0).Y - CSng(rect.Width) / 2 + 0.5F)), rect.Height, rect.Width)
        End Function
        Protected Overloads Overrides Function GetHitTest(ByVal ptMouse As Point) As IDockContent
            For Each state As DockState In DockStates
                Dim rectTabStrip As Rectangle = GetLogicalTabStripRectangle(state, True)
                If Not rectTabStrip.Contains(ptMouse) Then
                    Continue For
                End If
                For Each pane As AutoHidePane In GetPanes(state)
                    For Each tab As AutoHideTabFromBase In pane.Tabs
                        Dim rectTab As Rectangle = GetTabRectangle(tab, True)
                        rectTab.Intersect(rectTabStrip)
                        If rectTab.Contains(ptMouse) Then
                            Return tab.Content
                        End If
                    Next
                Next
            Next
            Return Nothing
        End Function
        Protected Overloads Overrides Function MeasureHeight() As Integer
            Return Math.Max(ImageGapBottom + ImageGapTop + ImageHeight, Font.Height) + TabGapTop
        End Function
        Protected Overloads Overrides Sub OnRefreshChanges()
            CalculateTabs()
            Invalidate()
        End Sub
    End Class
End Namespace


text:
namespace HolisticWare.Ph4ct3x.DiagnosticTests.Core
{
    public partial class StrengthMuscular : Strength
    {
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.firestore.v1.model;

/**
 * The TTL (time-to-live) configuration for documents that have this `Field` set. Storing a
 * timestamp value into a TTL-enabled field will be treated as the document's absolute expiration
 * time. Timestamp values in the past indicate that the document is eligible for immediate
 * expiration. Using any other data type or leaving the field absent will disable expiration for the
 * individual document.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Firestore API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleFirestoreAdminV1TtlConfig extends com.google.api.client.json.GenericJson {

  /**
   * Output only. The state of the TTL configuration.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String state;

  /**
   * Output only. The state of the TTL configuration.
   * @return value or {@code null} for none
   */
  public java.lang.String getState() {
    return state;
  }

  /**
   * Output only. The state of the TTL configuration.
   * @param state state or {@code null} for none
   */
  public GoogleFirestoreAdminV1TtlConfig setState(java.lang.String state) {
    this.state = state;
    return this;
  }

  @Override
  public GoogleFirestoreAdminV1TtlConfig set(String fieldName, Object value) {
    return (GoogleFirestoreAdminV1TtlConfig) super.set(fieldName, value);
  }

  @Override
  public GoogleFirestoreAdminV1TtlConfig clone() {
    return (GoogleFirestoreAdminV1TtlConfig) super.clone();
  }

}


text:
/**
 * The error handler module.
 *
 * @module error
 * @main error
 */

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'qi-error',
  templateUrl: '/public/html/error/error.html'
})

/**
 * The error component. This component consists of a template and
 * the `error` input string.
 *
 * @class ErrorComponent
 */
export class ErrorComponent {
  /**
   * The error message to display.
   *
   * @property error {string}
   */
  @Input() error: string;

  /**
   * The error pop-up dismissal event.
   *
   * @property dismissed {EventEmitter}
   */
  @Output() dismissed = new EventEmitter();

  constructor() {
  }

  dismiss() {
    this.dismissed.emit();
  }
}


text:
#include <config.h>

#include "timer.h"
#include "utest.h"
#include "utils.h"

#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

typedef struct {
    const char *name;
    UtFunc func;
    const char *file;
} Test;

typedef struct suite {
    const char *name;
    size_t size;
    size_t num;
    Test *tests;
    UtCallback setup;
    UtCallback teardown;
    struct suite *next;
} Suite;

struct ut_test_data {
    const char *name;
    const char *file;
    unsigned int assertions_ok;
    unsigned int assertions_failed;
    void **free_array;          /**< Array of pointers to be freed later. */
    UtFreeFunc *free_funcs;
    size_t free_arr_num;
    size_t free_arr_len;
    FILE *logs;
};

struct test_result {
    Timer *timer;
    unsigned int tests_ran;
    unsigned int tests_failed;
    unsigned int tests_crashed;
    unsigned int assertions_ok;
    unsigned int assertions_failed;
};

/**
 * Helper function for printing messages.
 */
static void _ut_vmessage (UtTestData *data, const char *msg, va_list args);

static Suite *global_tests = NULL;

static void __attribute__((destructor))
shutdown_tests (void)
{
    debug("Shutting down tests\n");
    Suite *s = global_tests;
    while (s) {
        global_tests = s->next;
        free(s->tests);
        free(s);
        s = global_tests;
    }
}

static Suite *
suite_new (const char *name)
{
    Suite *suite = safe_malloc(sizeof *suite);
    suite->name = name;
    suite->size = 8;
    suite->tests = safe_malloc(sizeof *suite->tests * suite->size);
    return suite;
}

static inline Suite *
find_suite (const char *name)
{
    Suite *tmp = global_tests;

    while (tmp != NULL && strcmp(tmp->name, name) != 0) {
        tmp = tmp->next;
    }
    if (tmp == NULL) {
        tmp = suite_new(name);
        tmp->next = global_tests;
        global_tests = tmp;
    }

    return tmp;
}

void
ut_register_test (const char *suite, const char * name, UtFunc f,
        const char *file)
{
    Suite *s = find_suite(suite);

    if (s->num >= s->size) {
        s->size *= 2;
        s->tests = safe_realloc(s->tests, sizeof *s->tests * s->size);
    }
    s->tests[s->num].name = name;
    s->tests[s->num].func = f;
    s->tests[s->num].file = file;
    ++s->num;
}

void
ut_register_callback (UtCallback cb, const char *suitename, UtCallbackType type)
{
    Suite *suite = find_suite(suitename);

    switch (type) {
    case UT_CALLBACK_SETUP:
        suite->setup = cb;
        break;
    case UT_CALLBACK_TEARDOWN:
        suite->teardown = cb;
        break;
    }
}

/**
 * Run all free functions and reset data structure related to them.
 */
static void
run_free_funcs(UtTestData *data)
{
    for (size_t i = 0; i < data->free_arr_num; ++i) {
        data->free_funcs[i](data->free_array[i]);
    }
    free(data->free_array);
    free(data->free_funcs);
    data->free_array = NULL;
    data->free_funcs = NULL;
    data->free_arr_num = data->free_arr_len = 0;
}

static void
test_run (Suite *suite, Test *test, UtTestData *data)
{
    if (suite->setup) {
        suite->setup();
    }

    test->func(data);

    if (suite->teardown) {
        suite->teardown();
    }

    run_free_funcs(data);
}

static bool
test_run_forked (Suite *suite, Test *test, Timer *timer,
        UtTestData *data, int *status, FILE *logs)
{
    int pipe_fd[2];

    if (pipe(pipe_fd) < 0) {
        perror("pipe");
        abort();
    }

    fflush(stdout);
    fflush(logs);
    timer_start(timer);
    pid_t pid = fork();
    ssize_t len;
    if (pid < 0) {
        perror("fork");
        abort();
    } else if (pid == 0) {
        close(pipe_fd[0]);
        test_run(suite, test, data);
        safe_write(pipe_fd[1], data, sizeof *data);
        close(pipe_fd[1]);
        fclose(logs);
        timer_free(timer);
        exit(EXIT_SUCCESS);
    } else {
        close(pipe_fd[1]);
        waitpid(pid, status, 0);
        timer_stop(timer);
        len = read(pipe_fd[0], data, sizeof *data);
        close(pipe_fd[0]);
    }

    if (len != sizeof *data && !WIFSIGNALED(*status)) {
        error("failed to read data");
        return false;
    }

    return true;
}

static void
suite_run (Suite *suite, struct test_result *results,
           FILE *logs, UtFlags flags)
{
    for (size_t i = 0; i < suite->num; ++i) {
        debug("Running '%s:%s'\n", suite->name, suite->tests[i].name);

        UtTestData data = {suite->tests[i].name, suite->tests[i].file, 0, 0, NULL, NULL, 0, 0, logs};
        int status;
        if (!(flags & UT_NO_FORK)) {
            if (!test_run_forked(suite, &suite->tests[i], results->timer, &data,
                        &status, logs))
                continue;
        } else {
            timer_start(results->timer);
            test_run(suite, &suite->tests[i], &data);
            timer_stop(results->timer);
        }

        if (!(flags & UT_NO_FORK) && WIFSIGNALED(status)) {
            ++results->tests_crashed;
            fprintf(logs, "Crash in "_ut_INBOLD("%s")" (%s)\n\t"
                    "Killed with signal "_ut_INBOLD("%d")" (%s)\n\n",
                    data.name, suite->tests[i].file,
                    WTERMSIG(status), strsignal(WTERMSIG(status)));
            putc_color('C', RED, flags);
        } else if (data.assertions_failed > 0) {
            ++results->tests_failed;
            putc_color('F', RED, flags);
        } else {
            putc_color('.', GREEN, flags);
        }
        results->assertions_ok += data.assertions_ok;
        results->assertions_failed += data.assertions_failed;
    }
    results->tests_ran += suite->num;
}

int
ut_run_all_tests (UtFlags flags)
{
    struct test_result results = { NULL, 0, 0, 0, 0, 0 };
    FILE *logs = tmpfile();
    results.timer = timer_new();

    for (Suite *suite = global_tests; suite; suite = suite->next) {
        suite_run(suite, &results, logs, flags);
    }

    if (!(flags & UT_QUIET)) {
        fputs("\n\n", stdout);

        rewind(logs);
        copy_from_to(logs, stdout, flags);

        printf("%u assertions succeeded, %u assertions failed\n",
                results.assertions_ok, results.assertions_failed);
        printf("%u tests ran, %u failed, %u crashed\n",
                results.tests_ran, results.tests_failed, results.tests_crashed);
        printf("Time elapsed: %.3f sec\n", timer_get_elapsed(results.timer));
    }
    fclose(logs);
    timer_free(results.timer);
    return results.tests_failed + results.tests_crashed == 0;
}

void
_ut_assert_func (UtTestData *data, int lineno, int expr, const char *msg, ...)
{
    if (expr) {
        _ut_pass(data);
        return;
    }
    _ut_fail(data, lineno);

    va_list args;
    va_start(args, msg);
    _ut_vmessage(data, msg, args);
    va_end(args);
}

void
_ut_assert_equal_string (UtTestData *data, int line,
                         const char *expected, const char *actual)
{
    if (expected == NULL && actual == NULL) {
        _ut_pass(data);
        return;
    }
    if (expected && actual && strcmp(expected, actual) == 0) {
        _ut_pass(data);
        return;
    }
    _ut_fail(data, line);

    if (expected == NULL) {
        _ut_message(data, "Expected NULL, got <"_ut_INBOLD("%s")">", actual);
        return;
    }
    if (actual == NULL) {
        _ut_message(data, "Expected <"_ut_INBOLD("%s")">, got NULL", expected);
        return;
    }

    fprintf(data->logs, "\tExpected <"_ut_INBOLD("%s")">\n", expected);
    fputs("\tGot      <" BOLD, data->logs);
    size_t len = strlen(expected);
    for (size_t i = 0; actual[i] != 0; ++i) {
        if (i < len && actual[i] != expected[i]) {
            fprintf(data->logs, RED "%c" NORMAL BOLD, actual[i]);
        } else {
            fputc(actual[i], data->logs);
        }
    }
    fputs(NORMAL ">\n\n", data->logs);
}

void
_ut_fail (UtTestData *data, int line)
{
    ++data->assertions_failed;
    fprintf(data->logs, "Assertion in "_ut_INBOLD("%s")" (%s:%d) failed:\n",
            data->name, data->file, line);
}

void
_ut_message (UtTestData *data, const char *msg, ...)
{
    va_list args;
    va_start(args, msg);
    _ut_vmessage(data, msg, args);
    va_end(args);
}

static void
_ut_vmessage (UtTestData *data, const char *msg, va_list args)
{
    fputc('\t', data->logs);
    vfprintf(data->logs, msg, args);
    fputs("\n\n", data->logs);
}

void
_ut_pass (UtTestData *data)
{
    ++data->assertions_ok;
}

void *
_ut_take_memory(UtTestData *data, void *ptr, UtFreeFunc func)
{
    if (data->free_arr_num >= data->free_arr_len) {
        data->free_arr_len += 8;
        data->free_array = safe_realloc(data->free_array, data->free_arr_len * sizeof (*data->free_array));
        data->free_funcs = safe_realloc(data->free_funcs, data->free_arr_len * sizeof (*data->free_array));
    }
    data->free_array[data->free_arr_num] = ptr;
    data->free_funcs[data->free_arr_num] = func;
    ++data->free_arr_num;
    return ptr;
}


text:
extern crate iron_sessionstorage;
#[macro_use] extern crate router;
extern crate urlencoded;

use iron::prelude::*;
use iron::status;
use iron::modifiers::Redirect;

use iron_sessionstorage::traits::*;
use iron_sessionstorage::SessionStorage;
use iron_sessionstorage::backends::SignedCookieBackend;

use urlencoded::UrlEncodedBody;

struct Login {
    username: String
}

impl iron_sessionstorage::Value for Login {
    fn get_key() -> &'static str { "logged_in_user" }
    fn into_raw(self) -> String { self.username }
    fn from_raw(value: String) -> Option<Self> {
        if value.is_empty() {
            None
        } else {
            Some(Login { username: value })
        }
    }
}

fn login(req: &mut Request) -> IronResult<Response> {
    if try!(req.session().get::<Login>()).is_some() {
        // Already logged in
        return Ok(Response::with((status::Found, Redirect(url_for!(req, "greet")))));
    }

    Ok(Response::with((
        status::Ok,
        "text/html".parse::<iron::mime::Mime>().unwrap(),
        format!("This is an insecure demo, so which username do you want to log in as?
 \n\
        <form method=post> \n\
        <input type=text name=username> \n\
        <input type=submit> \n\
        </form>")
    )))
}

fn login_post(req: &mut Request) -> IronResult<Response> {
    let username = {
        let formdata = iexpect!(req.get_ref::<UrlEncodedBody>().ok());
        iexpect!(formdata.get("username"))[0].to_owned()
    };

    try!(req.session().set(Login { username: username }));
    Ok(Response::with((status::Found, Redirect(url_for!(req, "greet")))))
}

fn logout(req: &mut Request) -> IronResult<Response> {
    try!(req.session().clear());
    Ok(Response::with((status::Found, Redirect(url_for!(req, "greet")))))
}

fn greet(req: &mut Request) -> IronResult<Response> {
    let login = iexpect!(
        req.session().get::<Login>().ok().and_then(|x| x),
        (
            status::Unauthorized,
            "text/html".parse::<iron::mime::Mime>().unwrap(),
            "Log in"
        )
    );

    Ok(Response::with((
        status::Ok,
        "text/html".parse::<iron::mime::Mime>().unwrap(),
        format!("Hello, {}!
\n\
        <form method=post action=/logout>\n\
        <input type=submit value='Log out' />\n\
        </form>", login.username)
    )))
}

fn main() {
    let router = router!(
        greet: get "/" => greet,
        login: get "/login" => login,
        login_post: post "/login" => login_post,
        logout: post "/logout" => logout,
    );

    let my_secret = b"verysecret".to_vec();
    let mut ch = Chain::new(router);
    ch.link_around(SessionStorage::new(SignedCookieBackend::new(my_secret)));
    let _res = Iron::new(ch).http("localhost:8080");
    println!("Listening on 8080.");
}


text:
const CADisplayLink = ObjC.classes.CADisplayLink;
const NSAutoreleasePool = ObjC.classes.NSAutoreleasePool;
const NSRunLoop = ObjC.classes.NSRunLoop;
const UIApplication = ObjC.classes.UIApplication;
const UITouch = ObjC.classes.UITouch;

const UITouchPhaseBegan = 0;
const UITouchPhaseMoved = 1;
const UITouchPhaseStationary = 2;
const UITouchPhaseEnded = 3;
const UITouchPhaseCancelled = 4;

const UITOUCH_FLAG_IS_FIRST_TOUCH_FOR_VIEW = 1;
const UITOUCH_FLAG_IS_TAP = 2;

const CGFloat = (Process.pointerSize === 4) ? 'float' : 'double';
const CGPoint = [CGFloat, CGFloat];
const CGPointEqualToPoint = new NativeFunction(
    Module.getExportByName('CoreGraphics', 'CGPointEqualToPoint'),
    'uint8',
    [CGPoint, CGPoint]);
const CGPointZero = Module.getExportByName('CoreGraphics', 'CGPointZero').readPointer();
const CGSize = [CGFloat, CGFloat];

const kIOHIDDigitizerEventRange = 0x00000001;
const kIOHIDDigitizerEventTouch = 0x00000002;
const kIOHIDDigitizerEventPosition = 0x00000004;
const IOHIDEventCreateDigitizerFingerEvent = new NativeFunction(
    Module.getExportByName(null, 'IOHIDEventCreateDigitizerFingerEvent'),
    'pointer',
    [
        'pointer',            // allocator
        ['uint32', 'uint32'], // timestamp
        'uint32',             // index
        'uint32',             // identity
        'uint32',             // eventMask
        CGFloat,              // x
        CGFloat,              // y
        CGFloat,              // z
        CGFloat,              // tipPressure
        CGFloat,              // twist
        'uint8',              // range
        'uint8',              // touch
        'uint32'              // options
    ]);

const kCFAllocatorDefault = Module.getExportByName('CoreFoundation', 'kCFAllocatorDefault').readPointer();
const NSRunLoopCommonModes = Module.getExportByName('Foundation', 'NSRunLoopCommonModes').readPointer();
const CFGetSystemUptime = new NativeFunction(
    Module.getExportByName('CoreFoundation', 'CFGetSystemUptime'),
    'double',
    []);
const CFRelease = new NativeFunction(
    Module.getExportByName('CoreFoundation', 'CFRelease'),
    'void',
    ['pointer']);

const mach_absolute_time = new NativeFunction(
    Module.getExportByName('libSystem.B.dylib', 'mach_absolute_time'),
    'uint64',
    []);

const Injector = ObjC.registerClass({
  methods: {
    '- init': function () {
      const self = this.super.init();
      if (self !== null) {
        const displayLink = CADisplayLink.displayLinkWithTarget_selector_(self, ObjC.selector('dispatchTouch:'));
        ObjC.bind(self, {
          displayLink: displayLink,
          window: null,
          touch: null,
          pending: [],
          previous: null,
          onComplete: function () {}
        });
        displayLink.addToRunLoop_forMode_(NSRunLoop.mainRunLoop(), NSRunLoopCommonModes);
        displayLink.setPaused_(false);
      }
      return self;
    },
    '- dealloc': function () {
      ObjC.unbind(this.self);
      this.super.dealloc();
    },
    '- dispatchTouch:': {
      retType: 'void',
      argTypes: ['object'],
      implementation: function (sender) {
        const priv = this.data;

        if (priv.pending.length === 0) {
          priv.displayLink.invalidate();
          priv.displayLink = null;

          priv.onComplete();
          return;
        }

        let touch, phase;
        let point = priv.pending.shift();
        const isLastTouch = priv.pending.length === 0;

        if (priv.touch === null) {
          touch = UITouch.alloc().init();
          priv.touch = touch;
          touch.setTapCount_(1);
          setIsTap(touch, true);
          phase = UITouchPhaseBegan;
          touch.setPhase_(phase);
          touch.setWindow_(priv.window);
          touch['- _setLocationInWindow:resetPrevious:'].call(touch, point, true);
          touch.setView_(priv.window.hitTest_withEvent_(point, NULL));
          setIsFirstTouchForView(touch, true);
        } else {
          touch = priv.touch;

          if (isLastTouch) {
            touch['- _setLocationInWindow:resetPrevious:'].call(touch, priv.previous, false);
            phase = UITouchPhaseEnded;
            point = priv.previous;
          } else {
            touch['- _setLocationInWindow:resetPrevious:'].call(touch, point, false);
            phase = CGPointEqualToPoint(point, priv.previous) ? UITouchPhaseStationary : UITouchPhaseMoved;
          }

          touch.setPhase_(phase);
        }

        const app = UIApplication.sharedApplication();
        const event = app['- _touchesEvent'].call(app);
        event['- _clearTouches'].call(event);

        const absoluteTime = mach_absolute_time();

        const timestamp = [
            absoluteTime.shr(32).toNumber(),
            absoluteTime.and(0xffffffff).toNumber()
        ];

        touch.setTimestamp_(CFGetSystemUptime());

        const eventMask = (phase === UITouchPhaseMoved)
            ? kIOHIDDigitizerEventPosition
            : (kIOHIDDigitizerEventRange | kIOHIDDigitizerEventTouch);
        const isRangeAndTouch = (phase !== UITouchPhaseEnded) ? 1 : 0;

        const hidEvent = IOHIDEventCreateDigitizerFingerEvent(
            kCFAllocatorDefault,
            timestamp,
            0,
            2,
            eventMask,
            point[0],
            point[1],
            0,
            0,
            0,
            isRangeAndTouch,
            isRangeAndTouch,
            0);

        if ('- _setHidEvent:' in touch) {
          touch['- _setHidEvent:'].call(touch, hidEvent);
        }

        event['- _setHIDEvent:'].call(event, hidEvent);
        event['- _addTouch:forDelayedDelivery:'].call(event, touch, false);

        const pool = NSAutoreleasePool.alloc().init();
        try {
          app.sendEvent_(event);
        } finally {
          pool.release();

          CFRelease(hidEvent);

          priv.previous = point;
          if (isLastTouch) {
            touch.release();
            priv.touch = null;
          }
        }
      }
    }
  }
});

function tap(view, x, y) {
  return new Promise(function (resolve, reject) {
    const window = view.window();
    if (window === null) {
      reject(new Error('Cannot tap on NULL window'));
      return;
    }

    const point = view.convertPoint_toView_([x, y], NULL);

    const injector = Injector.alloc().init();
    const priv = ObjC.getBoundData(injector);
    priv.window = window;
    priv.pending.push(point, CGPointZero);
    priv.onComplete = function () {
      injector.release();
      resolve();
    };
  });
}

function setIsTap (touch, isTap) {
  const flags = touch.$ivars['_touchFlags'];
  const newFlags = [...flags];
  if (isTap) {
    newFlags[0] |= UITOUCH_FLAG_IS_TAP;
  } else {
    newFlags[0] &= ~UITOUCH_FLAG_IS_TAP;
  }
  touch.$ivars['_touchFlags'] = newFlags;
}

function setIsFirstTouchForView (touch, isFirst) {
  const flags = touch.$ivars['_touchFlags'];
  const newFlags = [...flags];
  if (isFirst) {
    newFlags[0] |= UITOUCH_FLAG_IS_FIRST_TOUCH_FOR_VIEW;
  } else {
    newFlags[0] &= ~UITOUCH_FLAG_IS_FIRST_TOUCH_FOR_VIEW;
  }
  touch.$ivars['_touchFlags'] = newFlags;
}

module.exports = {
  tap: tap
};


text:
Go (golang) support for Vim, which comes with pre-defined sensible settings (like
auto gofmt on save), with autocomplete, snippet support, improved syntax
highlighting, go toolchain commands, and more.  If needed vim-go installs all
necessary binaries for providing seamless Vim integration with current
commands. It's highly customizable and each individual feature can be
disabled/enabled easily.

## Features

* Improved Syntax highlighting with items such as Functions, Operators, Methods.
* Auto completion support via `gocode`
* Better `gofmt` on save, which keeps cursor position and doesn't break your undo
  history
* Go to symbol/declaration with `:GoDef`
* Look up documentation with `:GoDoc` inside Vim or open it in browser
* Automatically import packages via `:GoImport` or plug it into autosave
* Compile your package with `:GoBuild`, install it with `:GoInstall` or test
  them with `:GoTest` (also supports running single tests via `:GoTestFunc`)
* Quickly execute your current file/files with `:GoRun`
* Automatic `GOPATH` detection based on the directory structure (i.e. `gb`
  projects, `godep` vendored projects)
* Change or display `GOPATH` with `:GoPath`
* Create a coverage profile and display annotated source code to see which
  functions are covered with `:GoCoverage`
* Call `gometalinter` with `:GoMetaLinter`, which invokes all possible linters
  (golint, vet, errcheck, deadcode, etc..) and shows the warnings/errors
* Lint your code with `:GoLint`
* Run your code through `:GoVet` to catch static errors
* Advanced source analysis tools utilizing guru, such as `:GoImplements`,
  `:GoCallees`, and `:GoReferrers`
* Precise type-safe renaming of identifiers with `:GoRename`
* List all source files and dependencies
* Unchecked error checking with `:GoErrCheck`
* Integrated and improved snippets, supporting `ultisnips` or `neosnippet`
* Share your current code to [play.golang.org](http://play.golang.org) with `:GoPlay`
* On-the-fly type information about the word under the cursor. Plug it into
  your custom vim function.
* Go asm formatting on save
* Tagbar support to show tags of the source code in a sidebar with `gotags`
* Custom vim text objects such as `a function` or `inner function`
  list.
* Jump to function or type declarations with `:GoDecls` or `:GoDeclsDir`
* A async launcher for the go command is implemented for Neovim, fully async
  building and testing (beta).
* Integrated with the Neovim terminal, launch `:GoRun` and other go commands
  in their own new terminal. (beta)
* Alternate between implementation and test code with `:GoAlternate`

Checkout the official [tutorial](https://github.com/fatih/vim-go-tutorial)
that goes literally over all features and shows many tips and tricks. It shows
how to install vim-go and explains many unknown use cases. Recommended for
beginners as well as advanced users: https://github.com/fatih/vim-go-tutorial

## Install

Master branch is supposed to be a development branch. So stuff here can break
and change.  Please try use always the [latest
release](https://github.com/fatih/vim-go/releases/latest)

Vim-go follows the standard runtime path structure, so I highly recommend to
use a common and well known plugin manager to install vim-go. Do not use vim-go
with other Go oriented vim plugins. For Pathogen just clone the repo. For other
plugin managers add the appropriate lines and execute the plugin's install
command.

*  [Pathogen](https://github.com/tpope/vim-pathogen)
  * `git clone https://github.com/fatih/vim-go.git ~/.vim/bundle/vim-go`
*  [vim-plug](https://github.com/junegunn/vim-plug)
  * `Plug 'fatih/vim-go'`
*  [NeoBundle](https://github.com/Shougo/neobundle.vim)
  * `NeoBundle 'fatih/vim-go'`
*  [Vundle](https://github.com/gmarik/vundle)
  * `Plugin 'fatih/vim-go'`
*  [Vim packages](http://vimhelp.appspot.com/repeat.txt.html#packages) (since Vim 7.4.1528)
  * `git clone https://github.com/fatih/vim-go.git ~/.vim/pack/plugins/start/vim-go`

Please be sure all necessary binaries are installed (such as `gocode`, `godef`,
`goimports`, etc.). You can easily install them with the included
`:GoInstallBinaries` command. If invoked, all necessary binaries will be
automatically downloaded and installed to your `$GOBIN` environment (if not set
it will use `$GOPATH/bin`). Note that this command requires `git` for fetching
the individual Go packages. Additionally, use `:GoUpdateBinaries` to update the
installed binaries.

### Optional

* Autocompletion is enabled by default via `<C-x><C-o>`. To get real-time
completion (completion by type) install:
[neocomplete](https://github.com/Shougo/neocomplete.vim) for Vim or
[deoplete](https://github.com/Shougo/deoplete.nvim) and
[deoplete-go](https://github.com/zchee/deoplete-go) for NeoVim or
[SimpleAutoCmplPop](https://github.com/roxma/SimpleAutoComplPop)
* To display source code tag information on a sidebar install
[tagbar](https://github.com/majutsushi/tagbar).
* For snippet features install:
[neosnippet](https://github.com/Shougo/neosnippet.vim) or
[ultisnips](https://github.com/SirVer/ultisnips).
* Screenshot color scheme is a slightly modified molokai:
  [fatih/molokai](https://github.com/fatih/molokai).
* For a better documentation viewer checkout:
  [go-explorer](https://github.com/garyburd/go-explorer).

## Usage

Many of the plugin's [features](#features) are enabled by default. There are no
additional settings needed. All usages and commands are listed in
`doc/vim-go.txt`. Note that help tags needs to be populated. Check your plugin
manager settings to generate the documentation (some do it automatically).
After that just open the help page to see all commands:

    :help vim-go

## Example Mappings

vim-go has several `<Plug>` mappings which can be used to create custom
mappings. Unless otherwise specified, none of these mappings are enabled
by default. Here some examples you might find useful:

Run commands such as `go run` for the current file with `<leader>r` or `go
build` and `go test` for the current package with `<leader>b` and `<leader>t`
respectively. Display beautifully annotated source code to see which functions
are covered with `<leader>c`.

```vim
au FileType go nmap <leader>r <Plug>(go-run)
au FileType go nmap <leader>b <Plug>(go-build)
au FileType go nmap <leader>t <Plug>(go-test)
au FileType go nmap <leader>c <Plug>(go-coverage)
```

By default the mapping `gd` is enabled, which opens the target identifier in
current buffer. You can also open the definition/declaration, in a new vertical,
horizontal, or tab, for the word under your cursor:

```vim
au FileType go nmap <Leader>ds <Plug>(go-def-split)
au FileType go nmap <Leader>dv <Plug>(go-def-vertical)
au FileType go nmap <Leader>dt <Plug>(go-def-tab)
```

Open the relevant Godoc for the word under the cursor with `<leader>gd` or open
it vertically with `<leader>gv`

```vim
au FileType go nmap <Leader>gd <Plug>(go-doc)
au FileType go nmap <Leader>gv <Plug>(go-doc-vertical)
```

Or open the Godoc in browser

```vim
au FileType go nmap <Leader>gb <Plug>(go-doc-browser)
```

Show a list of interfaces which is implemented by the type under your cursor
with `<leader>s`

```vim
au FileType go nmap <Leader>s <Plug>(go-implements)
```

Show type info for the word under your cursor with `<leader>i` (useful if you
have disabled auto showing type info via `g:go_auto_type_info`)

```vim
au FileType go nmap <Leader>i <Plug>(go-info)
```

Rename the identifier under the cursor to a new name

```vim
au FileType go nmap <Leader>e <Plug>(go-rename)
```

More `<Plug>` mappings can be seen with `:he go-mappings`. Also these are just
recommendations, you are free to create more advanced mappings or functions
based on `:he go-commands`.

## Settings
Below are some settings you might find useful. For the full list see `:he
go-settings`.

By default syntax-highlighting for Functions, Methods and Structs is disabled.
To change it:
```vim
let g:go_highlight_functions = 1
let g:go_highlight_methods = 1
let g:go_highlight_fields = 1
let g:go_highlight_types = 1
let g:go_highlight_operators = 1
let g:go_highlight_build_constraints = 1
```

Enable goimports to automatically insert import paths instead of gofmt:

```vim
let g:go_fmt_command = "goimports"
```

By default vim-go shows errors for the fmt command, to disable it:

```vim
let g:go_fmt_fail_silently = 1
```

Disable auto fmt on save:

```vim
let g:go_fmt_autosave = 0
```

Disable opening browser after posting your snippet to `play.golang.org`:

```vim
let g:go_play_open_browser = 0
```

By default when `:GoInstallBinaries` is called, the binaries are installed to
`$GOBIN` or `$GOPATH/bin`. To change it:

```vim
let g:go_bin_path = expand("~/.gotools")
let g:go_bin_path = "/home/fatih/.mypath"      "or give absolute path
```

Disable updating dependencies when installing/updating binaries:
```vim
let g:go_get_update = 0
```

### Using with Neovim (beta)

Note: Neovim currently is not a first class citizen for vim-go. You are free
to open bugs but I'm not going to look at them. Even though I'm using Neovim
myself, Neovim itself is still alpha. So vim-go might not work well as good as
in Vim. I'm happy to accept pull requests or very detailed bug reports.

Run `:GoRun` in a new tab, horizontal split or vertical split terminal

```vim
au FileType go nmap <leader>rt <Plug>(go-run-tab)
au FileType go nmap <Leader>rs <Plug>(go-run-split)
au FileType go nmap <Leader>rv <Plug>(go-run-vertical)
```

By default new terminals are opened in a vertical split. To change it

```vim
let g:go_term_mode = "split"
```

By default the testing commands run asynchronously in the background and
display results with `go#jobcontrol#Statusline()`. To make them run in a new
terminal

```vim
let g:go_term_enabled = 1
```

### Using with Syntastic
Sometimes when using both `vim-go` and `syntastic` Vim will start lagging while
saving and opening files. The following fixes this:

```vim
let g:syntastic_go_checkers = ['golint', 'govet', 'errcheck']
let g:syntastic_mode_map = { 'mode': 'active', 'passive_filetypes': ['go'] }
```

Another issue with `vim-go` and `syntastic` is that the location list window
that contains the output of commands such as `:GoBuild` and `:GoTest` might not appear.
To resolve this:

```vim
let g:go_list_type = "quickfix"
```

## More info

Check out the [Wiki](https://github.com/fatih/vim-go/wiki) page for more
information. It includes
[Screencasts](https://github.com/fatih/vim-go/wiki/Screencasts), an [FAQ
section](https://github.com/fatih/vim-go/wiki/FAQ-Troubleshooting), and many
other [various pieces](https://github.com/fatih/vim-go/wiki) of information.

## Donation

People have asked for this for a long time, now you can be a fully supporter by
[being a patron](https://www.patreon.com/fatih)!

By being a patron, you are enabling vim-go to grow and mature, helping me to
invest in bug fixes, new documentation, and improving both current and future
features. It's completely optional and is just a direct way to support Vim-go's
ongoing development. Thanks!

[https://www.patreon.com/fatih](https://www.patreon.com/fatih)

## Credits

* Go Authors for official vim plugins
* Gocode, Godef, Golint, Guru, Goimports, Gotags, Errcheck projects and
  authors of those projects.
* Other vim-plugins, thanks for inspiration (vim-golang, go.vim, vim-gocode,
  vim-godef)
* [Contributors](https://github.com/fatih/vim-go/graphs/contributors) of vim-go

## License

The BSD 3-Clause License - see `LICENSE` for more details


text:
require 'time'

module Gilt
  # A Gilt Sale object, representing an active or upcoming "flash" sale.
  class Sale
    class << self
      Gilt::Client::Sales.resources.keys.each do |key|
        define_method key do |params, &block|
          args = params || {}
          apikey = args[:apikey]
          affid = args[:affid]
          products = product_client apikey, affid
          req = client(apikey, affid).send(key.to_sym, args)
          response = req.perform.parse
          if response["sales"].nil?
            [self.new(response, products)]
          else
            response["sales"].map {|sale| self.new(sale, products)}
          end
        end
      end
    end

    def self.client(apikey, affid=nil)
      Gilt::Client::Sales.new(apikey, affid)
    end

    def self.product_client(apikey, affid=nil)
      Gilt::Client::Products.new(apikey, affid)
    end

    def self.create(store, sale_key, apikey, affid=nil)
      detail(:store => store, :sale_key => sale_key, :apikey => apikey, :affid => affid).first
    end

    def initialize(sale_body, client=nil)
      @sale = sale_body
      @client = client
    end

    def name
      @sale["name"]
    end

    def store
      @sale["store"].intern
    end

    def sale_key
      @sale["sale_key"]
    end

    def sale
      URI(@sale["sale"])
    end

    def sale_url
      URI(@sale["sale_url"])
    end

    def images
      @sale["image_urls"]
    end

    def description
      @sale["description"]
    end

    def begins
      Time.parse @sale["begins"]
    end

    def ends
      end_time = @sale["ends"]
      Time.parse end_time unless end_time.nil?
    end

    def ended?
      return false if ends.nil?
      ends < Time.now
    end

    def duration
      (ends - begins).ceil unless ends.nil?
    end

    def products
      return @products unless @products.nil?
      resource = Gilt::Client::Products.resources[:detail]
      @products = (@sale["products"] || []).map do |product|
        id = resource.url.extract(product)["product_id"]
        Product.defer @client.detail(:product_id => id).perform
      end
    end

    def length
      return products.length
    end

  end
end


text:
using App.Api.Models;
using App.Common.Db;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;

namespace App.Functional.Api.Controllers{

    public class ControllerFixture<T> : IDisposable where T : Controller
    {
        private AppDbScope _initDbScope;
        private AppDb _initDb;
        private AppDbScope _controllerDbScope;
        private AppDb _controllerDb;
        private T _controller;

        public T Controller => _controller;
        public readonly Author Author;
        public readonly List<Post> Posts = new List<Post>();

        public ControllerFixture()
        {
            _initDbScope = new AppDbScope();
            _initDb = _initDbScope.AppDb;
            _controllerDbScope = new AppDbScope();
            _controllerDb = _controllerDbScope.AppDb;
            _controller = (T)Activator.CreateInstance(typeof(T), _controllerDb);

            Author = new Author{
                Name = "author 0"
            };
            _initDb.Authors.Add(Author);
            for (var i=0; i<3; i++){
                var post = new Post{
                    Author = Author,
                    Title = $"title {i}",
                    Content = $"content {i}",
                };
                Posts.Add(post);
                _initDb.Posts.Add(post);
            }
            _initDb.SaveChanges();
        }

        public void Dispose()
        {
            if (_controllerDb != null){
                _controllerDb.Dispose();
                _controllerDb = null;
            }
            if (_controllerDbScope != null){
                _controllerDbScope.Dispose();
                _controllerDbScope = null;
            }
            if (_controller != null){
                _controller.Dispose();
                _controller = null;
            }
            if (_initDb != null){
                _initDb.Posts.RemoveRange(Posts);
                _initDb.Authors.Remove(Author);
                _initDb.SaveChanges();
                _initDb.Dispose();
                _initDb = null;
            }
            if (_initDbScope != null)
            {
                _initDbScope.Dispose();
                _initDbScope = null;
            }
        }
    }

}


text:
package org.blockartistry.mod.Restructured.util;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class WeightTable<T extends WeightTable.Item> {

	static final Random random = new Random();

	private ArrayList<T> items = new ArrayList<T>();
	private Random rand = random;
	private int totalWeight = 0;

	public static abstract class Item implements Cloneable {

		public final int itemWeight;
		protected final Random rnd;

		public Item(int weight) {
			this.itemWeight = weight;
			this.rnd = random;
		}

		@Override
		public Object clone() throws CloneNotSupportedException {
			return super.clone();
		}
	}

	public WeightTable() {
		this(null);
	}

	public WeightTable(Random rand) {
		if (rand != null)
			this.rand = rand;
	}

	public void add(T entry) {
		totalWeight += entry.itemWeight;
		items.add(entry);
	}

	public void remove(T entry) {
		if(items.remove(entry))
			totalWeight -= entry.itemWeight;
	}

	public T next() {

		assert totalWeight > 0;

		int targetWeight = rand.nextInt(totalWeight);

		int i = 0;
		for (i = items.size(); (targetWeight -= items.get(i - 1).itemWeight) >= 0; i--)
			;

		return items.get(i - 1);
	}

	public int size() {
		return items.size();
	}

	public List<T> getEntries() {
		return Collections.unmodifiableList(items);
	}

	public int getTotalWeight() {
		return totalWeight;
	}

	public void diagnostic(String title, Writer writer) throws IOException {

		writer.write(String.format("\nWeight table [%s] (total weight %d):\n",
				title, totalWeight));
		writer.write("==========================================================\n");
		for (Item i : items)
			writer.write(String.format("%5.1f%% (%4d) %s\n",
					(double) i.itemWeight * 100F / totalWeight, i.itemWeight,
					i.toString()));
	}
}