text:
from django.contrib import messages
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.views import logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.contrib.auth import login
from django.db import transaction

from django.shortcuts import render, reverse, redirect, HttpResponse, HttpResponseRedirect
from django.utils.functional import lazy
from django.views.generic import UpdateView, DetailView

from django.template.loader import render_to_string
from django.contrib.auth import get_user_model

from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_text
from django.utils.http import urlsafe_base64_decode

from apps.register.tokens import account_activation_token
from . import models
from . import forms
from . models import ProfileImage
from apps.user.models import User

reverse_lazy = lazy(reverse, str)

@login_required
def show_me(request):
    ''' shows user profile '''
    return render(
        request,
        'profile/me.html',
        {
            'last_projects': request.user.project_set.order_by('-updated', '-created')[:5]
        }
    )

def show(request, name = 'me'):
    if (name == 'me'):
        return show_me(request)
    user = get_user_model().objects.get(username=name)
    return render(
        request,
        'profile/profile.html',
        {
            'profile': user.profile,
            'last_projects': user.project_set.filter(visibility=True).order_by('-updated', '-created')[:5]
        }
    )

class ProfileUpdate(LoginRequiredMixin, UpdateView):
    success_url=reverse_lazy('profile:index')
    model = models.Profile
    template_name_suffix = '_update'
    fields = ['company', 'info', 'visibility_mail', 'visibility_company', 'visibility_info','visibility_first_name','visibility_last_name','expert']

    def get_object(self):
        try:
            return self.request.user.profile
        except ObjectDoesNotExist:
            return models.Profile(user=self.request.user)

    def get_context_data(self, **kwargs):
        data = super(ProfileUpdate, self).get_context_data(**kwargs)
        if self.request.method == 'POST':
            data['first_name'] = self.request.POST.get('first_name')
            data['last_name'] = self.request.POST.get('last_name')
            data['profile_image'] = forms.ProfileImageFormSet(self.request.POST, self.request.FILES, instance=self.object)
        else:
            data['profile_image'] = forms.ProfileImageFormSet(instance=self.object)
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        profile_image = context['profile_image']
        UserForm = forms.UserForm(data=context, instance=self.request.user)

        self.object = form.save()

        if UserForm.is_valid():
            UserForm.save()

        if profile_image.is_valid():
            profile_image.save()
        return super(ProfileUpdate, self).form_valid(form)

class ProfileImageUpdate(LoginRequiredMixin, UpdateView):
    success_url=reverse_lazy('profile:index')
    model = models.ProfileImage
    template_name_suffix = '_update'
    fields = ['path']

    def get_object(self):
        profile = ProfileUpdate(request=self.request).get_object()
        try:
            return profile.profileimage
        except ObjectDoesNotExist:
            return models.ProfileImage(profile=profile)

def deleteProfileImage(request):
    try:
        request.user.profile.profileimage.delete()
    except ProfileImage.DoesNotExist:
        pass
    return redirect(reverse('profile:edit'))

def change_email(request):
    if request.method == 'POST':
        mailer = {'newMail1': request.POST.get('mail'),
                  'newMail2': request.POST.get('newMail2'),}
        mail = mailer.get('newMail1')
        try:
            # prueft auf verschiedene fehler (dopplung in DB und beide felder gleich)
            if not mailer.get('newMail2') == mail:
                return render(request, 'profile/changeEmail.html',{'error': 'E-mail Adresse stimmt nicht überein!'})
            elif mail == '':
                return render(request, 'profile/changeEmail.html', {'error': 'Bitte geben sie eine Email Adresse an'})
            else:
                mailc = get_user_model().objects.get(email=mail)
                return render(request, 'profile/changeEmail.html', {'error': 'E-mail bereits vergeben'})
        except:
            mailc=None
        if mailc is None:
            token = account_activation_token.make_token(request.user)
            uid = urlsafe_base64_encode(force_bytes(request.user.pk)).decode()
            umail = urlsafe_base64_encode(force_bytes(mail)).decode()
            current_site = get_current_site(request)
            domain = current_site.domain

            mes = render_to_string('profile/newMail.html', {
                'use_https': request.is_secure(),
                'domain':domain,
                'uid': uid,
                'token': token,
                'mail': umail,
                'user': request.user,
            })

            email = EmailMessage(
                subject='Rattler: Email ändern',
                body=mes,
                to=[mail]
            )
            email.send()

            update_session_auth_hash(request, request.user)

            return render(request, 'profile/sendEmail.html')

    return render(request, 'profile/changeEmail.html')

def change_email_success (request, mail, uidb64, token):
    # get user from user id
    from django.contrib.auth import get_user_model
    try:
        uid = force_text(urlsafe_base64_decode(uidb64))
        user = get_user_model().objects.get(pk=uid)
    except (TypeError, ValueError, OverflowError, get_user_model().DoesNotExist):
        user = None

    if not user is None and account_activation_token.check_token(user=user, token=token):
        email = force_text(urlsafe_base64_decode(mail))
        user.email = email
        user.save()
        update_session_auth_hash(request, user)
        login(request=request,user= user)
        return redirect(reverse('profile:edit'))
    else:
        return render(request, 'profile/failChangeEmail.html')

def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)
            return redirect(reverse('profile:edit'))
        else:
            messages.error(request, 'Neues Passwort stimmt nicht überein')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'profile/changePassword.html', {
        'form': form
    })

def delete_account(request):

    User.objects.filter(id=request.user.id).update(is_active=False)

    return redirect(reverse('logout'))


text:
delete from item;
ALTER TABLE item ADD COLUMN timestamp DATETIME

redpajama_set_name: RedPajamaGithub


text:
Horizontal

  <jqxProgressBar #horizontal
                  [width]="250" [height]="30" [value]="50">
  </jqxProgressBar>

Vertical

  <jqxProgressBar #vertical
                  [width]="30" [height]="250" [value]="50" [orientation]="'vertical'">
  </jqxProgressBar>

Enter a value between 0 and 100

  <jqxInput #ValueInput></jqxInput>

  <jqxButton (onClick)="onClick()">Update</jqxButton>
  <jqxCheckBox (onChange)="onCheckBox($event)">
    Show Progress Text
  </jqxCheckBox>
  <jqxCheckBox (onChange)="onCustomTextCheckBox($event)">
    Custom Progress Text
  </jqxCheckBox>


text:
package webp

const cgoIsUnsafePtr = true


text:
using System;
using System.Collections.Generic;
using System.Json;
using System.Net.Http;

namespace NCDO.Interfaces
{
    public interface ICDORequest
    {
        /// <summary>
        /// A reference to an object with a property named operations, which is an array containing the request objects for each of the one or more Data Object record-change operations performed in response to calling the CDO saveChanges( ) method either with an empty parameter list;
        /// </summary>
        IEnumerable<ICDORequest> Batch { get; }

        /// <summary>
        /// For an invoke operation, the name of the CDO invocation method that called the operation.
        /// </summary>
        string FnName { get; }

        /// <summary>
        /// An object reference to the CDO that performed the operation returning the request object.
        /// </summary>
        ICloudDataObject CDO { get; }
        /// <summary>
        /// An object reference to the record created, updated, or deleted by the current Data Object record-change operation.
        /// </summary>
        ICloudDataRecord Record { get; }
        /// <summary>
        /// A reference to the object, if any, that was passed as an input parameter to the CDO method that has returned the current request object.
        /// </summary>
        JsonObject ObjParam { get; }
        /// <summary>
        /// Returns an object whose properties contain data from a Data Object built-in or invoke operation executed on the Cloud Data Server.
        /// </summary>
        JsonObject Response { get; }
        /// <summary>
        /// A Boolean that when set to true indicates that the Data Object operation was successfully executed.
        /// </summary>
        bool? Success { get; }

        #region Passthrough props
        HttpResponseMessage ResponseMessage { get; }
        Uri RequestUri { get; }
        HttpMethod Method { get; }
        #endregion

        /// <summary>
        /// Indicate if request affects cdo memory
        /// </summary>
        bool CdoMemory { get; set; }
    }
}


text:
#include "StdAfx.h"
#include "XmlDataHandler.h"

using namespace ScutDataLogic;

CXmlDataHandler::CXmlDataHandler(void)
{
}

CXmlDataHandler::~CXmlDataHandler(void)
{
}

bool ScutDataLogic::CXmlDataHandler::HandleData( int nTag, CStream& dataStream, LPVOID lpData )
{
	bool bRet = false;
	CMarkup* pMarkup = this->ParseMarkupData(dataStream);
	if (pMarkup)
	{
		bRet = DoHandleData(nTag, pMarkup, lpData);
		delete pMarkup;
	}
	return bRet;
}

bool ScutDataLogic::CXmlDataHandler::HandleProgress( int nTag, int nProgress, LPVOID lpData )
{
	return false;
}

CMarkup* ScutDataLogic::CXmlDataHandler::ParseMarkupData( CStream& dataStream )
{
	int nSize = dataStream.GetSize();
	if (nSize == 0)
	{
		return NULL;
	}

	CMarkup* pMarkup = new CMarkup();
	char* pBuffer = new char[nSize + 1];
	dataStream.SetPosition(0);

	if (dataStream.ReadBuffer(pBuffer, nSize))
	{
		pBuffer[nSize] = '\0';
#ifdef WIN32
		if (pMarkup->DetectUTF8(pBuffer, nSize))
		{
			std::string temp = pMarkup->UTF8ToA(pBuffer);
            //std::string temp = utf8ToGB2312(pBuffer, nSize);
			pMarkup->SetDoc(temp.c_str());
		}
		else
			pMarkup->SetDoc(pBuffer, nSize);
#else
		pMarkup->SetDoc(pBuffer, nSize);
#endif
	}
	delete []pBuffer;
	return pMarkup;
}

bool ScutDataLogic::CXmlDataHandler::DoHandleData( int nTag, CMarkup* pMarkup, LPVOID lpData )
{
	return false;
}


text:
package fi.csc.microarray.messaging.message;

import java.util.HashMap;

import javax.jms.JMSException;
import javax.jms.MapMessage;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class JsonMessage extends ChipsterMessage {

	private final static String KEY_JSON = "json";
	public static final String KEY_STATUS_REPORT = "status-report";

	private String value;

	public JsonMessage() {
		super();
	}

	public JsonMessage(String value) {
		super();
		this.value = value;
	}

	public String getJson() {
		return value;
	}

	public void unmarshal(MapMessage from) throws JMSException {
		super.unmarshal(from);
		this.value = from.getString(KEY_JSON);
	}

	public void marshal(MapMessage mapMessage) throws JMSException {
		super.marshal(mapMessage);
		mapMessage.setString(KEY_JSON, this.value);
	}

	public void setCommnad(String command) {
		HashMap<String, String> jsonMap = new HashMap<>();
		jsonMap.put("command", command);
		this.value = new Gson().toJson(jsonMap);
	}

	public String getValue(String key) {
		JsonObject jobj = new Gson().fromJson(this.value, JsonObject.class);
		return jobj.get(key).toString();
	}
}


text:
package org.elasticsearch.common;

import java.util.Set;

/**
 *
 */
public interface HasHeaders {

    <V> void putHeader(String key, V value);

    <V> V getHeader(String key);

    boolean hasHeader(String key);

    Set<String> getHeaders();

    void copyHeadersFrom(HasHeaders from);
}


text:
require "font-awesome-more-rails/version"
require "font-awesome-more-rails/engine" if defined?(::Rails)


text:
from __future__ import print_function, unicode_literals

laboratory_assigned_experiments = {
        'exp1:dummy1@Dummy experiments':
            {
                 'coord_address': 'experiment_dummy1:main_instance@provider2_machine',
                 'checkers': ()
            },
        'exp1:dummy4@Dummy experiments':
            {
                 'coord_address': 'experiment_dummy4:main_instance@provider2_machine',
                 'checkers': ()
            },
    }


text:
/*=========================================================================
 *
 *  Portions of this file are subject to the VTK Toolkit Version 3 copyright.
 *
 *  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
 *
 *  For complete copyright, license and disclaimer of warranty information
 *  please refer to the NOTICE file at the top of the ITK source tree.
 *
 *=========================================================================*/
#ifndef itkInPlaceLabelMapFilter_h
#define itkInPlaceLabelMapFilter_h

#include "itkLabelMapFilter.h"

namespace itk
{
/**
 *\class InPlaceLabelMapFilter
 * \brief Base class for filters that takes an image as input and overwrites
 * that image as the output
 *
 * InPlaceLabelMapFilter is the base class for all process objects whose
 * output image data is constructed by overwriting the input image
 * data. In other words, the output bulk data is the same block of
 * memory as the input bulk data.  This filter provides the mechanisms
 * for in place image processing while maintaining general pipeline
 * mechanics. InPlaceLabelMapFilters use less memory than standard
 * ImageToImageFilters because the input buffer is reused as the
 * output buffer.  However, this benefit does not come without a cost.
 * Since the filter overwrites its input, the ownership of the bulk
 * data is transitioned from the input data object to the output data
 * object.  When a data object has multiple consumers with one
 * of the consumers being an in place filter, the in place filter
 * effectively destroys the bulk data for the data object. Upstream
 * filters will then have to re-execute to regenerate the data object's
 * bulk data for the remaining consumers.
 *
 * Since an InPlaceLabelMapFilter reuses the input bulk data memory for the
 * output bulk data memory, the input image type must match the output
 * image type.  If the input and output image types are not identical,
 * the filter reverts to a traditional ImageToImageFilter behaviour
 * where an output image is allocated.  In place operation can also be
 * controlled (when the input and output image type match) via the
 * methods InPlaceOn() and InPlaceOff().
 *
 * Subclasses of InPlaceLabelMapFilter must take extra care in how they
 * manage memory using (and perhaps overriding) the implementations of
 * ReleaseInputs() and AllocateOutputs() provided here.
 *
 *
 * This code was contributed in the Insight Journal paper:
 * "Label object representation and manipulation with ITK"
 * by Lehmann G.
 * https://www.insight-journal.org/browse/publication/176
 *
 *
 * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction,
 *  INRA de Jouy-en-Josas, France.
 *
 * \sa LabelMapToBinaryImageFilter, LabelMapToLabelImageFilter
 * \ingroup ImageEnhancement  MathematicalMorphologyImageFilters
 * \ingroup ITKLabelMap
 */
template <typename TInputImage>
class ITK_TEMPLATE_EXPORT InPlaceLabelMapFilter : public LabelMapFilter<TInputImage, TInputImage>
{
public:
  ITK_DISALLOW_COPY_AND_MOVE(InPlaceLabelMapFilter);

  /** Standard class type aliases. */
  using Self = InPlaceLabelMapFilter;
  using Superclass = LabelMapFilter<TInputImage, TInputImage>;
  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Run-time type information (and related methods). */
  itkTypeMacro(InPlaceLabelMapFilter, LabelMapFilter);

  /** Standard New method. */
  itkNewMacro(Self);

  /** Superclass type alias. */
  using typename Superclass::OutputImageType;
  using typename Superclass::OutputImagePointer;
  using typename Superclass::OutputImageRegionType;
  using typename Superclass::OutputImagePixelType;

  /** Some convenient type alias. */
  using InputImageType = TInputImage;
  using InputImagePointer = typename InputImageType::Pointer;
  using InputImageConstPointer = typename InputImageType::ConstPointer;
  using InputImageRegionType = typename InputImageType::RegionType;
  using InputImagePixelType = typename InputImageType::PixelType;
  using LabelObjectType = typename InputImageType::LabelObjectType;

  using PixelType = typename InputImageType::PixelType;
  using IndexType = typename InputImageType::IndexType;
  using RegionType = typename InputImageType::RegionType;

  using TOutputImage = TInputImage;

  /** ImageDimension constants */
  static constexpr unsigned int InputImageDimension = TInputImage::ImageDimension;
  static constexpr unsigned int OutputImageDimension = TOutputImage::ImageDimension;

  /** In place operation can be turned on and off. This only has an
   * effect when the input and output image type match. */
  itkSetMacro(InPlace, bool);
  itkGetMacro(InPlace, bool);
  itkBooleanMacro(InPlace);

  /** Can the filter run in place? To do so, the filter's first input
   * and output must have the same dimension and pixel type. This
   * method can be used in conjunction with the InPlace ivar to
   * determine whether a particular use of the filter is really
   * running in place. Some filters may be able to optimize their
   * operation if the InPlace is true and CanRunInPlace is true. */
  bool
  CanRunInPlace() const
  {
    return true; // used to test if TInputImage == TOutputImage. But
                 // if you look above, the superclass declaration
                 // specifies
                 // LabelMapFilter<TInputImage,TOutputImage> so there's
                 // no way this couldn't be true.
  }

protected:
  InPlaceLabelMapFilter() = default;
  ~InPlaceLabelMapFilter() override = default;

  void
  PrintSelf(std::ostream & os, Indent indent) const override;

  /** The GenerateData method normally allocates the buffers for all
   * of the outputs of a filter. Since InPlaceLabelMapFilter's can use an
   * overwritten version of the input for its output, the output
   * buffer should not be allocated. When possible, we graft the input
   * to the filter to the output.  If an InPlaceFilter has multiple
   * outputs, then it would need to override this method to graft one
   * of its outputs and allocate the remaining. If a filter is
   * threaded (i.e. it provides an implementation of
   * ThreadedGenerateData()), this method is called automatically. If
   * an InPlaceFilter is not threaded (i.e. it provides an
   * implementation of GenerateData()), then this method (or
   * equivalent) must be called in GenerateData(). */
  void
  AllocateOutputs() override;

  /**
   * Return the output label collection image, instead of the input as in the default
   * implementation
   */
  InputImageType *
  GetLabelMap() override
  {
    return this->GetOutput();
  }

private:
  bool m_InPlace{ true };
};
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#  include "itkInPlaceLabelMapFilter.hxx"
#endif

#endif


text:
package net.ltgt.cookietests;

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.simple.SimpleContainerFactory;
import org.glassfish.jersey.simple.SimpleServer;
import org.junit.After;
import org.junit.Before;

import com.squareup.okhttp.HttpUrl;

public class JerseySimpleTest extends OkHttpTest {

  SimpleServer server;

  @Before public void setUp() {
    server = SimpleContainerFactory.create(getUrl("/").uri(), ResourceConfig.forApplicationClass(Application.class));
  }

  @After public void tearDown() throws Exception {
    server.close();
  }

  @Override
  protected HttpUrl getUrl(String path) {
    return new HttpUrl.Builder()
        .scheme("http")
        .host("localhost")
        .port(9998) // TODO
        .encodedPath(path)
        .build();
  }
}


text:
"""
Sponge Knowledge Base
Heartbeat 2
"""

from java.util.concurrent.atomic import AtomicBoolean

def onInit():
    sponge.setVariable("soundTheAlarm", AtomicBoolean(False))

# Sounds the alarm when heartbeat event stops occurring at most every 2 seconds.
class HeartbeatRule(Rule):
    def onConfigure(self):
        self.withEvents(["heartbeat h1", "heartbeat h2 :none"]).withDuration(Duration.ofSeconds(2))
    def onRun(self, event):
        self.logger.info("Sound the alarm!")
        sponge.getVariable("soundTheAlarm").set(True)

def onStartup():
    sponge.event("heartbeat").send()
    sponge.event("heartbeat").sendAfter(1000)


text:
#ifndef CLIENT_H
#define CLIENT_H

#include <unistd.h>
#include <sys/socket.h>

#include "util.h"
#include "uvhost.h"

/* FDs First initialization value
 *
 * The value is set, cause to be sure, that FD is not opened and/or
 * the function shm_open does not returns an error.
 *
 */
#define CLIENT_INIT_FD_VAL (-2)
#define QEMU_PROT_VERSION (0x01)

typedef struct Client {
    char socket_path[UNIX_PATH_MAX];
    int socket;
    char sh_mem_path[UNIX_PATH_MAX];
    int sh_mem_fds[VHOST_MEMORY_MAX_NREGIONS];
} Client;

typedef enum {
    E_CLIENT_OK = EXIT_SUCCESS,
    E_CLIENT_ERR,
    E_CLIENT_ERR_ALLOC,
    E_CLIENT_ERR_UNK,
    E_CLIENT_ERR_FARG,
    E_CLIENT_ERR_SOCK,
    E_CLIENT_ERR_CONN,
    E_CLIENT_ERR_IOCTL_SEND,
    E_CLIENT_ERR_IOCTL_REPLY,
    E_CLIENT_ERR_VIOCTL,
    E_CLIENT_VIOCTL_REPLY,
    E_CLIENT_LAST
} CLIENT_H_RET_VAL;

int client_close_fds(Client *client);
int client_disconnect_socket(Client *client);
int client_init_Client(Client *client, const char *path);
int client_vhost_ioctl(Client *client, VhostUserRequest request, void *req_ptr);
#endif


text:
#ifndef __PRIVATETYPES__
#define __PRIVATETYPES__

#ifdef __cplusplus
extern "C" {
#endif

// all the 4D Application internal structures use 2 bytes alignment
#pragma pack(push,2)

// used for query operations.
typedef struct LineBlock
{
	char				fOperator;
	short				fField;
	short				fTable;
	char				fComparison;
	union
	{
		char				fString[42];
		double				fReal;
		PA_Date				fDate;
		PA_long32				fLongint;
		short				fInteger;
		char				fBoolean;
		PA_Unichar*			fUnichars;
	} uValue;
} LineBlock;

// This structure is always sent when calling back 4D Application.
// the different fields are used depending the kind of
// the action required.
typedef struct EngineBlock
{
// New v11 fields for Unicode support
	PA_Unichar			fUName[256];
	PA_Unichar			fUString[256];
	PA_Unistring		fUniString1;
	PA_Unistring		fUniString2;
	PA_Picture			fPicture;
	void*				fPtr1;
	void*				fPtr2;
	void*				fPtr3;
// all the following records are identical
// to the EngineBlock of 4D 2004
	short				fTable;
	short				fField;
	PA_long32				fRecord;
	char				fManyToOne;
	char				fOneToMany;
	char				fName[256];
	PA_Handle			fHandle;
	short				fError;
	sLONG_PTR			fParam1;
	sLONG_PTR			fParam2;
	sLONG_PTR			fParam3;
	sLONG_PTR			fParam4;
	double				fReal;
	short				fFiller;
	PA_Date				fDate;
	PA_long32				fLongint;
	short				fShort;
	char				fString[82];
	short				fTextSize;
	PA_Handle			fTextHandle;
	char				fClearOldVariable;
	char				fNativeReal;
	short				fNbSearchLines;
} EngineBlock;

// facility to call back 4D more easily using the proc pointer
#define Call4D(s,p) (*gCall4D)(s,p)

#if VERSIONMAC
	#define FOURDCALL pascal __attribute__((visibility("default"))) void
#elif VERSIONWIN
	#define FOURDCALL void __stdcall
#endif

#if VERSIONMAC
	typedef pascal void (*Call4DProcPtr)( short, EngineBlock* );
#elif VERSIONWIN
	typedef void (__stdcall *Call4DProcPtr)( short, EngineBlock* );
#endif

FOURDCALL FourDPackex( PA_long32 selector, void* params, void** data, void* result );

extern Call4DProcPtr gCall4D;

// this structure is sent to Plugin at init.
typedef struct PackInitBlock
{
	PA_long32			fVersion;
	PA_long32			fLength;
	PA_long32			fCPUType;
	Call4DProcPtr	fCall4D;
 	PA_long32			fSupportedVersion;
	Call4DProcPtr	fCall4Dex;
} PackInitBlock;

// reset struct alignment
#pragma pack(pop)

#ifdef __cplusplus
}
#endif

#endif


text:
QHttpServer
===========

A Qt HTTP Server - because hard-core programmers write web-apps in C++ :)

It uses Ryan Dahl's [HTTP Parser](http://github.com/ry/http-parser) and is asynchronous and does not require any inheritance.

**NOTE: QHttpServer is NOT fully HTTP compliant right now! DO NOT use it for
anything complex**

Installation
------------

Requires Qt 4.

    qmake && make && su -c 'make install'

To link to your projects put this in your project's qmake project file

    LIBS += -lqhttpserver

Usage
-----

Include the headers

    #include <qhttpserver.h>
    #include <qhttprequest.h>
    #include <qhttpresponse.h>

Create a server, and connect to the signal for new requests

    QHttpServer *server = new QHttpServer;
    connect(server, SIGNAL(newRequest(QHttpRequest*, QHttpResponse*)),
            handler, SLOT(handle(QHttpRequest*, QHttpResponse*)));

    // let's go
    server->listen(8080);

In the handler, you may dispatch on routes or do whatever other things
you want. See the API documentation for what information
is provided about the request via the QHttpRequest object.

To send data back to the browser and end the request:

    void Handler::handle(QHttpRequest *req, QHttpResponse *resp)
    {
    	resp->setHeader("Content-Length", 11);
    	resp->writeHead(200); // everything is OK
    	resp->write("Hello World");
    	resp->end();
    }

The server and request/response objects emit various signals
and have guarantees about memory management. See the API documentation for
these.


text:
// Simple 2D OpenGL Functions

#include "../include/simple2d.h"

// Set to `true` to force OpenGL 2.1 (for testing)
static bool FORCE_GL2 = false;

// Flag set if using OpenGL 2.1
static bool S2D_GL2 = false;

// The orthographic projection matrix for 2D rendering.
// Elements 0 and 5 are set in S2D_GL_SetViewport.
static GLfloat orthoMatrix[16] =
  {    0,    0,     0,    0,
       0,    0,     0,    0,
       0,    0,     0,    0,
   -1.0f, 1.0f, -1.0f, 1.0f };

/*
 * Prints current GL error
 */
void S2D_GL_PrintError(char *error) {
  S2D_Log(S2D_ERROR, "%s (%d)", error, glGetError());
}

/*
 * Print info about the current OpenGL context
 */
void S2D_GL_PrintContextInfo(S2D_Window *window) {
  S2D_Log(S2D_INFO,
    "OpenGL Context\n"
    "      GL_VENDOR: %s\n"
    "      GL_RENDERER: %s\n"
    "      GL_VERSION: %s\n"
    "      GL_SHADING_LANGUAGE_VERSION: %s",
    window->S2D_GL_VENDOR,
    window->S2D_GL_RENDERER,
    window->S2D_GL_VERSION,
    window->S2D_GL_SHADING_LANGUAGE_VERSION
  );
}

/*
 * Store info about the current OpenGL context
 */
void S2D_GL_StoreContextInfo(S2D_Window *window) {

  window->S2D_GL_VENDOR   = glGetString(GL_VENDOR);
  window->S2D_GL_RENDERER = glGetString(GL_RENDERER);
  window->S2D_GL_VERSION  = glGetString(GL_VERSION);

  // These are not defined in GLES
  #if GLES
    window->S2D_GL_MAJOR_VERSION = 0;
    window->S2D_GL_MINOR_VERSION = 0;
  #else
    glGetIntegerv(GL_MAJOR_VERSION, &window->S2D_GL_MAJOR_VERSION);
    glGetIntegerv(GL_MINOR_VERSION, &window->S2D_GL_MINOR_VERSION);
  #endif

  window->S2D_GL_SHADING_LANGUAGE_VERSION = glGetString(GL_SHADING_LANGUAGE_VERSION);
};

/*
 * Creates a shader object, loads shader string, and compiles.
 * Returns 0 if shader could not be compiled.
 */
GLuint S2D_GL_LoadShader(GLenum type, const GLchar *shaderSrc, char *shaderName) {

  // Create the shader object
  GLuint shader = glCreateShader(type);

  if (shader == 0) {
    S2D_GL_PrintError("Failed to create shader program");
    return 0;
  }

  // Load the shader source
  glShaderSource(shader, 1, &shaderSrc, NULL);

  // Compile the shader
  glCompileShader(shader);

  // Check the compile status
  GLint compiled;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);

  if (!compiled) {
    GLint infoLen = 0;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen);

    if (infoLen > 1) {
      char *infoLog = malloc(sizeof(char) * infoLen);
      glGetShaderInfoLog(shader, infoLen, NULL, infoLog);
      printf("Error compiling shader \"%s\":\n%s\n", shaderName, infoLog);
      free(infoLog);
    }

    glDeleteShader(shader);
    return 0;
  }

  return shader;
}

/*
 * Check if shader program was linked
 */
int S2D_GL_CheckLinked(GLuint program, char *name) {

  GLint linked;
  glGetProgramiv(program, GL_LINK_STATUS, &linked);

  if (!linked) {
    GLint infoLen = 0;
    glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen);

    if (infoLen > 1) {
      char *infoLog = malloc(sizeof(char) * infoLen);
      glGetProgramInfoLog(program, infoLen, NULL, infoLog);
      printf("Error linking program `%s`: %s\n", name, infoLog);
      free(infoLog);
    }

    glDeleteProgram(program);
    return GL_FALSE;
  }

  return GL_TRUE;
}

/*
 * Calculate the viewport's scaled width and height
 */
void S2D_GL_GetViewportScale(S2D_Window *window, int *w, int *h, double *scale) {

  double s = fmin(
    window->width  / (double)window->viewport.width,
    window->height / (double)window->viewport.height
  );

  *w = window->viewport.width  * s;
  *h = window->viewport.height * s;

  if (scale) *scale = s;
}

/*
 * Sets the viewport and matrix projection
 */
void S2D_GL_SetViewport(S2D_Window *window) {

  int ortho_w = window->viewport.width;
  int ortho_h = window->viewport.height;
  int x, y, w, h;  // calculated GL viewport values

  x = 0; y = 0; w = window->width; h = window->height;

  switch (window->viewport.mode) {

    case S2D_FIXED:
      w = window->orig_width;
      h = window->orig_height;
      y = window->height - h;
      break;

    case S2D_EXPAND:
      ortho_w = w;
      ortho_h = h;
      break;

    case S2D_SCALE:
      S2D_GL_GetViewportScale(window, &w, &h, NULL);
      // Center the viewport
      x = window->width  / 2.0 - w/2.0;
      y = window->height / 2.0 - h/2.0;
      break;

    case S2D_STRETCH:
      break;
  }

  glViewport(x, y, w, h);

  // Set orthographic projection matrix
  orthoMatrix[0] =  2.0f / (GLfloat)ortho_w;
  orthoMatrix[5] = -2.0f / (GLfloat)ortho_h;

  #if GLES
    S2D_GLES_ApplyProjection(orthoMatrix);
  #else
    if (S2D_GL2) {
      S2D_GL2_ApplyProjection(ortho_w, ortho_h);
    } else {
      S2D_GL3_ApplyProjection(orthoMatrix);
    }
  #endif
}

/*
 * Initialize OpenGL
 */
int S2D_GL_Init(S2D_Window *window) {

  // Specify OpenGL contexts and set attributes
  #if GLES
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE,   8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,  8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
  #else
    // Use legacy OpenGL 2.1
    if (FORCE_GL2) {
      SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
      SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);

    // Request an OpenGL 3.3 forward-compatible core profile
    } else {
      SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
      SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
      SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
    }
  #endif

  // Create and store the OpenGL context
  if (FORCE_GL2) {
    window->glcontext = NULL;
  } else {
    // Ask SDL to create an OpenGL context
    window->glcontext = SDL_GL_CreateContext(window->sdl);
  }

  // Check if a valid OpenGL context was created
  if (window->glcontext) {
    // Valid context found

    // Initialize OpenGL ES 2.0
    #if GLES
      S2D_GLES_Init();
      S2D_GL_SetViewport(window);

    // Initialize OpenGL 3.3+
    #else
      // Initialize GLEW on Windows
      #if WINDOWS
        GLenum err = glewInit();
        if (GLEW_OK != err) S2D_Error("GLEW", glewGetErrorString(err));
      #endif
      S2D_GL3_Init();
      S2D_GL_SetViewport(window);
    #endif

  // Context could not be created
  } else {

    #if GLES
      S2D_Error("GLES / SDL_GL_CreateContext", SDL_GetError());

    #else
      // Try to fallback using an OpenGL 2.1 context
      SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
      SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);

      // Try creating the context again
      window->glcontext = SDL_GL_CreateContext(window->sdl);

      // Check if this context was created
      if (window->glcontext) {
        // Valid context found
        S2D_GL2 = true;
        S2D_GL2_Init();
        S2D_GL_SetViewport(window);

      // Could not create any OpenGL contexts, hard failure
      } else {
        S2D_Error("GL2 / SDL_GL_CreateContext", SDL_GetError());
        S2D_Log(S2D_ERROR, "An OpenGL context could not be created");
        return -1;
      }
    #endif
  }

  // Store the context and print it if diagnostics is enabled
  S2D_GL_StoreContextInfo(window);
  if (S2D_diagnostics) S2D_GL_PrintContextInfo(window);

  return 0;
}

/*
 * Creates a texture for rendering
 */
void S2D_GL_CreateTexture(GLuint *id, GLint format,
                          int w, int h,
                          const GLvoid *data, GLint filter) {

  // If 0, then a new texture; generate name
  if (*id == 0) glGenTextures(1, id);

  // Bind the named texture to a texturing target
  glBindTexture(GL_TEXTURE_2D, *id);

  // Specifies the 2D texture image
  glTexImage2D(
    GL_TEXTURE_2D, 0, format, w, h,
    0, format, GL_UNSIGNED_BYTE, data
  );

  // Set the filtering mode
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filter);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
}

/*
 * Free a texture
 */
void S2D_GL_FreeTexture(GLuint *id) {
  if (*id != 0) {
    glDeleteTextures(1, id);
    *id = 0;
  }
}

/*
 * Draw a triangle
 */
void S2D_GL_DrawTriangle(GLfloat x1, GLfloat y1,
                         GLfloat r1, GLfloat g1, GLfloat b1, GLfloat a1,
                         GLfloat x2, GLfloat y2,
                         GLfloat r2, GLfloat g2, GLfloat b2, GLfloat a2,
                         GLfloat x3, GLfloat y3,
                         GLfloat r3, GLfloat g3, GLfloat b3, GLfloat a3) {

  #if GLES
    S2D_GLES_DrawTriangle(x1, y1, r1, g1, b1, a1,
                          x2, y2, r2, g2, b2, a2,
                          x3, y3, r3, g3, b3, a3);
  #else
    if (S2D_GL2) {
      S2D_GL2_DrawTriangle(x1, y1, r1, g1, b1, a1,
                           x2, y2, r2, g2, b2, a2,
                           x3, y3, r3, g3, b3, a3);
    } else {
      S2D_GL3_DrawTriangle(x1, y1, r1, g1, b1, a1,
                           x2, y2, r2, g2, b2, a2,
                           x3, y3, r3, g3, b3, a3);
    }
  #endif
}

/*
 * Draw an image
 */
void S2D_GL_DrawImage(S2D_Image *img) {
  #if GLES
    S2D_GLES_DrawImage(img);
  #else
    if (S2D_GL2) {
      S2D_GL2_DrawImage(img);
    } else {
      S2D_GL3_DrawImage(img);
    }
  #endif
}

/*
 * Draw sprite
 */
void S2D_GL_DrawSprite(S2D_Sprite *spr) {
  #if GLES
    S2D_GLES_DrawSprite(spr);
  #else
    if (S2D_GL2) {
      S2D_GL2_DrawSprite(spr);
    } else {
      S2D_GL3_DrawSprite(spr);
    }
  #endif
}

/*
 * Draw text
 */
void S2D_GL_DrawText(S2D_Text *txt) {
  #if GLES
    S2D_GLES_DrawText(txt);
  #else
    if (S2D_GL2) {
      S2D_GL2_DrawText(txt);
    } else {
      S2D_GL3_DrawText(txt);
    }
  #endif
}

/*
 * Render and flush OpenGL buffers
 */
void S2D_GL_FlushBuffers() {
  // Only implemented in our OpenGL 3.3+ and ES 2.0 renderers
  #if GLES
    // TODO: S2D_GLES_FlushBuffers();
  #else
    if (!S2D_GL2) S2D_GL3_FlushBuffers();
  #endif
}

/*
 * Clear buffers to given color values
 */
void S2D_GL_Clear(S2D_Color clr) {
  glClearColor(clr.r, clr.g, clr.b, clr.a);
  glClear(GL_COLOR_BUFFER_BIT);
}


text:
/* True if we have allocno conflicts.  It is false for non-optimized
   mode or when the conflict table is too big.  */
extern bool ira_conflicts_p;

struct target_ira {
  /* Number of given class hard registers available for the register
     allocation for given classes.  */
  int x_ira_available_class_regs[N_REG_CLASSES];

  /* Map: hard register number -> allocno class it belongs to.  If the
     corresponding class is NO_REGS, the hard register is not available
     for allocation.  */
  enum reg_class x_ira_hard_regno_allocno_class[FIRST_PSEUDO_REGISTER];

  /* Number of allocno classes.  Allocno classes are register classes
     which can be used for allocations of allocnos.  */
  int x_ira_allocno_classes_num;

  /* The array containing allocno classes.  Only first
     IRA_ALLOCNO_CLASSES_NUM elements are used for this.  */
  enum reg_class x_ira_allocno_classes[N_REG_CLASSES];

  /* Map of all register classes to corresponding allocno classes
     containing the given class.  If given class is not a subset of an
     allocno class, we translate it into the cheapest allocno class.  */
  enum reg_class x_ira_allocno_class_translate[N_REG_CLASSES];

  /* Number of pressure classes.  Pressure classes are register
     classes for which we calculate register pressure.  */
  int x_ira_pressure_classes_num;

  /* The array containing pressure classes.  Only first
     IRA_PRESSURE_CLASSES_NUM elements are used for this.  */
  enum reg_class x_ira_pressure_classes[N_REG_CLASSES];

  /* Map of all register classes to corresponding pressure classes
     containing the given class.  If given class is not a subset of an
     pressure class, we translate it into the cheapest pressure
     class.  */
  enum reg_class x_ira_pressure_class_translate[N_REG_CLASSES];

  /* Bigest pressure register class containing stack registers.
     NO_REGS if there are no stack registers.  */
  enum reg_class x_ira_stack_reg_pressure_class;

  /* Maps: register class x machine mode -> maximal/minimal number of
     hard registers of given class needed to store value of given
     mode.  */
  unsigned char x_ira_reg_class_max_nregs[N_REG_CLASSES][MAX_MACHINE_MODE];
  unsigned char x_ira_reg_class_min_nregs[N_REG_CLASSES][MAX_MACHINE_MODE];

  /* Array analogous to target hook TARGET_MEMORY_MOVE_COST.  */
  short x_ira_memory_move_cost[MAX_MACHINE_MODE][N_REG_CLASSES][2];

  /* Array of number of hard registers of given class which are
     available for the allocation.  The order is defined by the
     allocation order.  */
  short x_ira_class_hard_regs[N_REG_CLASSES][FIRST_PSEUDO_REGISTER];

  /* The number of elements of the above array for given register
     class.  */
  int x_ira_class_hard_regs_num[N_REG_CLASSES];

  /* Function specific hard registers can not be used for the register
     allocation.  */
  HARD_REG_SET x_ira_no_alloc_regs;
};

extern struct target_ira default_target_ira;
#if SWITCHABLE_TARGET
extern struct target_ira *this_target_ira;
#else
#define this_target_ira (&default_target_ira)
#endif

#define ira_available_class_regs \
  (this_target_ira->x_ira_available_class_regs)
#define ira_hard_regno_allocno_class \
  (this_target_ira->x_ira_hard_regno_allocno_class)
#define ira_allocno_classes_num \
  (this_target_ira->x_ira_allocno_classes_num)
#define ira_allocno_classes \
  (this_target_ira->x_ira_allocno_classes)
#define ira_allocno_class_translate \
  (this_target_ira->x_ira_allocno_class_translate)
#define ira_pressure_classes_num \
  (this_target_ira->x_ira_pressure_classes_num)
#define ira_pressure_classes \
  (this_target_ira->x_ira_pressure_classes)
#define ira_pressure_class_translate \
  (this_target_ira->x_ira_pressure_class_translate)
#define ira_stack_reg_pressure_class \
  (this_target_ira->x_ira_stack_reg_pressure_class)
#define ira_reg_class_max_nregs \
  (this_target_ira->x_ira_reg_class_max_nregs)
#define ira_reg_class_min_nregs \
  (this_target_ira->x_ira_reg_class_min_nregs)
#define ira_memory_move_cost \
  (this_target_ira->x_ira_memory_move_cost)
#define ira_class_hard_regs \
  (this_target_ira->x_ira_class_hard_regs)
#define ira_class_hard_regs_num \
  (this_target_ira->x_ira_class_hard_regs_num)
#define ira_no_alloc_regs \
  (this_target_ira->x_ira_no_alloc_regs)

extern void ira_init_once (void);
extern void ira_init (void);
extern void ira_finish_once (void);
extern void ira_setup_eliminable_regset (void);
extern rtx ira_eliminate_regs (rtx, enum machine_mode);
extern void ira_set_pseudo_classes (FILE *);
extern void ira_implicitly_set_insn_hard_regs (HARD_REG_SET *);

extern void ira_sort_regnos_for_alter_reg (int *, int, unsigned int *);
extern void ira_mark_allocation_change (int);
extern void ira_mark_memory_move_deletion (int, int);
extern bool ira_reassign_pseudos (int *, int, HARD_REG_SET, HARD_REG_SET *,
				  HARD_REG_SET *, bitmap);
extern rtx ira_reuse_stack_slot (int, unsigned int, unsigned int);
extern void ira_mark_new_stack_slot (rtx, int, unsigned int);
extern bool ira_better_spill_reload_regno_p (int *, int *, rtx, rtx, rtx);
extern bool ira_bad_reload_regno (int, rtx, rtx);

extern void ira_adjust_equiv_reg_cost (unsigned, int);


text:
package com.comcast.cdn.traffic_control.traffic_router.core.loc;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;

import static org.junit.Assert.assertNotNull;

import com.comcast.cdn.traffic_control.traffic_router.core.TestBase;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.Geolocation;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.GeolocationDatabaseUpdater;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.MaxmindGeolocationService;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.NetworkUpdater;

public class GeoTest {
	private static final Logger LOGGER = Logger.getLogger(GeoTest.class);

	private GeolocationDatabaseUpdater geolocationDatabaseUpdater;
	private MaxmindGeolocationService geolocationService;
	private NetworkUpdater networkUpdater;
	private static ApplicationContext context;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		try {
			context = TestBase.getContext();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	@Before
	public void setUp() throws Exception {
		geolocationDatabaseUpdater = (GeolocationDatabaseUpdater) context.getBean("geolocationDatabaseUpdater");
		networkUpdater = (NetworkUpdater) context.getBean("networkUpdater");
		geolocationService = (MaxmindGeolocationService) context.getBean("GeolocationService");

		while (!networkUpdater.isLoaded()) {
			LOGGER.info("Waiting for a valid location database before proceeding");
			Thread.sleep(1000);
		}

		while (!geolocationDatabaseUpdater.isLoaded()) {
			LOGGER.info("Waiting for a valid Maxmind database before proceeding");
			Thread.sleep(1000);
		}
	}

	@Test
	public void testIps() {
		try {
			final String testips[][] = {
					{"40.40.40.40","cache-group-1"}
			};
			for(int i = 0; i < testips.length; i++) {
				Geolocation location = geolocationService.location(testips[i][0]);
				assertNotNull(location);
				String loc = location.toString();
				LOGGER.info(String.format("result for ip=%s: %s\n",testips[i], loc));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


text:
html, body {
    background: #fff;
    font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
    color: #000;
    height: 100%;
    margin: 0;
}

#body-wrapper {
    width: 100%;
    height: 100%;
    position: relative;
}

.navbar {
    /*background: #353434;*/
    background: white;
    height: 53px;
}

.navbar-header img{
    margin: 7px 30px 0px 10px;
    height: 40px;
}

.content-wrapper {
    position: absolute;
    bottom: 0;
    top: 53px;
    width: 100%;
    overflow: auto;
}

.content-header {
    background-color: #383b3e;
    height: 50px;
   /*position: relative; */
}
.content-header .title {
    color: white;
    width: 70px;
    font-size: 17px;
    margin-left: 20px;
    margin-right: 20px;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    float: left;
}
.content-header .control-button {
    position: relative;
  top: 50%;
  transform: translateY(-50%);
    float: left;
}

.content-header .control-button .navigation-btn {
    background-color: Transparent;
    color: #e5e5e5;
    border: 1px solid #e5e5e5;
    border-radius: 5px;
    font-size: 70%;
}
.content-content-wrapper {
    background: #fff;
    position: absolute;
    bottom: 0;
    top: 50px;
    width:100%;
    /*overflow:auto;*/
}
#content-main {
    position:absolute;
    right:200px;
    left:0px;
    /*bottom: 0px;*/
    /*top: 0px;*/
    height: 100%;
    padding: 7px 20px 20px 20px;
    color: #777;
    background: #e5e5e5;
    overflow-y:scroll;

    /*position:absolute;
    right:200px;
    left:0px;
    bottom: 0px;
    padding:20px;
    color: #777;
    background: #e5e5e5;
    overflow-y:scroll;*/
}
#content-main .queue{
    /*border-radius: 5px;*/
    /*background: #fff;*/
    padding: 7px;
    height: 200px;
}
#content-main .queue .queue-content {
    border-radius: 5px;
    background: #fff;
    width: 100%;
    height: 100%;
}
#content-main .queue .queue-title {
    color: #ec6841;
    font-size: 90%;
    margin: 0px;
    padding: 12px 8px 9px 8px;
}
#content-sidebar {
    background-color: #fff;
    position:fixed;
    overflow-y:scroll;
    right:0px;
    width:200px;
    height:100%;
    padding: 15px;
    color: #777;
}

#content-sidebar #content-sidebar-title {
    color: #b1b7be;
    font-size: 70%;
    margin-top: 5px;
    margin-bottom: 7px;
}

#content-sidebar .sidebar-connectedSortable {
    /*border: 1px solid #eee;*/
    /*width: 93%;*/
    /*min-height: 20px;*/
    list-style-type: none;
    padding: 0px 0 0 0;
    float: left;
    margin-bottom: 20px;
    /*margin-right: 50px;*/
    /*background-color: #535353;*/
  }
#content-sidebar .sidebar-connectedSortable li {
    font-size: 75%;
    height:40px;
    width: 170px;
    /*background-color: red;*/
     /*height: auto;*/
  }

#content-sidebar .sidebar-connectedSortable li:hover {
    /*background-color: #f0f0f0;*/
    background-color: #9068be;
    color: white !important;
}

#content-sidebar .sidebar-connectedSortable li .my-progress-bar {
    width: 33px;
    height: 40px;
    /*background: red;*/
    float: left;
    padding: 2px;
}
#content-sidebar .sidebar-connectedSortable li .my-progress-bar p {
    color:#333333 !important;
    font-size: 90%;
}
#content-sidebar .sidebar-connectedSortable li .my-progress-bar > svg {
    height: 100%;
    /*display: block;*/
}
#content-sidebar .sidebar-connectedSortable li .queue-title {
    /*margin-left: 24px;
    margin-right: 50px;*/

    height: 40px;
    width: 100%;
}
#content-sidebar .sidebar-connectedSortable li .queue-title p {
    padding-left: 34px;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

.table-queue{
    width: 100%;
    /*height: 150px;
    overflow-y: scroll;
    background-color: red;*/
}
.table-queue tr td{
    text-align: center;
    height: 25px;
    border-bottom: 1px solid #ddd;
}

/* ==========================================================================
Hide ng-cloak on page load, https://docs.angularjs.org/api/ng/directive/ngCloak
========================================================================== */
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
    display: none !important;
}

/* ==========================================================================
Developement Ribbon
========================================================================== */
.ribbon {
    background-color: #a00;
    box-shadow: 0 0 10px #888;
    left: -3.5em;
    moz-box-shadow: 0 0 10px #888;
    moz-transform: rotate(-45deg);
    ms-transform: rotate(-45deg);
    o-transform: rotate(-45deg);
    overflow: hidden;
    position: absolute;
    top: 40px;
    transform: rotate(-45deg);
    webkit-box-shadow: 0 0 10px #888;
    webkit-transform: rotate(-45deg);
    white-space: nowrap;
    width: 15em;
    z-index: 9999;
    pointer-events: none;
}

.ribbon a {
    border: 1px solid #faa;
    color: #fff;
    display: block;
    font: bold 81.25% 'Helvetica Neue', Helvetica, Arial, sans-serif;
    margin: 1px 0;
    padding: 10px 50px;
    text-align: center;
    text-decoration: none;
    text-shadow: 0 0 5px #444;
    pointer-events: none;
}

/* ==========================================================================
Version number in navbar
========================================================================== */
.navbar-version {
    font-size: 10px;
    color: #ccc
}

/* ==========================================================================
Browser Upgrade Prompt
========================================================================== */
.browserupgrade {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
Main page styles
========================================================================== */
.hero-unit {
    margin: 50px auto 0 auto;
    width: 300px;
    font-size: 18px;
    font-weight: 200;
    line-height: 30px;
    background-color: #eee;
    border-radius: 6px;
    padding: 60px;
}

.hero-unit h1 {
    font-size: 60px;
    line-height: 1;
    letter-spacing: -1px;
}

.hipster {
    display: inline-block;
    width: 347px;
    height: 497px;
    background: url("../images/hipster.png") no-repeat center top;
    background-size: contain;
}

/* wait autoprefixer update to allow simple generation of high pixel density media query */
@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (   min--moz-device-pixel-ratio: 2),
only screen and (     -o-min-device-pixel-ratio: 2/1),
only screen and (        min-device-pixel-ratio: 2),
only screen and (                min-resolution: 192dpi),
only screen and (                min-resolution: 2dppx) {
    .hipster {
        background: url("../images/hipster2x.png") no-repeat center top;
        background-size: contain;
    }
}

/* ==========================================================================
Generic styles
========================================================================== */
.error {
    color: white;
    background-color: red;
}

.pad {
    padding: 10px;
}

.break {
    white-space: normal;
    word-break:break-all;
}

.voffset  { margin-top: 2px; }
.voffset1 { margin-top: 5px; }
.voffset2 { margin-top: 10px; }
.voffset3 { margin-top: 15px; }
.voffset4 { margin-top: 30px; }
.voffset5 { margin-top: 40px; }
.voffset6 { margin-top: 60px; }
.voffset7 { margin-top: 80px; }
.voffset8 { margin-top: 100px; }
.voffset9 { margin-top: 150px; }

.readonly {
    background-color: #eee;
    opacity: 1;
}

/* ==========================================================================
make sure browsers use the pointer cursor for anchors, even with no href
========================================================================== */
a:hover {
  cursor: pointer;
}

.hand {
    cursor: pointer;
}

/* ==========================================================================
Metrics and Health styles
========================================================================== */
#threadDump .popover, #healthCheck .popover {
    top: inherit;
    display: block;
    font-size: 10px;
    max-width: 1024px;
}

#healthCheck .popover {
    margin-left: -50px;
}

.health-details {
    min-width: 400px;
}

/* ==========================================================================
start Password strength bar style
========================================================================== */
ul#strengthBar {
    display:inline;
    list-style:none;
    margin:0;
    margin-left:15px;
    padding:0;
    vertical-align:2px;
}

.point:last {
    margin:0 !important;
}
.point {
    background:#DDD;
    border-radius:2px;
    display:inline-block;
    height:5px;
    margin-right:1px;
    width:20px;
}

/* ==========================================================================
Custom alerts for notification
========================================================================== */
.alerts .alert{
    text-overflow: ellipsis;
}
.alert pre{
    background: none;
    border: none;
    font: inherit;
    color: inherit;
    padding: 0;
    margin: 0;
}

.alert .popover pre {
    font-size: 10px;
}

.alerts .toast {
    position: fixed;
    width: 100%;
}

.alerts .toast.left {
    left: 5px;
}

.alerts .toast.right {
    right: 5px;
}

.alerts .toast.top {
    top: 55px;
}

.alerts .toast.bottom {
    bottom: 55px;
}

@media screen and (min-width: 480px) {
    .alerts .toast {
        width: 50%;
    }
}

/* ==========================================================================
entity tables helpers
========================================================================== */
/* Remove Bootstrap padding from the element
   http://stackoverflow.com/questions/19562903/remove-padding-from-columns-in-bootstrap-3 */
.no-padding-left { padding-left: 0 !important; }
.no-padding-right { padding-right: 0 !important; }
.no-padding-top { padding-top: 0 !important; }
.no-padding-bottom { padding-bottom: 0 !important; }
.no-padding { padding: 0 !important; }

/* bootstrap 3 input-group 100% width
   http://stackoverflow.com/questions/23436430/bootstrap-3-input-group-100-width */
.width-min { width: 1% !important; }

/* Makes toolbar not wrap on smaller screens
 http://www.sketchingwithcss.com/samplechapter/cheatsheet.html#right */
.flex-btn-group-container {
   display: -webkit-flex;
   display: flex;
   -webkit-flex-direction: row;
   flex-direction: row;
   -webkit-justify-content: flex-end;
   justify-content: flex-end;
}

.jh-table > tbody > tr > td {
    /* Align text in td verifically (top aligned by Bootstrap) */
    vertical-align: middle;
}

.jh-table > thead > tr > th > .glyphicon-sort, .jh-table > thead > tr > th > .glyphicon-sort-by-attributes, .jh-table > thead > tr > th > .glyphicon-sort-by-attributes-alt {
    /* less visible sorting icons */
    opacity: 0.5;
}

.jh-table > thead > tr > th > .glyphicon-sort:hover, .jh-table > thead > tr > th > .glyphicon-sort-by-attributes:hover, .jh-table > thead > tr > th > .glyphicon-sort-by-attributes-alt:hover {
    /* full visible sorting icons and pointer when mouse is over them */
    opacity: 1;
    cursor: pointer;
}

/* ==========================================================================
entity detail page css
========================================================================== */
.dl-horizontal.jh-entity-details > dd {
    margin-bottom: 15px;
}

@media screen and (min-width: 768px) {
    .dl-horizontal.jh-entity-details > dt {
        margin-bottom: 15px;
    }

    .dl-horizontal.jh-entity-details > dd {
        border-bottom: 1px solid #eee;
        padding-left: 180px;
        margin-left: 0;
    }
}

/* ==========================================================================
ui bootstrap tweaks
========================================================================== */
.nav, .pagination, .carousel, .panel-title a {
    cursor: pointer;
}

.datetime-picker-dropdown > li.date-picker-menu div > table .btn-default,
.uib-datepicker-popup  > li > div.uib-datepicker > table .btn-default {
    border: 0;
}

.datetime-picker-dropdown > li.date-picker-menu div > table:focus,
.uib-datepicker-popup  > li > div.uib-datepicker > table:focus {
    outline: none;
}

/* jhipster-needle-css-add-main JHipster will add new css style */


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <meta charset="utf-8">

  <title>Invoice - Metro King</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="keywords" content="">
  <meta name="author" content="">

  <link href="style/bootstrap.css" rel="stylesheet">

  <link rel="stylesheet" href="style/font-awesome.css">

  <link rel="stylesheet" href="style/jquery-ui.css">

  <link rel="stylesheet" href="style/fullcalendar.css">

  <link rel="stylesheet" href="style/prettyPhoto.css">

  <link rel="stylesheet" href="style/rateit.css">

  <link rel="stylesheet" href="style/bootstrap-datetimepicker.min.css">

  <link rel="stylesheet" href="style/jquery.gritter.css">

  <link rel="stylesheet" href="style/jquery.cleditor.css">

  <link rel="stylesheet" href="style/bootstrap-switch.css">

  <link href="style/style.css" rel="stylesheet">

  <link href="style/widgets.css" rel="stylesheet">

  <link rel="shortcut icon" href="img/favicon/favicon.png">

		  <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
			Toggle navigation

		  </button>
		  Metro King

               Admin

 Profile

 Settings

 Logout

                 Chats 6

 Chats

                    Hi :) 10:42

                    How are you? 20:42

                    What are you doing? 14:42

                      View All

                 Inbox 6

 Messages

                    Hello how are you?

Quisque eu consectetur erat eget  semper...

                    Today is wonderful?

Quisque eu consectetur erat eget  semper...

                      View All

                 Users 6

 Users

                    Ravi Kumar Free

                    Balaji Premium

                    Kumarasamy Free

                      View All

Navigation

             <form >
              	<input type="text" class="form-control" placeholder="Search">
            </form>

 Dashboard

                 Widgets

Widgets #1

Widgets #2

 Charts

 UI Elements

                 Pages #1

Calendar

Make Post

Login

Register

Statement

Error Log

Support

                 Pages #2

Error

Gallery

Grid

Invoice

Media

Profile

 Forms

 Tables

Invoice

          Something Goes Here

           Home

          /
          Invoice

Invoice

Metro King

                          19/133, New New York Street

                          Near Bus Stop, Right side

                          Mexico, NY - 63442

                          USA

MacMedia

                          24/133, Mexico Street

                          Near Airport, Right side

                          Mexico, CA - 53432

                          Mexico

Invoice

                          Invoice No : 52322

                          Date : 12/34/2012

                          Account No : 4290293203

                              #
                              Name
                              Quantity
                              Unit Price
                              Tax
                              Total

                              1
                              Sony Xperia Pro X1242
                              5
                              $534
                              12.5%
                              $2424

                              2
                              Samsung Galaxy Pro
                              2
                              $244
                              12.5%
                              $5342

                              3
                              Apple iPhone 5G - Black
                              7
                              $434
                              12.5%
                              $34524

                              4
                              Nokia Lumina Tipo - Windows Mobile
                              4
                              $754
                              12.5%
                              $8866

                              5
                              Motorola Defy 29323
                              5
                              $644
                              12.5%
                              $88865

                              6
                              Micromax Funbook - Android Tablet
                              9
                              $434
                              12.5%
                              $53535

                              Total
                              $2405

                    <button class="btn btn-danger pull-right">Send Invoice</button>

Notification Box

Today Earnings

$5,0000

Yesterday Earnings

$4,6000

Have some content here.

Aliquam dui libero, pharetra nec venenatis in, scelerisque quis odio. In hac habitasse platea dictumst. Etiam porta placerat turpis, eget fermentum neque egestas at. Vestibulum ullamcorper, augue a sollicitudin vestibulum, orci purus semper felis, lobortis consequat nisi nunc eu enim.

Have some content here.

Aliquam dui libero, pharetra nec venenatis in, scelerisque quis odio. In hac habitasse platea dictumst. Etiam porta placerat turpis, eget fermentum neque egestas at. Vestibulum ullamcorper, augue a sollicitudin vestibulum, orci purus semper felis, lobortis consequat nisi nunc eu enim.


text:
package com.arckenver.nations.cmdexecutor.nation;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextColors;

import com.arckenver.nations.DataHandler;
import com.arckenver.nations.LanguageHandler;
import com.arckenver.nations.cmdelement.NationNameElement;
import com.arckenver.nations.object.Nation;
import com.arckenver.nations.object.Request;

public class NationJoinExecutor implements CommandExecutor
{
	public static void create(CommandSpec.Builder cmd) {
		cmd.child(CommandSpec.builder()
				.description(Text.of(""))
				.permission("nations.command.nation.join")
				.arguments(GenericArguments.optional(new NationNameElement(Text.of("nation"))))
				.executor(new NationJoinExecutor())
				.build(), "join", "apply");
	}

	public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
	{
		if (src instanceof Player)
		{
			Player guestPlayer = (Player) src;
			if (!ctx.<String>getOne("nation").isPresent())
			{
				src.sendMessage(Text.of(TextColors.YELLOW, "/n join <nation>"));
				return CommandResult.success();
			}
			if (DataHandler.getNationOfPlayer(guestPlayer.getUniqueId()) != null)
			{
				src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NEEDLEAVE));
				return CommandResult.success();
			}
			String nationName = ctx.<String>getOne("nation").get();
			Nation nation = DataHandler.getNation(nationName);
			if (nation == null)
			{
				src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_BADNATIONNAME));
				return CommandResult.success();
			}

			Request req = DataHandler.getJoinRequest(nation.getUUID(), guestPlayer.getUniqueId());
			if (req != null)
			{
				src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_ALREADYASKED));
				return CommandResult.success();
			}
			req = DataHandler.getInviteRequest(nation.getUUID(), guestPlayer.getUniqueId());
			if (nation.getFlag("open") || req != null)
			{
				if (req != null)
				{
					DataHandler.removeInviteRequest(req);
				}
				for (UUID uuid : nation.getCitizens())
				{
					Optional<Player> optPlayer = Sponge.getServer().getPlayer(uuid);
					if (optPlayer.isPresent())
						optPlayer.get().sendMessage(Text.of(TextColors.GREEN, LanguageHandler.INFO_JOINNATIONANNOUNCE.replaceAll("\\{PLAYER\\}", guestPlayer.getName())));
				}
				nation.addCitizen(guestPlayer.getUniqueId());
				guestPlayer.sendMessage(Text.of(TextColors.GREEN, LanguageHandler.INFO_JOINNATION.replaceAll("\\{NATION\\}", nation.getName())));
				DataHandler.saveNation(nation.getUUID());
				return CommandResult.success();
			}
			ArrayList<UUID> nationStaff = nation.getStaff();
			List<Player> nationStaffPlayers = nationStaff
					.stream()
					.filter(uuid -> Sponge.getServer().getPlayer(uuid).isPresent())
					.map(uuid -> Sponge.getServer().getPlayer(uuid).get())
					.collect(Collectors.toList());

			if (nationStaffPlayers.isEmpty())
			{
				src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOSTAFFONLINE));
				return CommandResult.success();
			}
			DataHandler.addJoinRequest(new Request(nation.getUUID(), guestPlayer.getUniqueId()));
			for (Player p : nationStaffPlayers)
			{
				String str = LanguageHandler.INFO_CLICK_JOINREQUEST.replaceAll("\\{PLAYER\\}", guestPlayer.getName());
				p.sendMessage(Text.builder()
						.append(Text.of(TextColors.AQUA, str.split("\\{CLICKHERE\\}")[0]))
						.append(Text.builder(LanguageHandler.CLICKME)
								.onClick(TextActions.runCommand("/nation invite " + guestPlayer.getName()))
								.color(TextColors.DARK_AQUA)
								.build())
						.append(Text.of(TextColors.AQUA, str.split("\\{CLICKHERE\\}")[1])).build());
			}
			src.sendMessage(Text.of(TextColors.GREEN, LanguageHandler.INFO_INVITSEND.replaceAll("\\{RECEIVER\\}", nationName)));
		}
		else
		{
			src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_NOPLAYER));
		}
		return CommandResult.success();
	}
}


text:
package gomatrixserverlib

import (
	"bytes"
	"context"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"

	"github.com/matrix-org/gomatrix"
	"github.com/matrix-org/util"
	"github.com/sirupsen/logrus"
)

// Default HTTPS request timeout
const requestTimeout time.Duration = time.Duration(30) * time.Second

// A Client makes request to the federation listeners of matrix
// homeservers
type Client struct {
	client http.Client
}

// UserInfo represents information about a user.
type UserInfo struct {
	Sub string `json:"sub"`
}

// NewClient makes a new Client (with default timeout)
func NewClient() *Client {
	return NewClientWithTimeout(requestTimeout)
}

// NewClientWithTimeout makes a new Client with a specified request timeout
func NewClientWithTimeout(timeout time.Duration) *Client {
	return &Client{client: http.Client{
		Transport: newFederationTripper(),
		Timeout:   timeout}}
}

type federationTripper struct {
	transport http.RoundTripper
}

func newFederationTripper() *federationTripper {
	// TODO: Verify ceritificates
	return &federationTripper{
		transport: &http.Transport{
			// Set our own DialTLS function to avoid the default net/http SNI.
			// By default net/http and crypto/tls set the SNI to the target host.
			// By avoiding the default implementation we can keep the ServerName
			// as the empty string so that crypto/tls doesn't add SNI.
			DialTLS: func(network, addr string) (net.Conn, error) {
				rawconn, err := net.Dial(network, addr)
				if err != nil {
					return nil, err
				}
				// Wrap a raw connection ourselves since tls.Dial defaults the SNI
				conn := tls.Client(rawconn, &tls.Config{
					ServerName: "",
					// TODO: We should be checking that the TLS certificate we see here matches
					//       one of the allowed SHA-256 fingerprints for the server.
					InsecureSkipVerify: true, // nolint: gas
				})
				if err := conn.Handshake(); err != nil {
					return nil, err
				}
				return conn, nil
			},
		},
	}
}

func makeHTTPSURL(u *url.URL, addr string) (httpsURL url.URL) {
	httpsURL = *u
	httpsURL.Scheme = "https"
	httpsURL.Host = addr
	return
}

func (f *federationTripper) RoundTrip(r *http.Request) (*http.Response, error) {
	serverName := ServerName(r.URL.Host)
	dnsResult, err := LookupServer(serverName)
	if err != nil {
		return nil, err
	}

	if len(dnsResult.Addrs) == 0 {
		return nil, fmt.Errorf("no address found for matrix host %v", serverName)
	}

	var resp *http.Response
	// TODO: respect the priority and weight fields from the SRV record
	for _, addr := range dnsResult.Addrs {
		u := makeHTTPSURL(r.URL, addr)
		r.URL = &u
		resp, err = f.transport.RoundTrip(r)
		if err == nil {
			return resp, nil
		}
		util.GetLogger(r.Context()).Warnf("Error sending request to %s: %v",
			u.String(), err)
	}

	// just return the most recent error
	return nil, err
}

// LookupUserInfo gets information about a user from a given matrix homeserver
// using a bearer access token.
func (fc *Client) LookupUserInfo(
	ctx context.Context, matrixServer ServerName, token string,
) (u UserInfo, err error) {
	url := url.URL{
		Scheme:   "matrix",
		Host:     string(matrixServer),
		Path:     "/_matrix/federation/v1/openid/userinfo",
		RawQuery: url.Values{"access_token": []string{token}}.Encode(),
	}

	req, err := http.NewRequest("GET", url.String(), nil)
	if err != nil {
		return
	}

	var response *http.Response
	response, err = fc.DoHTTPRequest(ctx, req)
	if response != nil {
		defer response.Body.Close() // nolint: errcheck
	}
	if err != nil {
		return
	}
	if response.StatusCode < 200 || response.StatusCode >= 300 {
		var errorOutput []byte
		errorOutput, err = ioutil.ReadAll(response.Body)
		if err != nil {
			return
		}
		err = fmt.Errorf("HTTP %d : %s", response.StatusCode, errorOutput)
		return
	}

	err = json.NewDecoder(response.Body).Decode(&u)
	if err != nil {
		return
	}

	userParts := strings.SplitN(u.Sub, ":", 2)
	if len(userParts) != 2 || userParts[1] != string(matrixServer) {
		err = fmt.Errorf("userID doesn't match server name '%v' != '%v'", u.Sub, matrixServer)
		return
	}

	return
}

// GetServerKeys asks a matrix server for its signing keys and TLS cert
func (fc *Client) GetServerKeys(
	ctx context.Context, matrixServer ServerName,
) (ServerKeys, error) {
	url := url.URL{
		Scheme: "matrix",
		Host:   string(matrixServer),
		Path:   "/_matrix/key/v2/server",
	}

	var body ServerKeys
	req, err := http.NewRequest("GET", url.String(), nil)
	if err != nil {
		return body, err
	}

	err = fc.DoRequestAndParseResponse(
		ctx, req, &body,
	)
	return body, err
}

// LookupServerKeys looks up the keys for a matrix server from a matrix server.
// The first argument is the name of the matrix server to download the keys from.
// The second argument is a map from (server name, key ID) pairs to timestamps.
// The (server name, key ID) pair identifies the key to download.
// The timestamps tell the server when the keys need to be valid until.
// Perspective servers can use that timestamp to determine whether they can
// return a cached copy of the keys or whether they will need to retrieve a fresh
// copy of the keys.
// Returns the keys returned by the server, or an error if there was a problem talking to the server.
func (fc *Client) LookupServerKeys(
	ctx context.Context, matrixServer ServerName, keyRequests map[PublicKeyLookupRequest]Timestamp,
) ([]ServerKeys, error) {
	url := url.URL{
		Scheme: "matrix",
		Host:   string(matrixServer),
		Path:   "/_matrix/key/v2/query",
	}

	// The request format is:
	// { "server_keys": { "<server_name>": { "<key_id>": { "minimum_valid_until_ts": <ts> }}}
	type keyreq struct {
		MinimumValidUntilTS Timestamp `json:"minimum_valid_until_ts"`
	}
	request := struct {
		ServerKeyMap map[ServerName]map[KeyID]keyreq `json:"server_keys"`
	}{map[ServerName]map[KeyID]keyreq{}}
	for k, ts := range keyRequests {
		server := request.ServerKeyMap[k.ServerName]
		if server == nil {
			server = map[KeyID]keyreq{}
			request.ServerKeyMap[k.ServerName] = server
		}
		server[k.KeyID] = keyreq{ts}
	}

	requestBytes, err := json.Marshal(request)
	if err != nil {
		return nil, err
	}

	var body struct {
		ServerKeyList []ServerKeys `json:"server_keys"`
	}

	req, err := http.NewRequest("POST", url.String(), bytes.NewBuffer(requestBytes))
	if err != nil {
		return nil, err
	}
	req.Header.Add("Content-Type", "application/json")

	err = fc.DoRequestAndParseResponse(
		ctx, req, &body,
	)
	if err != nil {
		return nil, err
	}

	return body.ServerKeyList, nil
}

// CreateMediaDownloadRequest creates a request for media on a homeserver and returns the http.Response or an error
func (fc *Client) CreateMediaDownloadRequest(
	ctx context.Context, matrixServer ServerName, mediaID string,
) (*http.Response, error) {
	requestURL := "matrix://" + string(matrixServer) + "/_matrix/media/v1/download/" + string(matrixServer) + "/" + mediaID
	req, err := http.NewRequest("GET", requestURL, nil)
	if err != nil {
		return nil, err
	}

	return fc.DoHTTPRequest(ctx, req)
}

// DoRequestAndParseResponse calls DoHTTPRequest and then decodes the response.
//
// If the HTTP response is not a 200, an attempt is made to parse the response
// body into a gomatrix.RespError. In any case, a non-200 response will result
// in a gomatrix.HTTPError.
//
func (fc *Client) DoRequestAndParseResponse(
	ctx context.Context,
	req *http.Request,
	result interface{},
) error {
	response, err := fc.DoHTTPRequest(ctx, req)
	if response != nil {
		defer response.Body.Close() // nolint: errcheck
	}
	if err != nil {
		return err
	}

	if response.StatusCode/100 != 2 { // not 2xx
		// Adapted from https://github.com/matrix-org/gomatrix/blob/master/client.go
		var contents []byte
		contents, err = ioutil.ReadAll(response.Body)
		if err != nil {
			return err
		}

		var wrap error
		var respErr gomatrix.RespError
		if _ = json.Unmarshal(contents, &respErr); respErr.ErrCode != "" {
			wrap = respErr
		}

		// If we failed to decode as RespError, don't just drop the HTTP body, include it in the
		// HTTP error instead (e.g proxy errors which return HTML).
		msg := "Failed to " + req.Method + " JSON to " + req.RequestURI
		if wrap == nil {
			msg = msg + ": " + string(contents)
		}

		return gomatrix.HTTPError{
			Code:         response.StatusCode,
			Message:      msg,
			WrappedError: wrap,
		}
	}

	if err = json.NewDecoder(response.Body).Decode(result); err != nil {
		return err
	}

	return nil
}

// DoHTTPRequest creates an outgoing request ID and adds it to the context
// before sending off the request and awaiting a response.
//
// If the returned error is nil, the Response will contain a non-nil
// Body which the caller is expected to close.
//
func (fc *Client) DoHTTPRequest(ctx context.Context, req *http.Request) (*http.Response, error) {
	reqID := util.RandomString(12)
	logger := util.GetLogger(ctx).WithFields(logrus.Fields{
		"out.req.ID":     reqID,
		"out.req.method": req.Method,
		"out.req.uri":    req.URL,
	})
	logger.Info("Outgoing request")
	newCtx := util.ContextWithLogger(ctx, logger)

	start := time.Now()
	resp, err := fc.client.Do(req.WithContext(newCtx))
	if err != nil {
		logger.WithField("error", err).Warn("Outgoing request failed")
		return nil, err
	}

	// we haven't yet read the body, so this is slightly premature, but it's the easiest place.
	logger.WithFields(logrus.Fields{
		"out.req.code":        resp.StatusCode,
		"out.req.duration_ms": int(time.Since(start) / time.Millisecond),
	}).Info("Outgoing request returned")

	return resp, nil
}