text:
import * as protos from '../protos/protos';
import * as assert from 'assert';
import * as sinon from 'sinon';
import {SinonStub} from 'sinon';
import {describe, it} from 'mocha';
import * as identityawareproxyadminv1beta1Module from '../src';

import {protobuf} from 'google-gax';

// Dynamically loaded proto JSON is needed to get the type information
// to fill in default values for request objects
const root = protobuf.Root.fromJSON(
  require('../protos/protos.json')
).resolveAll();

// eslint-disable-next-line @typescript-eslint/no-unused-vars
function getTypeDefaultValue(typeName: string, fields: string[]) {
  let type = root.lookupType(typeName) as protobuf.Type;
  for (const field of fields.slice(0, -1)) {
    type = type.fields[field]?.resolvedType as protobuf.Type;
  }
  return type.fields[fields[fields.length - 1]]?.defaultValue;
}

function generateSampleMessage<T extends object>(instance: T) {
  const filledObject = (
    instance.constructor as typeof protobuf.Message
  ).toObject(instance as protobuf.Message<T>, {defaults: true});
  return (instance.constructor as typeof protobuf.Message).fromObject(
    filledObject
  ) as T;
}

function stubSimpleCall<ResponseType>(response?: ResponseType, error?: Error) {
  return error
    ? sinon.stub().rejects(error)
    : sinon.stub().resolves([response]);
}

function stubSimpleCallWithCallback<ResponseType>(
  response?: ResponseType,
  error?: Error
) {
  return error
    ? sinon.stub().callsArgWith(2, error)
    : sinon.stub().callsArgWith(2, null, response);
}

describe('v1beta1.IdentityAwareProxyAdminV1Beta1Client', () => {
  describe('Common methods', () => {
    it('has servicePath', () => {
      const servicePath =
        identityawareproxyadminv1beta1Module.v1beta1
          .IdentityAwareProxyAdminV1Beta1Client.servicePath;
      assert(servicePath);
    });

    it('has apiEndpoint', () => {
      const apiEndpoint =
        identityawareproxyadminv1beta1Module.v1beta1
          .IdentityAwareProxyAdminV1Beta1Client.apiEndpoint;
      assert(apiEndpoint);
    });

    it('has port', () => {
      const port =
        identityawareproxyadminv1beta1Module.v1beta1
          .IdentityAwareProxyAdminV1Beta1Client.port;
      assert(port);
      assert(typeof port === 'number');
    });

    it('should create a client with no option', () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client();
      assert(client);
    });

    it('should create a client with gRPC fallback', () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            fallback: true,
          }
        );
      assert(client);
    });

    it('has initialize method and supports deferred initialization', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      assert.strictEqual(client.identityAwareProxyAdminV1Beta1Stub, undefined);
      await client.initialize();
      assert(client.identityAwareProxyAdminV1Beta1Stub);
    });

    it('has close method for the initialized client', done => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      assert(client.identityAwareProxyAdminV1Beta1Stub);
      client.close().then(() => {
        done();
      });
    });

    it('has close method for the non-initialized client', done => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      assert.strictEqual(client.identityAwareProxyAdminV1Beta1Stub, undefined);
      client.close().then(() => {
        done();
      });
    });

    it('has getProjectId method', async () => {
      const fakeProjectId = 'fake-project-id';
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.auth.getProjectId = sinon.stub().resolves(fakeProjectId);
      const result = await client.getProjectId();
      assert.strictEqual(result, fakeProjectId);
      assert((client.auth.getProjectId as SinonStub).calledWithExactly());
    });

    it('has getProjectId method with callback', async () => {
      const fakeProjectId = 'fake-project-id';
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.auth.getProjectId = sinon
        .stub()
        .callsArgWith(0, null, fakeProjectId);
      const promise = new Promise((resolve, reject) => {
        client.getProjectId((err?: Error | null, projectId?: string | null) => {
          if (err) {
            reject(err);
          } else {
            resolve(projectId);
          }
        });
      });
      const result = await promise;
      assert.strictEqual(result, fakeProjectId);
    });
  });

  describe('setIamPolicy', () => {
    it('invokes setIamPolicy without error', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      const request = generateSampleMessage(
        new protos.google.iam.v1.SetIamPolicyRequest()
      );
      const defaultValue1 = getTypeDefaultValue(
        '.google.iam.v1.SetIamPolicyRequest',
        ['resource']
      );
      request.resource = defaultValue1;
      const expectedHeaderRequestParams = `resource=${defaultValue1}`;
      const expectedResponse = generateSampleMessage(
        new protos.google.iam.v1.Policy()
      );
      client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse);
      const [response] = await client.setIamPolicy(request);
      assert.deepStrictEqual(response, expectedResponse);
      const actualRequest = (
        client.innerApiCalls.setIamPolicy as SinonStub
      ).getCall(0).args[0];
      assert.deepStrictEqual(actualRequest, request);
      const actualHeaderRequestParams = (
        client.innerApiCalls.setIamPolicy as SinonStub
      ).getCall(0).args[1].otherArgs.headers['x-goog-request-params'];
      assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams));
    });

    it('invokes setIamPolicy without error using callback', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      const request = generateSampleMessage(
        new protos.google.iam.v1.SetIamPolicyRequest()
      );
      const defaultValue1 = getTypeDefaultValue(
        '.google.iam.v1.SetIamPolicyRequest',
        ['resource']
      );
      request.resource = defaultValue1;
      const expectedHeaderRequestParams = `resource=${defaultValue1}`;
      const expectedResponse = generateSampleMessage(
        new protos.google.iam.v1.Policy()
      );
      client.innerApiCalls.setIamPolicy =
        stubSimpleCallWithCallback(expectedResponse);
      const promise = new Promise((resolve, reject) => {
        client.setIamPolicy(
          request,
          (
            err?: Error | null,
            result?: protos.google.iam.v1.IPolicy | null
          ) => {
            if (err) {
              reject(err);
            } else {
              resolve(result);
            }
          }
        );
      });
      const response = await promise;
      assert.deepStrictEqual(response, expectedResponse);
      const actualRequest = (
        client.innerApiCalls.setIamPolicy as SinonStub
      ).getCall(0).args[0];
      assert.deepStrictEqual(actualRequest, request);
      const actualHeaderRequestParams = (
        client.innerApiCalls.setIamPolicy as SinonStub
      ).getCall(0).args[1].otherArgs.headers['x-goog-request-params'];
      assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams));
    });

    it('invokes setIamPolicy with error', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      const request = generateSampleMessage(
        new protos.google.iam.v1.SetIamPolicyRequest()
      );
      const defaultValue1 = getTypeDefaultValue(
        '.google.iam.v1.SetIamPolicyRequest',
        ['resource']
      );
      request.resource = defaultValue1;
      const expectedHeaderRequestParams = `resource=${defaultValue1}`;
      const expectedError = new Error('expected');
      client.innerApiCalls.setIamPolicy = stubSimpleCall(
        undefined,
        expectedError
      );
      await assert.rejects(client.setIamPolicy(request), expectedError);
      const actualRequest = (
        client.innerApiCalls.setIamPolicy as SinonStub
      ).getCall(0).args[0];
      assert.deepStrictEqual(actualRequest, request);
      const actualHeaderRequestParams = (
        client.innerApiCalls.setIamPolicy as SinonStub
      ).getCall(0).args[1].otherArgs.headers['x-goog-request-params'];
      assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams));
    });

    it('invokes setIamPolicy with closed client', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      const request = generateSampleMessage(
        new protos.google.iam.v1.SetIamPolicyRequest()
      );
      const defaultValue1 = getTypeDefaultValue(
        '.google.iam.v1.SetIamPolicyRequest',
        ['resource']
      );
      request.resource = defaultValue1;
      const expectedError = new Error('The client has already been closed.');
      client.close();
      await assert.rejects(client.setIamPolicy(request), expectedError);
    });
  });

  describe('getIamPolicy', () => {
    it('invokes getIamPolicy without error', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      const request = generateSampleMessage(
        new protos.google.iam.v1.GetIamPolicyRequest()
      );
      const defaultValue1 = getTypeDefaultValue(
        '.google.iam.v1.GetIamPolicyRequest',
        ['resource']
      );
      request.resource = defaultValue1;
      const expectedHeaderRequestParams = `resource=${defaultValue1}`;
      const expectedResponse = generateSampleMessage(
        new protos.google.iam.v1.Policy()
      );
      client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse);
      const [response] = await client.getIamPolicy(request);
      assert.deepStrictEqual(response, expectedResponse);
      const actualRequest = (
        client.innerApiCalls.getIamPolicy as SinonStub
      ).getCall(0).args[0];
      assert.deepStrictEqual(actualRequest, request);
      const actualHeaderRequestParams = (
        client.innerApiCalls.getIamPolicy as SinonStub
      ).getCall(0).args[1].otherArgs.headers['x-goog-request-params'];
      assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams));
    });

    it('invokes getIamPolicy without error using callback', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      const request = generateSampleMessage(
        new protos.google.iam.v1.GetIamPolicyRequest()
      );
      const defaultValue1 = getTypeDefaultValue(
        '.google.iam.v1.GetIamPolicyRequest',
        ['resource']
      );
      request.resource = defaultValue1;
      const expectedHeaderRequestParams = `resource=${defaultValue1}`;
      const expectedResponse = generateSampleMessage(
        new protos.google.iam.v1.Policy()
      );
      client.innerApiCalls.getIamPolicy =
        stubSimpleCallWithCallback(expectedResponse);
      const promise = new Promise((resolve, reject) => {
        client.getIamPolicy(
          request,
          (
            err?: Error | null,
            result?: protos.google.iam.v1.IPolicy | null
          ) => {
            if (err) {
              reject(err);
            } else {
              resolve(result);
            }
          }
        );
      });
      const response = await promise;
      assert.deepStrictEqual(response, expectedResponse);
      const actualRequest = (
        client.innerApiCalls.getIamPolicy as SinonStub
      ).getCall(0).args[0];
      assert.deepStrictEqual(actualRequest, request);
      const actualHeaderRequestParams = (
        client.innerApiCalls.getIamPolicy as SinonStub
      ).getCall(0).args[1].otherArgs.headers['x-goog-request-params'];
      assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams));
    });

    it('invokes getIamPolicy with error', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      const request = generateSampleMessage(
        new protos.google.iam.v1.GetIamPolicyRequest()
      );
      const defaultValue1 = getTypeDefaultValue(
        '.google.iam.v1.GetIamPolicyRequest',
        ['resource']
      );
      request.resource = defaultValue1;
      const expectedHeaderRequestParams = `resource=${defaultValue1}`;
      const expectedError = new Error('expected');
      client.innerApiCalls.getIamPolicy = stubSimpleCall(
        undefined,
        expectedError
      );
      await assert.rejects(client.getIamPolicy(request), expectedError);
      const actualRequest = (
        client.innerApiCalls.getIamPolicy as SinonStub
      ).getCall(0).args[0];
      assert.deepStrictEqual(actualRequest, request);
      const actualHeaderRequestParams = (
        client.innerApiCalls.getIamPolicy as SinonStub
      ).getCall(0).args[1].otherArgs.headers['x-goog-request-params'];
      assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams));
    });

    it('invokes getIamPolicy with closed client', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      const request = generateSampleMessage(
        new protos.google.iam.v1.GetIamPolicyRequest()
      );
      const defaultValue1 = getTypeDefaultValue(
        '.google.iam.v1.GetIamPolicyRequest',
        ['resource']
      );
      request.resource = defaultValue1;
      const expectedError = new Error('The client has already been closed.');
      client.close();
      await assert.rejects(client.getIamPolicy(request), expectedError);
    });
  });

  describe('testIamPermissions', () => {
    it('invokes testIamPermissions without error', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      const request = generateSampleMessage(
        new protos.google.iam.v1.TestIamPermissionsRequest()
      );
      const defaultValue1 = getTypeDefaultValue(
        '.google.iam.v1.TestIamPermissionsRequest',
        ['resource']
      );
      request.resource = defaultValue1;
      const expectedHeaderRequestParams = `resource=${defaultValue1}`;
      const expectedResponse = generateSampleMessage(
        new protos.google.iam.v1.TestIamPermissionsResponse()
      );
      client.innerApiCalls.testIamPermissions =
        stubSimpleCall(expectedResponse);
      const [response] = await client.testIamPermissions(request);
      assert.deepStrictEqual(response, expectedResponse);
      const actualRequest = (
        client.innerApiCalls.testIamPermissions as SinonStub
      ).getCall(0).args[0];
      assert.deepStrictEqual(actualRequest, request);
      const actualHeaderRequestParams = (
        client.innerApiCalls.testIamPermissions as SinonStub
      ).getCall(0).args[1].otherArgs.headers['x-goog-request-params'];
      assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams));
    });

    it('invokes testIamPermissions without error using callback', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      const request = generateSampleMessage(
        new protos.google.iam.v1.TestIamPermissionsRequest()
      );
      const defaultValue1 = getTypeDefaultValue(
        '.google.iam.v1.TestIamPermissionsRequest',
        ['resource']
      );
      request.resource = defaultValue1;
      const expectedHeaderRequestParams = `resource=${defaultValue1}`;
      const expectedResponse = generateSampleMessage(
        new protos.google.iam.v1.TestIamPermissionsResponse()
      );
      client.innerApiCalls.testIamPermissions =
        stubSimpleCallWithCallback(expectedResponse);
      const promise = new Promise((resolve, reject) => {
        client.testIamPermissions(
          request,
          (
            err?: Error | null,
            result?: protos.google.iam.v1.ITestIamPermissionsResponse | null
          ) => {
            if (err) {
              reject(err);
            } else {
              resolve(result);
            }
          }
        );
      });
      const response = await promise;
      assert.deepStrictEqual(response, expectedResponse);
      const actualRequest = (
        client.innerApiCalls.testIamPermissions as SinonStub
      ).getCall(0).args[0];
      assert.deepStrictEqual(actualRequest, request);
      const actualHeaderRequestParams = (
        client.innerApiCalls.testIamPermissions as SinonStub
      ).getCall(0).args[1].otherArgs.headers['x-goog-request-params'];
      assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams));
    });

    it('invokes testIamPermissions with error', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      const request = generateSampleMessage(
        new protos.google.iam.v1.TestIamPermissionsRequest()
      );
      const defaultValue1 = getTypeDefaultValue(
        '.google.iam.v1.TestIamPermissionsRequest',
        ['resource']
      );
      request.resource = defaultValue1;
      const expectedHeaderRequestParams = `resource=${defaultValue1}`;
      const expectedError = new Error('expected');
      client.innerApiCalls.testIamPermissions = stubSimpleCall(
        undefined,
        expectedError
      );
      await assert.rejects(client.testIamPermissions(request), expectedError);
      const actualRequest = (
        client.innerApiCalls.testIamPermissions as SinonStub
      ).getCall(0).args[0];
      assert.deepStrictEqual(actualRequest, request);
      const actualHeaderRequestParams = (
        client.innerApiCalls.testIamPermissions as SinonStub
      ).getCall(0).args[1].otherArgs.headers['x-goog-request-params'];
      assert(actualHeaderRequestParams.includes(expectedHeaderRequestParams));
    });

    it('invokes testIamPermissions with closed client', async () => {
      const client =
        new identityawareproxyadminv1beta1Module.v1beta1.IdentityAwareProxyAdminV1Beta1Client(
          {
            credentials: {client_email: 'bogus', private_key: 'bogus'},
            projectId: 'bogus',
          }
        );
      client.initialize();
      const request = generateSampleMessage(
        new protos.google.iam.v1.TestIamPermissionsRequest()
      );
      const defaultValue1 = getTypeDefaultValue(
        '.google.iam.v1.TestIamPermissionsRequest',
        ['resource']
      );
      request.resource = defaultValue1;
      const expectedError = new Error('The client has already been closed.');
      client.close();
      await assert.rejects(client.testIamPermissions(request), expectedError);
    });
  });
});


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('products', '0019_brandimage'),
    ]

    operations = [
        migrations.AddField(
            model_name='product',
            name='brands',
            field=models.ManyToManyField(to='products.Brand', blank=True),
        ),
        migrations.AddField(
            model_name='product',
            name='categories',
            field=models.ManyToManyField(to='products.Category', blank=True),
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.semantic.thumbnail.image;

import com.bric.image.pixel.GenericImageSinglePassIterator;
import com.semantic.thumbnail.Thumbnailer;
import com.semantic.util.image.ImageUtil;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.apache.sanselan.Sanselan;

/**
 * http://javagraphics.blogspot.com/2011/05/images-scaling-jpegs-and-pngs.html
 * @author Christian Plonka (cplonka81@gmail.com)
 */
public class StreamImageThumbnailer implements Thumbnailer {

    private Dimension maxSize = new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    private ImageIOThumbnailer fallback = new ImageIOThumbnailer();

    @Override
    public void generateThumbnail(File input, File output, String mimeType) throws RuntimeException {
        try {
            BufferedImage subBuffer = null;
            /* try to find and extract embedded thumbnail in jpg files */
            if (mimeType.equals("image/jpeg")) {
                byte[] thumbData = ImageUtil.extractEXIFThumbnailData(Sanselan.getMetadata(input));
                /* */
                if (thumbData != null) {
                    subBuffer = ImageUtil.toBufferedImage(Toolkit.getDefaultToolkit().createImage(
                            thumbData));
                }
            }
            /* do generic generation for thumbnail */
            if (subBuffer == null) {
                subBuffer = GenericImageSinglePassIterator.createScaledImage(
                        input.toURI().toURL(), maxSize);
            }
            /* save thumbnail, if we have an alpha channel then save as png */
            ImageIO.write(subBuffer, ImageUtil.hasAlpha(subBuffer) ? "png" : "jpg", output);
        } catch (Exception e) {
            /* try imageio fallback */
            fallback.generateThumbnail(input, output, mimeType);
        }
    }

    @Override
    public String[] getMimeTypes() {
        return ImageIO.getReaderMIMETypes();
    }
}


text: My custom functions for jupyter notebooks


text:
package base

import (
	"sync"
)

type SafeMap struct {
	locker *sync.RWMutex
	data   map[string]bool
}

func (s *SafeMap) Set(verstr string) {
	s.locker.Lock()
	defer s.locker.Unlock()
	s.data[verstr] = true
}

func (s *SafeMap) Get(verstr string) bool {
	s.locker.RLock()
	defer s.locker.RUnlock()
	return s.data[verstr]
}

func NewSafeMap() *SafeMap {
	return &SafeMap{
		locker: &sync.RWMutex{},
		data:   make(map[string]bool),
	}
}


text:
var request = require('request-promise');
var weather_host = $WEATHER_COMPANY_URL;

var today = new Date();
var currentDay = parseInt(today.getDay());
var weekday = new Array(7);
weekday[0] = 'Sonntag';
weekday[1] = 'Montag';
weekday[2] = 'Dienstag';
weekday[3] = 'Mittwoch';
weekday[4] = 'Donnerstag';
weekday[5] = 'Freitag';
weekday[6] = 'Samstag';
var currentDayString = weekday[currentDay];

var geo_location = 'Karlsruhe';
var geocode = new Array(2);
geocode[0] = 49.0068901;  // latitude
geocode[1] = 8.4036527; // longitude

function main(params) {
    if ('__ow_body' in params) { // For testing this action!!
        params = JSON.parse(params.__ow_body);
    }

    console.log('------Weather Action started!------');
    console.log('WeatherAction Params:' + JSON.stringify(params, null, 4));
    console.log('Day: ' + currentDay);
    console.log('DayString: ' + currentDayString);
    params.units = 'm';
    params.language = 'de-DE';

    var qs = {language: params.language, units: params.units};
    if ('latitude' in params && 'longitude' in params) {
        geocode[0] = params.latitude;
        geocode[1] = params.longitude;
    }
    if ('geo_location' in params) {
        geo_location = params.geo_location;
    }

    var optionsObservation = {
        url: weather_host + '/api/weather/v1/geocode/' + geocode[0] + '/' + geocode[1] + '/observations.json',
        qs: qs
    };

    var optionsForecast = {
        url: weather_host + '/api/weather/v1/geocode/' + geocode[0] + '/' + geocode[1] + '/forecast/daily/3day.json',
        qs: qs
    };

    var observationHtmlString;

    return request(optionsObservation)
        .then(function (response) {
            return processObservationData(response);

        }).then(function (response) {
            observationHtmlString = response;
            return request(optionsForecast);

        }).then(function (response) {
            return processForecastData(response, observationHtmlString);

        }).then(function (response) {
            return response;
        });
}

function processObservationData(observationData) {
    var data = JSON.parse(observationData);
    var observation = data.observation;
    var weatherHtml = "
";

    weatherHtml += "
" + geo_location + "
";
    weatherHtml += "
" + observation.wx_phrase + "
";
    weatherHtml += "
" + observation.temp + "℃
";
    weatherHtml += "
";

    return weatherHtml;
}

function processForecastData(forecastData, weatherHtml) {
    var resultObject = {};
    var data = JSON.parse(forecastData);
    var forecasts = data.forecasts, forecastsLength = forecasts.length;

    weatherHtml += '
';

    for (var i = 1; i < forecastsLength; i++) {
        var forecast = forecasts[i];

        var day = forecast.day, //night = forecast.night, shortcast = forecast.shortcast,
            max_temp = forecast.max_temp, min_temp = forecast.min_temp, dow = forecast.dow;

        weatherHtml += '
' + dow + '		' + max_temp + " Grad	" + min_temp + " Grad
";
    }

    weatherHtml += '
';
    resultObject.htmlText = weatherHtml;
    var payloadShortcast;

    if ('day' in forecasts[0]) {
        payloadShortcast = forecasts[0].day.shortcast;
    } else {
        payloadShortcast = forecasts[0].night.shortcast;
    }

    resultObject.payload = 'In ' + geo_location + ' wird es heute ' + payloadShortcast;

    return resultObject;
}

function getIconURL(code) {
    return "http://weather-company-data-demo.eu-gb.mybluemix.net/images/weathericons/icon" + code + ".png";
}

exports.main = main;


text:
function isSeller(name) {
  return name.split('').pop() === 'm';
}

export default function bfs(graph, name) {
  const queue = [...graph[name]];
  const searched = new Set();

  while (queue.length > 0) {
    const person = queue.shift();

    if (!searched.has(person)) {
      if (isSeller(person)) {
        return person;
      }

      queue.push(...graph[person]);
      searched.add(person);
    }
  }

  return false;
}


text:
package net.i2p.router.startup;
/*
 * free (adj.): unencumbered; not under the control of others
 * Written by jrandom in 2003 and released into the public domain
 * with no warranty of any kind, either expressed or implied.
 * It probably won't make your computer catch on fire, or eat
 * your children, but it might.  Use at your own risk.
 *
 */

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.util.Properties;

import net.i2p.crypto.SigType;
import net.i2p.data.Certificate;
import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;
import net.i2p.data.KeyCertificate;
import net.i2p.data.PrivateKey;
import net.i2p.data.PrivateKeyFile;
import net.i2p.data.PublicKey;
import net.i2p.data.router.RouterIdentity;
import net.i2p.data.router.RouterInfo;
import net.i2p.data.SigningPrivateKey;
import net.i2p.data.SigningPublicKey;
import net.i2p.data.SimpleDataStructure;
import net.i2p.router.Job;
import net.i2p.router.JobImpl;
import net.i2p.router.Router;
import net.i2p.router.RouterContext;
import net.i2p.router.util.EventLog;
import net.i2p.util.Log;
import net.i2p.util.SecureFileOutputStream;

/**
 *  Warning - misnamed. This creates a new RouterIdentity, i.e.
 *  new router keys and hash. It then builds a new RouterInfo
 *  and saves all the keys. This is generally run only once, on a new install.
 *
 */
public class CreateRouterInfoJob extends JobImpl {
    private final Log _log;
    private final Job _next;

    public static final String INFO_FILENAME = "router.info";
    public static final String KEYS_FILENAME = "router.keys";
    public static final String KEYS2_FILENAME = "router.keys.dat";
    private static final String PROP_ROUTER_SIGTYPE = "router.sigType";
    /** TODO when changing, check isAvailable() and fallback to DSA_SHA1 */
    private static final SigType DEFAULT_SIGTYPE = SigType.DSA_SHA1;

    CreateRouterInfoJob(RouterContext ctx, Job next) {
        super(ctx);
        _next = next;
        _log = ctx.logManager().getLog(CreateRouterInfoJob.class);
    }

    public String getName() { return "Create New Router Info"; }

    public void runJob() {
        _log.debug("Creating the new router info");
        // create a new router info and store it where LoadRouterInfoJob looks
        synchronized (getContext().router().routerInfoFileLock) {
            createRouterInfo();
        }
        getContext().jobQueue().addJob(_next);
    }

    /**
     *  Writes 6 files: router.info (standard RI format),
     *  router.keys.dat, and 4 individual key files under keyBackup/
     *
     *  router.keys.dat file format: This is the
     *  same "eepPriv.dat" format used by the client code,
     *  as documented in PrivateKeyFile.
     *
     *  Old router.keys file format: Note that this is NOT the
     *  same "eepPriv.dat" format used by the client code.
     *

     *   - Private key (256 bytes)
     *   - Signing Private key (20 bytes)
     *   - Public key (256 bytes)
     *   - Signing Public key (128 bytes)
     *  Total 660 bytes
     *

     *
     *  Caller must hold Router.routerInfoFileLock.
     */
    RouterInfo createRouterInfo() {
        SigType type = getSigTypeConfig(getContext());
        RouterInfo info = new RouterInfo();
        OutputStream fos1 = null;
        try {
            info.setAddresses(getContext().commSystem().createAddresses());
            Properties stats = getContext().statPublisher().publishStatistics();
            stats.setProperty(RouterInfo.PROP_NETWORK_ID, Router.NETWORK_ID+"");
            getContext().router().addCapabilities(info);
            info.setOptions(stats);
            // not necessary, in constructor
            //info.setPeers(new HashSet());
            info.setPublished(getCurrentPublishDate(getContext()));
            Object keypair[] = getContext().keyGenerator().generatePKIKeypair();
            PublicKey pubkey = (PublicKey)keypair[0];
            PrivateKey privkey = (PrivateKey)keypair[1];
            SimpleDataStructure signingKeypair[] = getContext().keyGenerator().generateSigningKeys(type);
            SigningPublicKey signingPubKey = (SigningPublicKey)signingKeypair[0];
            SigningPrivateKey signingPrivKey = (SigningPrivateKey)signingKeypair[1];
            RouterIdentity ident = new RouterIdentity();
            Certificate cert = createCertificate(getContext(), signingPubKey);
            ident.setCertificate(cert);
            ident.setPublicKey(pubkey);
            ident.setSigningPublicKey(signingPubKey);
            byte[] padding;
            int padLen = SigningPublicKey.KEYSIZE_BYTES - signingPubKey.length();
            if (padLen > 0) {
                padding = new byte[padLen];
                getContext().random().nextBytes(padding);
                ident.setPadding(padding);
            } else {
                padding = null;
            }
            info.setIdentity(ident);

            info.sign(signingPrivKey);

            if (!info.isValid())
                throw new DataFormatException("RouterInfo we just built is invalid: " + info);

            // remove router.keys
            (new File(getContext().getRouterDir(), KEYS_FILENAME)).delete();

            // write router.info
            File ifile = new File(getContext().getRouterDir(), INFO_FILENAME);
            fos1 = new BufferedOutputStream(new SecureFileOutputStream(ifile));
            info.writeBytes(fos1);

            // write router.keys.dat
            File kfile = new File(getContext().getRouterDir(), KEYS2_FILENAME);
            PrivateKeyFile pkf = new PrivateKeyFile(kfile, pubkey, signingPubKey, cert,
                                                    privkey, signingPrivKey, padding);
            pkf.write();

            getContext().keyManager().setKeys(pubkey, privkey, signingPubKey, signingPrivKey);

            if (_log.shouldLog(Log.INFO))
                _log.info("Router info created and stored at " + ifile.getAbsolutePath() + " with private keys stored at " + kfile.getAbsolutePath() + " [" + info + "]");
            getContext().router().eventLog().addEvent(EventLog.REKEYED, ident.calculateHash().toBase64());
        } catch (GeneralSecurityException gse) {
            _log.log(Log.CRIT, "Error building the new router information", gse);
        } catch (DataFormatException dfe) {
            _log.log(Log.CRIT, "Error building the new router information", dfe);
        } catch (IOException ioe) {
            _log.log(Log.CRIT, "Error writing out the new router information", ioe);
        } finally {
            if (fos1 != null) try { fos1.close(); } catch (IOException ioe) {}
        }
        return info;
    }

    /**
     *  The configured SigType to expect on read-in
     *  @since 0.9.16
     */
    public static SigType getSigTypeConfig(RouterContext ctx) {
        SigType cstype = CreateRouterInfoJob.DEFAULT_SIGTYPE;
        String sstype = ctx.getProperty(PROP_ROUTER_SIGTYPE);
        if (sstype != null) {
            SigType ntype = SigType.parseSigType(sstype);
            if (ntype != null)
                cstype = ntype;
        }
        // fallback?
        if (cstype != SigType.DSA_SHA1 && !cstype.isAvailable())
            cstype = SigType.DSA_SHA1;
        return cstype;
    }

    /**
     * We probably don't want to expose the exact time at which a router published its info.
     * perhaps round down to the nearest minute?  10 minutes?  30 minutes?  day?
     *
     */
    static long getCurrentPublishDate(RouterContext context) {
        //_log.info("Setting published date to /now/");
        return context.clock().now();
    }

    /**
     *  Only called at startup via LoadRouterInfoJob and RebuildRouterInfoJob.
     *  Not called by periodic RepublishLocalRouterInfoJob.
     *  We don't want to change the cert on the fly as it changes the router hash.
     *  RouterInfo.isHidden() checks the capability, but RouterIdentity.isHidden() checks the cert.
     *  There's no reason to ever add a hidden cert?
     *
     *  @return the certificate for a new RouterInfo - probably a null cert.
     *  @since 0.9.16 moved from Router
     */
    static Certificate createCertificate(RouterContext ctx, SigningPublicKey spk) {
        if (spk.getType() != SigType.DSA_SHA1)
            return new KeyCertificate(spk);
        if (ctx.getBooleanProperty(Router.PROP_HIDDEN))
            return new Certificate(Certificate.CERTIFICATE_TYPE_HIDDEN, null);
        return Certificate.NULL_CERT;
    }
}


text:
title: 'Trigger and Job Listeners'
---

Listeners are objects that you create to perform actions based on events occuring within the scheduler.
As you can probably guess, TriggerListeners receive events related to triggers, and JobListeners receive events related to jobs.

Trigger-related events include: trigger firings, trigger mis-firings (discussed in the "Triggers" section of this document),
and trigger completions (the jobs fired off by the trigger is finished).

::: danger
Make sure your trigger and job listeners never throw an exception (use a try-catch) and that they can handle internal problems.
Jobs can get stuck after Quartz is unable to determine whether required logic in listener was completed successfully when listener notification failed.
:::

__The ITriggerListener Interface__

```csharp
public interface ITriggerListener
{
	 string Name { get; }

	 Task TriggerFired(ITrigger trigger, IJobExecutionContext context);

	 Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context);

	 Task TriggerMisfired(ITrigger trigger);

	 Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, int triggerInstructionCode);
}
```

Job-related events include: a notification that the job is about to be executed, and a notification when the job has completed execution.

__The IJobListener Interface__

```csharp
public interface IJobListener
{
	string Name { get; }

	Task JobToBeExecuted(IJobExecutionContext context);

	Task JobExecutionVetoed(IJobExecutionContext context);

	Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException);
}
```

## Using Your Own Listeners

To create a listener, simply create an object the implements either the `ITriggerListener` and/or `IJobListener` interface.
Listeners are then registered with the scheduler during run time, and must be given a name (or rather, they must advertise their own
name via their Name property.

For your convenience, rather than implementing those interfaces, your class could also extend the class `JobListenerSupport` or `TriggerListenerSupport`
and simply override the events you're interested in.

Listeners are registered with the scheduler's `ListenerManager` along with a Matcher that describes which Jobs/Triggers the listener wants to receive events for.

::: tip
Listeners are registered with the scheduler during run time, and are **NOT** stored in the JobStore along with the jobs and triggers.
This is because listeners are typically an integration point with your application.
Hence, each time your application runs, the listeners need to be re-registered with the scheduler.
:::

**Adding a JobListener that is interested in a particular job:**

```csharp
scheduler.ListenerManager.AddJobListener(myJobListener, KeyMatcher<JobKey>.KeyEquals(new JobKey("myJobName", "myJobGroup")));
```

**Adding a JobListener that is interested in all jobs of a particular group:**

```csharp
scheduler.ListenerManager.AddJobListener(myJobListener, GroupMatcher<JobKey>.GroupEquals("myJobGroup"));
```

**Adding a JobListener that is interested in all jobs of two particular groups:**

```csharp
scheduler.ListenerManager.AddJobListener(myJobListener,
	OrMatcher<JobKey>.Or(GroupMatcher<JobKey>.GroupEquals("myJobGroup"), GroupMatcher<JobKey>.GroupEquals("yourGroup")));
```

**Adding a JobListener that is interested in all jobs:**

```csharp
scheduler.ListenerManager.AddJobListener(myJobListener, GroupMatcher<JobKey>.AnyGroup());
```

Listeners are not used by most users of Quartz.NET, but are handy when application requirements create the need
for the notification of events, without the Job itself explicitly notifying the application.


text:
#include <string.h>

#include <rte_cycles.h>
#include <rte_malloc.h>
#include <rte_test.h>
#include <rte_dmadev.h>

extern int test_dma_api(uint16_t dev_id);

#define DMA_TEST_API_RUN(test) \
	testsuite_run_test(test, #test)

#define TEST_MEMCPY_SIZE	1024
#define TEST_WAIT_US_VAL	50000

#define TEST_SUCCESS 0
#define TEST_FAILED  -1

static int16_t test_dev_id;
static int16_t invalid_dev_id;

static char *src;
static char *dst;

static int total;
static int passed;
static int failed;

static int
testsuite_setup(int16_t dev_id)
{
	test_dev_id = dev_id;
	invalid_dev_id = -1;

	src = rte_malloc("dmadev_test_src", TEST_MEMCPY_SIZE, 0);
	if (src == NULL)
		return -ENOMEM;
	dst = rte_malloc("dmadev_test_dst", TEST_MEMCPY_SIZE, 0);
	if (dst == NULL) {
		rte_free(src);
		src = NULL;
		return -ENOMEM;
	}

	total = 0;
	passed = 0;
	failed = 0;

	/* Set dmadev log level to critical to suppress unnecessary output
	 * during API tests.
	 */
	rte_log_set_level_pattern("lib.dmadev", RTE_LOG_CRIT);

	return 0;
}

static void
testsuite_teardown(void)
{
	rte_free(src);
	src = NULL;
	rte_free(dst);
	dst = NULL;
	/* Ensure the dmadev is stopped. */
	rte_dma_stop(test_dev_id);

	rte_log_set_level_pattern("lib.dmadev", RTE_LOG_INFO);
}

static void
testsuite_run_test(int (*test)(void), const char *name)
{
	int ret = 0;

	if (test) {
		ret = test();
		if (ret < 0) {
			failed++;
			printf("%s Failed\n", name);
		} else {
			passed++;
			printf("%s Passed\n", name);
		}
	}

	total++;
}

static int
test_dma_get_dev_id_by_name(void)
{
	int ret = rte_dma_get_dev_id_by_name("invalid_dmadev_device");
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	return TEST_SUCCESS;
}

static int
test_dma_is_valid_dev(void)
{
	int ret;
	ret = rte_dma_is_valid(invalid_dev_id);
	RTE_TEST_ASSERT(ret == false, "Expected false for invalid dev id");
	ret = rte_dma_is_valid(test_dev_id);
	RTE_TEST_ASSERT(ret == true, "Expected true for valid dev id");
	return TEST_SUCCESS;
}

static int
test_dma_count(void)
{
	uint16_t count = rte_dma_count_avail();
	RTE_TEST_ASSERT(count > 0, "Invalid dmadev count %u", count);
	return TEST_SUCCESS;
}

static int
test_dma_info_get(void)
{
	struct rte_dma_info info =  { 0 };
	int ret;

	ret = rte_dma_info_get(invalid_dev_id, &info);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	ret = rte_dma_info_get(test_dev_id, NULL);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	ret = rte_dma_info_get(test_dev_id, &info);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to obtain device info");

	return TEST_SUCCESS;
}

static int
test_dma_configure(void)
{
	struct rte_dma_conf conf = { 0 };
	struct rte_dma_info info = { 0 };
	int ret;

	/* Check for invalid parameters */
	ret = rte_dma_configure(invalid_dev_id, &conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	ret = rte_dma_configure(test_dev_id, NULL);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	/* Check for nb_vchans == 0 */
	memset(&conf, 0, sizeof(conf));
	ret = rte_dma_configure(test_dev_id, &conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	/* Check for conf.nb_vchans > info.max_vchans */
	ret = rte_dma_info_get(test_dev_id, &info);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to obtain device info");
	memset(&conf, 0, sizeof(conf));
	conf.nb_vchans = info.max_vchans + 1;
	ret = rte_dma_configure(test_dev_id, &conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	/* Check enable silent mode */
	memset(&conf, 0, sizeof(conf));
	conf.nb_vchans = info.max_vchans;
	conf.enable_silent = true;
	ret = rte_dma_configure(test_dev_id, &conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	/* Configure success */
	memset(&conf, 0, sizeof(conf));
	conf.nb_vchans = info.max_vchans;
	ret = rte_dma_configure(test_dev_id, &conf);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to configure dmadev, %d", ret);

	/* Check configure success */
	ret = rte_dma_info_get(test_dev_id, &info);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to obtain device info");
	RTE_TEST_ASSERT_EQUAL(conf.nb_vchans, info.nb_vchans,
			      "Configure nb_vchans not match");

	return TEST_SUCCESS;
}

static int
check_direction(void)
{
	struct rte_dma_vchan_conf vchan_conf;
	int ret;

	/* Check for direction */
	memset(&vchan_conf, 0, sizeof(vchan_conf));
	vchan_conf.direction = RTE_DMA_DIR_DEV_TO_DEV + 1;
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	vchan_conf.direction = RTE_DMA_DIR_MEM_TO_MEM - 1;
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	/* Check for direction and dev_capa combination */
	memset(&vchan_conf, 0, sizeof(vchan_conf));
	vchan_conf.direction = RTE_DMA_DIR_MEM_TO_DEV;
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	vchan_conf.direction = RTE_DMA_DIR_DEV_TO_MEM;
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	vchan_conf.direction = RTE_DMA_DIR_DEV_TO_DEV;
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	return 0;
}

static int
check_port_type(struct rte_dma_info *dev_info)
{
	struct rte_dma_vchan_conf vchan_conf;
	int ret;

	/* Check src port type validation */
	memset(&vchan_conf, 0, sizeof(vchan_conf));
	vchan_conf.direction = RTE_DMA_DIR_MEM_TO_MEM;
	vchan_conf.nb_desc = dev_info->min_desc;
	vchan_conf.src_port.port_type = RTE_DMA_PORT_PCIE;
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	/* Check dst port type validation */
	memset(&vchan_conf, 0, sizeof(vchan_conf));
	vchan_conf.direction = RTE_DMA_DIR_MEM_TO_MEM;
	vchan_conf.nb_desc = dev_info->min_desc;
	vchan_conf.dst_port.port_type = RTE_DMA_PORT_PCIE;
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	return 0;
}

static int
test_dma_vchan_setup(void)
{
	struct rte_dma_vchan_conf vchan_conf = { 0 };
	struct rte_dma_conf dev_conf = { 0 };
	struct rte_dma_info dev_info = { 0 };
	int ret;

	/* Check for invalid parameters */
	ret = rte_dma_vchan_setup(invalid_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	ret = rte_dma_vchan_setup(test_dev_id, 0, NULL);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	/* Make sure configure success */
	ret = rte_dma_info_get(test_dev_id, &dev_info);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to obtain device info");
	dev_conf.nb_vchans = dev_info.max_vchans;
	ret = rte_dma_configure(test_dev_id, &dev_conf);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to configure dmadev, %d", ret);

	/* Check for invalid vchan */
	ret = rte_dma_vchan_setup(test_dev_id, dev_conf.nb_vchans, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	/* Check for direction */
	ret = check_direction();
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to check direction");

	/* Check for nb_desc validation */
	memset(&vchan_conf, 0, sizeof(vchan_conf));
	vchan_conf.direction = RTE_DMA_DIR_MEM_TO_MEM;
	vchan_conf.nb_desc = dev_info.min_desc - 1;
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	vchan_conf.nb_desc = dev_info.max_desc + 1;
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	/* Check port type */
	ret = check_port_type(&dev_info);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to check port type");

	/* Check vchan setup success */
	memset(&vchan_conf, 0, sizeof(vchan_conf));
	vchan_conf.direction = RTE_DMA_DIR_MEM_TO_MEM;
	vchan_conf.nb_desc = dev_info.min_desc;
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to setup vchan, %d", ret);

	return TEST_SUCCESS;
}

static int
setup_one_vchan(void)
{
	struct rte_dma_vchan_conf vchan_conf = { 0 };
	struct rte_dma_info dev_info = { 0 };
	struct rte_dma_conf dev_conf = { 0 };
	int ret;

	ret = rte_dma_info_get(test_dev_id, &dev_info);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to obtain device info, %d", ret);
	dev_conf.nb_vchans = dev_info.max_vchans;
	ret = rte_dma_configure(test_dev_id, &dev_conf);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to configure, %d", ret);
	vchan_conf.direction = RTE_DMA_DIR_MEM_TO_MEM;
	vchan_conf.nb_desc = dev_info.min_desc;
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to setup vchan, %d", ret);

	return TEST_SUCCESS;
}

static int
test_dma_start_stop(void)
{
	struct rte_dma_vchan_conf vchan_conf = { 0 };
	struct rte_dma_conf dev_conf = { 0 };
	int ret;

	/* Check for invalid parameters */
	ret = rte_dma_start(invalid_dev_id);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	ret = rte_dma_stop(invalid_dev_id);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	/* Setup one vchan for later test */
	ret = setup_one_vchan();
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to setup one vchan, %d", ret);

	ret = rte_dma_start(test_dev_id);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to start, %d", ret);

	/* Check reconfigure and vchan setup when device started */
	ret = rte_dma_configure(test_dev_id, &dev_conf);
	RTE_TEST_ASSERT(ret == -EBUSY, "Failed to configure, %d", ret);
	ret = rte_dma_vchan_setup(test_dev_id, 0, &vchan_conf);
	RTE_TEST_ASSERT(ret == -EBUSY, "Failed to setup vchan, %d", ret);

	ret = rte_dma_stop(test_dev_id);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to stop, %d", ret);

	return TEST_SUCCESS;
}

static int
test_dma_stats(void)
{
	struct rte_dma_info dev_info = { 0 };
	struct rte_dma_stats stats = { 0 };
	int ret;

	/* Check for invalid parameters */
	ret = rte_dma_stats_get(invalid_dev_id, 0, &stats);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	ret = rte_dma_stats_get(invalid_dev_id, 0, NULL);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	ret = rte_dma_stats_reset(invalid_dev_id, 0);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	/* Setup one vchan for later test */
	ret = setup_one_vchan();
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to setup one vchan, %d", ret);

	/* Check for invalid vchan */
	ret = rte_dma_info_get(test_dev_id, &dev_info);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to obtain device info, %d", ret);
	ret = rte_dma_stats_get(test_dev_id, dev_info.max_vchans, &stats);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);
	ret = rte_dma_stats_reset(test_dev_id, dev_info.max_vchans);
	RTE_TEST_ASSERT(ret == -EINVAL, "Expected -EINVAL, %d", ret);

	/* Check for valid vchan */
	ret = rte_dma_stats_get(test_dev_id, 0, &stats);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to get stats, %d", ret);
	ret = rte_dma_stats_get(test_dev_id, RTE_DMA_ALL_VCHAN, &stats);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to get all stats, %d", ret);
	ret = rte_dma_stats_reset(test_dev_id, 0);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to reset stats, %d", ret);
	ret = rte_dma_stats_reset(test_dev_id, RTE_DMA_ALL_VCHAN);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to reset all stats, %d", ret);

	return TEST_SUCCESS;
}

static int
test_dma_dump(void)
{
	int ret;

	/* Check for invalid parameters */
	ret = rte_dma_dump(invalid_dev_id, stderr);
	RTE_TEST_ASSERT(ret == -EINVAL, "Excepted -EINVAL, %d", ret);
	ret = rte_dma_dump(test_dev_id, NULL);
	RTE_TEST_ASSERT(ret == -EINVAL, "Excepted -EINVAL, %d", ret);

	return TEST_SUCCESS;
}

static void
setup_memory(void)
{
	int i;

	for (i = 0; i < TEST_MEMCPY_SIZE; i++)
		src[i] = (char)i;
	memset(dst, 0, TEST_MEMCPY_SIZE);
}

static int
verify_memory(void)
{
	int i;

	for (i = 0; i < TEST_MEMCPY_SIZE; i++) {
		if (src[i] == dst[i])
			continue;
		RTE_TEST_ASSERT_EQUAL(src[i], dst[i],
			"Failed to copy memory, %d %d", src[i], dst[i]);
	}

	return 0;
}

static int
test_dma_completed(void)
{
	uint16_t last_idx = 1;
	bool has_error = true;
	uint16_t cpl_ret;
	int ret;

	/* Setup one vchan for later test */
	ret = setup_one_vchan();
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to setup one vchan, %d", ret);

	ret = rte_dma_start(test_dev_id);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to start, %d", ret);

	setup_memory();

	/* Check enqueue without submit */
	ret = rte_dma_copy(test_dev_id, 0, (rte_iova_t)src, (rte_iova_t)dst,
			   TEST_MEMCPY_SIZE, 0);
	RTE_TEST_ASSERT_EQUAL(ret, 0, "Failed to enqueue copy, %d", ret);
	rte_delay_us_sleep(TEST_WAIT_US_VAL);
	cpl_ret = rte_dma_completed(test_dev_id, 0, 1, &last_idx, &has_error);
	RTE_TEST_ASSERT_EQUAL(cpl_ret, 0, "Failed to get completed");

	/* Check add submit */
	ret = rte_dma_submit(test_dev_id, 0);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to submit, %d", ret);
	rte_delay_us_sleep(TEST_WAIT_US_VAL);
	cpl_ret = rte_dma_completed(test_dev_id, 0, 1, &last_idx, &has_error);
	RTE_TEST_ASSERT_EQUAL(cpl_ret, 1, "Failed to get completed");
	RTE_TEST_ASSERT_EQUAL(last_idx, 0, "Last idx should be zero, %u",
				last_idx);
	RTE_TEST_ASSERT_EQUAL(has_error, false, "Should have no error");
	ret = verify_memory();
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to verify memory");

	setup_memory();

	/* Check for enqueue with submit */
	ret = rte_dma_copy(test_dev_id, 0, (rte_iova_t)src, (rte_iova_t)dst,
			   TEST_MEMCPY_SIZE, RTE_DMA_OP_FLAG_SUBMIT);
	RTE_TEST_ASSERT_EQUAL(ret, 1, "Failed to enqueue copy, %d", ret);
	rte_delay_us_sleep(TEST_WAIT_US_VAL);
	cpl_ret = rte_dma_completed(test_dev_id, 0, 1, &last_idx, &has_error);
	RTE_TEST_ASSERT_EQUAL(cpl_ret, 1, "Failed to get completed");
	RTE_TEST_ASSERT_EQUAL(last_idx, 1, "Last idx should be 1, %u",
				last_idx);
	RTE_TEST_ASSERT_EQUAL(has_error, false, "Should have no error");
	ret = verify_memory();
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to verify memory");

	/* Stop dmadev to make sure dmadev to a known state */
	ret = rte_dma_stop(test_dev_id);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to stop, %d", ret);

	return TEST_SUCCESS;
}

static int
test_dma_completed_status(void)
{
	enum rte_dma_status_code status[1] = { 1 };
	uint16_t last_idx = 1;
	uint16_t cpl_ret, i;
	int ret;

	/* Setup one vchan for later test */
	ret = setup_one_vchan();
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to setup one vchan, %d", ret);

	ret = rte_dma_start(test_dev_id);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to start, %d", ret);

	/* Check for enqueue with submit */
	ret = rte_dma_copy(test_dev_id, 0, (rte_iova_t)src, (rte_iova_t)dst,
			   TEST_MEMCPY_SIZE, RTE_DMA_OP_FLAG_SUBMIT);
	RTE_TEST_ASSERT_EQUAL(ret, 0, "Failed to enqueue copy, %d", ret);
	rte_delay_us_sleep(TEST_WAIT_US_VAL);
	cpl_ret = rte_dma_completed_status(test_dev_id, 0, 1, &last_idx,
					   status);
	RTE_TEST_ASSERT_EQUAL(cpl_ret, 1, "Failed to completed status");
	RTE_TEST_ASSERT_EQUAL(last_idx, 0, "Last idx should be zero, %u",
				last_idx);
	for (i = 0; i < RTE_DIM(status); i++)
		RTE_TEST_ASSERT_EQUAL(status[i], 0,
				"Failed to completed status, %d", status[i]);

	/* Check do completed status again */
	cpl_ret = rte_dma_completed_status(test_dev_id, 0, 1, &last_idx,
					   status);
	RTE_TEST_ASSERT_EQUAL(cpl_ret, 0, "Failed to completed status");

	/* Check for enqueue with submit again */
	ret = rte_dma_copy(test_dev_id, 0, (rte_iova_t)src, (rte_iova_t)dst,
			   TEST_MEMCPY_SIZE, RTE_DMA_OP_FLAG_SUBMIT);
	RTE_TEST_ASSERT_EQUAL(ret, 1, "Failed to enqueue copy, %d", ret);
	rte_delay_us_sleep(TEST_WAIT_US_VAL);
	cpl_ret = rte_dma_completed_status(test_dev_id, 0, 1, &last_idx,
					   status);
	RTE_TEST_ASSERT_EQUAL(cpl_ret, 1, "Failed to completed status");
	RTE_TEST_ASSERT_EQUAL(last_idx, 1, "Last idx should be 1, %u",
				last_idx);
	for (i = 0; i < RTE_DIM(status); i++)
		RTE_TEST_ASSERT_EQUAL(status[i], 0,
				"Failed to completed status, %d", status[i]);

	/* Stop dmadev to make sure dmadev to a known state */
	ret = rte_dma_stop(test_dev_id);
	RTE_TEST_ASSERT_SUCCESS(ret, "Failed to stop, %d", ret);

	return TEST_SUCCESS;
}

int
test_dma_api(uint16_t dev_id)
{
	int ret = testsuite_setup(dev_id);
	if (ret) {
		printf("testsuite setup fail!\n");
		return -1;
	}

	/* If the testcase exit successfully, ensure that the test dmadev exist
	 * and the dmadev is in the stopped state.
	 */
	DMA_TEST_API_RUN(test_dma_get_dev_id_by_name);
	DMA_TEST_API_RUN(test_dma_is_valid_dev);
	DMA_TEST_API_RUN(test_dma_count);
	DMA_TEST_API_RUN(test_dma_info_get);
	DMA_TEST_API_RUN(test_dma_configure);
	DMA_TEST_API_RUN(test_dma_vchan_setup);
	DMA_TEST_API_RUN(test_dma_start_stop);
	DMA_TEST_API_RUN(test_dma_stats);
	DMA_TEST_API_RUN(test_dma_dump);
	DMA_TEST_API_RUN(test_dma_completed);
	DMA_TEST_API_RUN(test_dma_completed_status);

	testsuite_teardown();

	printf("Total tests   : %d\n", total);
	printf("Passed        : %d\n", passed);
	printf("Failed        : %d\n", failed);

	if (failed)
		return -1;

	return 0;
};


text:
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class Users extends Public_Controller
{
    function __construct()
    {
        parent::__construct();
    }

    // ------------------------------------------------------------------------

    public function login()
    {
        // Init
        $data = array();
        $this->load->model('users_model');

        // Prevent IE users from caching this page
        if( ! isset($_SESSION))
        {
            session_start();
        }

        // If redirect session var set redirect to home page
        if ( ! $redirect_to = $this->session->userdata('redirect_to'))
        {
            $redirect_to = '/';
        }

        // If user is already logged in redirect to desired location
        if ($this->secure->is_auth())
        {
            redirect($redirect_to);
        }

        // Check if user has a remember me cookie
        if ($this->users_model->check_remember_me())
        {
            redirect($redirect_to);
        }

        // Form Validation
        $this->form_validation->set_rules('email', 'Username', 'trim|required');
        $this->form_validation->set_rules('password', 'Password', 'trim|required');

        // Process Form
        if ($this->form_validation->run() == TRUE)
        {
            $Data = array_to_object($this->input->post());

            // Database query to lookup email and password
            if ($this->users_model->login($this->input->post('email'), $this->input->post('password')))
            {
                redirect($redirect_to);
            }

            redirect(current_url());
        }

        // If the user was attempting to log into the admin panel use the admin theme
        if ($this->uri->segment(1) == ADMIN_PATH)
        {
            $this->template->set_theme('admin', 'default', ADMIN_THEME_PATH);
            $this->template->set_layout('default_wo_errors');

            $this->template->add_package('jquery');
            $this->template->add_script("
                $(document).ready(function() {
                    $('#email').focus();
                });");

            $this->template->view("admin/login", $data);
        }
        else
        {
            $this->template->view("/users/login", $data);
        }
    }

    // ------------------------------------------------------------------------

    public function register()
    {
        // Init
        $data = array();
        $data['states'] = unserialize(STATES);

        // Check that user registration is enabled
        if ( ! $this->settings->users_module->enable_registration)
        {
            return show_404();
        }

        // Validate Form
        $this->form_validation->set_rules('email', 'Email', "trim|required|valid_email|callback_email_check");
        $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]');
        $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
        $this->form_validation->set_rules('first_name', 'First Name', 'trim|required');
        $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
        // $this->form_validation->set_rules('phone', 'Phone', 'required|format_phone');
        // $this->form_validation->set_rules('address', 'Address', 'trim|required');
        // $this->form_validation->set_rules('address2', 'Address 2', 'trim');
        // $this->form_validation->set_rules('city', 'City', 'trim|required');
        // $this->form_validation->set_rules('state', 'State', 'trim|required');
        // $this->form_validation->set_rules('zip', 'Zip', 'trim|required');
        $this->form_validation->set_rules('spam_check', 'Spam Check', 'trim');

        if ($this->form_validation->run() == TRUE)
        {
            // Use spam_check to filter spam
            // Stops bots that attempt to fill the field which is hidden by CSS
            if ($this->input->post('spam_check') != '')
            {
                return $this->template->view('/users/register', $data);
            }

            $this->load->model('users_model');
            $this->users_model->from_array($this->input->post());
            $this->users_model->id = NULL; // Prevent someone from trying to post an ID
            $this->users_model->group_id = $this->settings->users_module->default_group;
            $this->users_model->password = md5($this->config->item('encryption_key') . $this->input->post('password'));
            $this->users_model->created_date = date('Y-m-d H:i:s');

            // Generate and send activation email
            if ($this->settings->users_module->email_activation)
            {
                $this->users_model->activation_code = md5($this->users_model->id . strtotime($this->users_model->created_date) . mt_rand());
                $this->users_model->activated = 0;
                $this->users_model->save();

                $subject = $this->settings->site_name . ' Activation';
                $message = "Thank you for your new member registration.\n\nTo activate your account, please visit the following URL\n\n" . site_url('users/activate/' . $this->users_model->id . '/' . $this->users_model->activation_code) . "\n\nThank You!\n\n" . $this->settings->site_name;

                // Generate and send email
                $this->_sendmail(
                    $this->settings->mail_reply_email, // From
                    $this->settings->site_name, // From name
                    $this->users_model->email, // To
                    $subject,  // Subject
                    $message // Message body
                );

                $this->session->set_flashdata('message', '
An email containing your activation code has been sent to your email address.
');

                redirect('/users/login');
            }
            else
            {
                $this->users_model->save();
                $this->users_model->create_session(); // Create session and log the user in

                redirect('/');
            }
        }

        $this->template->view('/users/register', $data);
    }

    // ------------------------------------------------------------------------

    public function logout()
    {
        $this->load->model('users_model');

        // Check if current user was an admin logged in as another user
        if (isset($this->secure->get_user_session()->admin_id))
        {
            $this->users_model->get_by_id($this->secure->get_user_session()->admin_id);

            // Return to admin session
            if ($this->users_model->exists())
            {
                $this->users_model->create_session();

                redirect(ADMIN_PATH);
            }
        }

        // Check if we should redirect to a particular page upon loggin out
        if ($this->session->userdata('logout_redirect_to'))
        {
            $redirect_to = $this->session->userdata('logout_redirect_to');
        }
        else
        {
            $redirect_to = '/';
        }

        // Delete all session data
        $this->session->sess_destroy();
        $this->users_model->destroy_remember_me();

        redirect($redirect_to);
    }

    // ------------------------------------------------------------------------

    public function forgot_password()
    {
        // Init
        $data = array();

        $enable_logging = $this->settings->enable_logging;

        // Form Validation
        $this->form_validation->set_rules('email', 'Email', 'trim|valid_email|required|callback_email_exists');

        if ($this->form_validation->run() == TRUE)
        {
            // Randomly string together a human readable 8 character password
            $pass = ucfirst(random_readable_string(4)) . random_number(4);

            $User = $this->input->post('user');

            // Generate and send email
            $send = $this->_sendmail(
                $this->settings->mail_reply_email, // From
                $this->settings->site_name, // From name
                $User->email, // To
                'Password Reset',   // Subject
                "Your " . $this->settings->site_name . " password has been reset.\n\nYour new password is: $pass"  // Message body
            );

            // Set users password in database
            $User->password = md5($this->config->item('encryption_key') . $pass);

            $this->load->model('users_model');
            $User->save();

            if($send)
            {
                $this->session->set_flashdata('message', '
An email containing your new password has been sent to your email address.
');
                if ($enable_logging) {
                    $error_message = 'Password send success: A password was generated for account ['. $User->email .'] and the email was successfully sent.';
                    log_message('debug', $error_message);
                }
            }
            else
            {
                $this->session->set_flashdata('message', '
Cannot send generated password.
');
                if ($enable_logging) {
                    $error_message = 'Password send failure: A password was generated for account ['. $User->email .'] but the email failed to send.';
                    log_message('error', $error_message);
                }
            }

            if ($this->uri->segment(1) == ADMIN_PATH)
            {
                redirect(ADMIN_PATH . '/users/login');
            }
            else
            {
                redirect('users/login');
            }
        }

        // If user was in admin panel load admin view
        if ($this->uri->segment(1) == ADMIN_PATH)
        {
            $this->template->set_theme('admin', 'default', 'application/themes');
            $this->template->set_layout('default_wo_errors');

            $this->template->add_package('jquery');
            $this->template->add_script("
                $(document).ready(function() {
                    $('#email').focus();
                });");
            $this->template->view("admin/forgot_password", $data);
        }
        else
        {
            $this->template->view("/users/forgot_password", $data);
        }
    }

    // ------------------------------------------------------------------------

    public function activate()
    {
        // Init
        $data = array();
        $this->load->model('users_model');
        $user_id = $this->uri->segment(3);
        $activation_code = $this->uri->segment(4);

        // Check that user email activation is enabled
        if ( ! $this->settings->users_module->email_activation)
        {
            return show_404();
        }

        if ( ! $user_id ||  ! $activation_code)
        {
            return show_404();
        }

        // Lookup user by id and activation code
        $data['User'] = $User = $this->users_model
            ->where('id', $user_id)
            ->where('activation_code', $activation_code)
            ->get();

        // Show 404 if user not found
        if ( ! $User->exists())
        {
            return show_404();
        }

        $data['new_activation'] = FALSE;

        if ( ! $User->activated)
        {
            $User->activated = 1;
            $User->save();
            $data['new_activation'] = TRUE;
        }

        $this->template->view('/users/activate', $data);
    }

    /*
     * Form Validation callback to check that the provided email address exists.
     */
    function email_exists($email)
    {
        $this->load->model('users_model');
        $User = $this->users_model->where("email = '$email'")->get();
        $enable_logging = $this->settings->enable_logging;

        if ( ! $User->exists())
        {
            $this->form_validation->set_message('email_exists', "The email address $email was not found.");
            if ($enable_logging) {
                $error_message = "Email address not found: User email [{$email}] was trying to reset their password.";
                log_message('error', $error_message);
            }
            return FALSE;
        }
        else
        {
            $_POST['user'] = $User;
            return TRUE;
        }
    }

    /*
     * Form Validation callback to check if an email address is already in use.
     */
    function email_check($email)
    {
        $this->load->model('users_model');
        $User = $this->users_model->where("email = '$email'")->get();

        if ($User->exists())
        {
            $this->form_validation->set_message('email_check', "This email address is already in use.");
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

    // ------------------------------------------------------------------------

    /**
     * Send Mail
     *
     * Builds and sends email to the specified address
     * Using PHPMailer to send email as html using SMTP service.
     *
     * @author     Cosmo Mathieu <cosmo@cosmointeractive.co>
     * @access     private
     * @return     bool
     */
    private function _sendmail($from, $fromName, $to, $subject, $message)
    {
        $config = array(
            'protocol'    => $this->settings->mail_protocol,
            'smtp_host'   => $this->settings->mail_server,
            'smtp_port'   => $this->settings->mail_outgoing_port,
            'smtp_user'   => $this->settings->mail_login,
            'smtp_pass'   => $this->settings->mail_password,
            'smtp_crypto' => $this->settings->mail_authen_srvc,
            'smtp_debug'  => ((ENVIRONMENT !== 'production') ? 2 : 0), // 2 to enable SMTP debug information
            'mailtype'    => 'html',
            'wrapchars'  => 76,
            'wordwrap'   => true,
        );
        $this->load->library('email', $config);
        // $this->load->library('parser');

		$result = $this->email
                ->from($from, $this->settings->site_name)
                ->reply_to($this->settings->mail_reply_email)    // Optional, an account where a human being reads.
                ->to($to)
                ->subject($subject)
                ->message($message)
                ->send();

        return $result;
    }
}


text:
  Chargé est
      une commune géographiquement positionnée dans le département de l'Indre-et-Loire en Centre. Elle comptait 1 013 habitants en 2008.

À Chargé, le prix moyen à l'achat d'un appartement s'évalue à 2 000 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 986 € du m². À la location la valeur moyenne se situe à 6,82 € du m² mensuel.

Le nombre de logements, à Chargé, se décomposait en 2011 en trois appartements et 532 maisons soit
 un marché plutôt équilibré.

La ville offre quelques  équipements sportifs, elle dispose, entre autres, de un terrain de tennis, un terrain de sport et un équipement de roller/skate.

À coté de Chargé sont localisées les communes de
Vallières-les-Grandes située à 8 km, 771 habitants,
Pocé-sur-Cisse à 3 km, 1 530 habitants,
Mosnes localisée à 5 km, 757 habitants,
Veuves située à 8 km, 220 habitants,
Saint-Règle située à 3 km, 340 habitants,
Lussault-sur-Loire localisée à 8 km, 703 habitants,
 entre autres. De plus, Chargé est située à seulement 26 km de Tours.


text:
Type a Phrase. Giphy Breaker will turn it into a GIF that you can break and collect!

Giphy Breaker allows you to put gifs onto breakable blocks.
After winning a level, you can collect the gif and start a new query and game!

##PLAY IT: https://giphybreaker.herokuapp.com/
![](./images/gameplay.jpg)
# How It Works:
 Upon receiving a query, the game makes a search request for a Giphy image. Giphy sends a request back to the game and the image is mapped onto the blocks of the game. Since each image has a unique size and shape, each arrangement of blocks is different. You'll never know what you're going to get.

#The Build:
 Giphy API, HTML Canvas, jQuery, CSS, HTML 5, Animate.css, and Javascript to create the game.

#In Development
-Adding Framerate control
-Improving overall performance of code

 #Difficulties and Bugs:
 The collisions with the ball were the hardest part. Once I got the collisions working and blocks disapearing, implementing the Giphy API was relatively straightforward. There may still be a couple of bugs. If you receive an image that is larger than the canvas, it may automatically win.


text:
namespace ODataValidator.RuleEngine
{
    #region Namespaces
    using System;
    using ODataValidator.RuleEngine.Common;
    using System.Collections.Generic;
    #endregion

    /// <summary>
    /// Delegate type for running semantic extension verification
    /// </summary>
    /// <param name="context">The Interop service context</param>
    /// <param name="info">out parameter to return vialoadtion information</param>
    /// <returns>The flag indicating wheter verifaction passes or not. Null if not applicable.</returns>
    internal delegate bool? ExtensionVerify(ServiceContext context, out ExtensionRuleViolationInfo info);

    /// <summary>
    /// Class of semantic extension rule verifier
    /// </summary>
    internal class ExtensionVerifier : IVerifier
    {
        /// <summary>
        /// The delegate object to semantic extension verification
        /// </summary>
        private ExtensionVerify semanticExtensionVerifier;

        /// <summary>
        /// Creates an instance of SemanticVerifier from an ExtensionVerify delegate object
        /// </summary>
        /// <param name="extensionVerifier">The ExtensionVerify delegate object</param>
        public ExtensionVerifier(ExtensionVerify extensionVerifier)
        {
            this.semanticExtensionVerifier = extensionVerifier;
        }

        /// <summary>
        /// Verifies whether the specific interop request context pass the validation or not
        /// </summary>
        /// <param name="context">Current interop request context</param>
        /// <param name="result">Output parameter of TestResult object</param>
        /// <returns>True if passed; false if failed</returns>
        public bool Verify(ServiceContext context, out TestResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? flagExec;
            ExtensionRuleViolationInfo info;
            flagExec = this.semanticExtensionVerifier(context, out info);
            bool passed = flagExec.HasValue ? flagExec.Value : true;
            result = new TestResult();

            if (info != null)
            {
                result.ErrorDetail = info.Message;
                result.LineNumberInError = info.PayloadLineNumberInError;
                if (info.Endpoint != null)
                {
                    result.TextInvolved = info.Endpoint.AbsoluteUri;
                }

                if (info.Details != null)
                {
                    result.Details = new List<ExtensionRuleResultDetail>();

                    foreach (ExtensionRuleResultDetail detail in info.Details)
                    {
                        result.Details.Add(detail.Clone());
                    }
                }
            }

            if (!flagExec.HasValue)
            {
                result.Classification = Constants.ClassificationNotApplicable;
            }

            return passed;
        }
    }
}


text:
import { Component } from '@angular/core'

@Component({
    selector: "titlebar",
    templateUrl: './titlebar.component.html',
    styleUrls: ['./titlebar.component.css']
})
export class TitleBarComponent {

}


text:
package com.rbmhtechnology.eventuate.adapter.vertx

import akka.actor.ActorSystem
import akka.testkit.TestKit
import com.rbmhtechnology.eventuate.adapter.vertx.api.{ EventProducer, VertxAdapterConfig }
import com.rbmhtechnology.eventuate.log.EventLogWriter
import com.rbmhtechnology.eventuate.log.leveldb.LeveldbEventLog
import com.rbmhtechnology.eventuate.utilities._
import com.rbmhtechnology.eventuate.{ LocationCleanupLeveldb, ReplicationEndpoint }
import com.typesafe.config.Config
import org.scalatest.{ BeforeAndAfterAll, MustMatchers, WordSpecLike }

import scala.collection.immutable.Seq

object VertxAdapterSpec {
  case class Event(id: String)

  val Config = TestConfig.withReplayBatchSize(10)
}

class VertxAdapterSpec extends TestKit(ActorSystem("test", VertxAdapterSpec.Config))
  with WordSpecLike with MustMatchers with BeforeAndAfterAll with StopSystemAfterAll with LocationCleanupLeveldb
  with VertxEnvironment with VertxEventBusProbes {

  import VertxAdapterSpec._
  import utilities._

  val logName = "logA"
  val adapterId = "adapter1"
  var storage: ActorStorageProvider = _
  var endpoint: ReplicationEndpoint = _

  override def config: Config = VertxAdapterSpec.Config

  override def beforeAll(): Unit = {
    super.beforeAll()
    storage = new ActorStorageProvider(adapterId)
    endpoint = new ReplicationEndpoint(id = "1", logNames = Set(logName), logFactory = logId => LeveldbEventLog.props(logId), connections = Set())
  }

  "A VertxAdapter" must {
    "read events from an inbound log and deliver them to the Vert.x eventbus" in {
      val log = endpoint.logs(logName)
      val adapterConfig = VertxAdapterConfig()
        .addProducer(EventProducer.fromLog(log)
          .publishTo {
            case _ => endpoint1.address
          }
          .as("adapter1"))
        .registerDefaultCodecFor(classOf[Event])

      val vertxAdapter = VertxAdapter(adapterConfig, vertx, storage)
      val logWriter = new EventLogWriter("w1", endpoint.logs(logName))

      endpoint.activate()
      vertxAdapter.start()

      logWriter.write(Seq(Event("1"))).await.head

      storage.expectRead(replySequenceNr = 0)
      storage.expectWrite(sequenceNr = 1)

      endpoint1.probe.expectVertxMsg(body = Event("1"))

      logWriter.write(Seq(Event("2"))).await

      storage.expectWrite(sequenceNr = 2)

      endpoint1.probe.expectVertxMsg(body = Event("2"))

      logWriter.write(Seq(Event("3"), Event("4"))).await

      storage.expectWriteAnyOf(sequenceNrs = Seq(3, 4))

      endpoint1.probe.expectVertxMsg(body = Event("3"))
      endpoint1.probe.expectVertxMsg(body = Event("4"))
    }
  }
}


text:
describe("Bind", function() {
    require("./bind-cases.spec");
    require("./bind.short.spec");
    require("./bind.on.spec");
    require('./bind.pathSyntax.spec');
});


text:
angular.module('opApp').directive('opLayer', function () {
    'use strict';

    return {
        scope: {},
        restrict: 'E',
        templateUrl: 'modules/sidebar/layer/opLayerSelect.html'
    };
});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
   >

    <ImageView
        android:id="@+id/im_logo"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/eafit002"
        android:layout_margin="16dp"
        android:layout_gravity="center"
        />

    <EditText
        android:id="@+id/et_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textSize="@dimen/dim_text_size_edit_text"
        android:hint="@string/hint_username"
        />

    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textSize="@dimen/dim_text_size_edit_text"
        android:hint="@string/hint_password"
        android:inputType="textPassword"

        />

    <Button
        android:id="@+id/btn_login"
        android:onClick="logIn"
        android:layout_width="match_parent"
        android:layout_margin="8dp"
        android:layout_height="wrap_content"
        android:text="@string/lb_btn_login" />

    <Button
        android:id="@+id/btn_sign_up"
        android:layout_width="match_parent"
        android:layout_margin="8dp"
        android:layout_height="wrap_content"
        android:text="@string/lb_btn_sign_up" />

</LinearLayout>


text:
import { Mesh, ShaderMaterial } from 'three';
import { CurvedLineShape } from '../../drawing/shape/curved-line-shape';
import { BaseBuffer } from '../base-buffer';
/**
 * This renders a curved line by injecting all attributes needed to render it.
 * This naively includes all possible data in the vertex.
 *
 * This ONLY supports a single color
 */
export declare class SimpleStaticBezierLineBuffer extends BaseBuffer<CurvedLineShape<any>, Mesh> {
    /**
     * @override
     * See interface definition
     */
    init(material: ShaderMaterial, unitCount: number): void;
    /**
     * @override
     * See interface definition
     *
     * @param shapeBuffer
     */
    update(shapeBuffer: CurvedLineShape<any>[]): boolean;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.IO;

namespace Record_Searcher
{
    //this class is here to log any errors or strangeness into the text file for it for debugging.
    public class Error
    {
       private static string BasePath;
       static string path;
       static string TxtFileName;
       private static List<string> errors;

        public Error()
        {
            //gets the path info
            TxtFileName = "ErrorLog.txt";
            BasePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            path = Path.Combine(BasePath, TxtFileName);
        }

        public static void Log(string problem)
        {
            errors = new List<string>();
            //takes any errors that are being logged and adds them to a list of erros that will be logged on closing, unless called sooner.
            errors.Add(problem);
        }

        public void OnClosing()
        {
            //if there is a file at the right path, a writer will write to it.
            if (errors != null)
            {
                if (File.Exists(path))
                {
                    using (StreamWriter writer =
                        new StreamWriter(path))
                    {
                        foreach (string line in errors)
                        {
                            writer.WriteLine(line);
                        }
                        writer.Close();
                    }

                }
                else
                {
                    File.Create(path).Dispose();
                    using (StreamWriter writer =
                       new StreamWriter(path))
                    {
                        writer.WriteLine("This is the Error Log:");
                        foreach (string line in errors)
                        {
                            writer.WriteLine(line);
                        }
                        writer.Close();
                    }

                }
            }
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>React + jQuery UI Sortable Example</title>


text:
'use strict'

// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------

const utils = require('../utils')

// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------

/**
 * Creates AST event handlers for require-component-is.
 *
 * @param {RuleContext} context - The rule context.
 * @returns {Object} AST event handlers.
 */
function create (context) {
  return utils.defineTemplateBodyVisitor(context, {
    "VElement[name='component']" (node) {
      if (!utils.hasDirective(node, 'bind', 'is')) {
        context.report({
          node,
          loc: node.loc,
          message: "Expected '<component>' elements to have 'v-bind:is' attribute."
        })
      }
    }
  })
}

// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------

module.exports = {
  create,
  meta: {
    docs: {
      description: 'require `v-bind:is` of `<component>` elements',
      category: 'Best Practices',
      recommended: true
    },
    fixable: false,
    schema: []
  }
}


text:
export {transforms} from './transform';
export default from './transform';


text:
__version__ = '1.0b12'
__author__ = 'Adrian Sampson <adrian@radbox.org>'

import beets.library
Library = beets.library.Library


text:
//enums
int MOVETYPE_NOCLIP_ENUM;
int IN_MOVELEFT;
int IN_MOVERIGHT;
int IN_FORWARD;
int IN_BACK;

inline float GoodRound(float flt) {
	return roundf(flt * 1000000) / 1000000;
}

inline std::string escape_string(std::string str) { //credits to mysql
	std::string::iterator it;
	std::string ret = "";
	for (it = str.begin(); it < str.end(); it++) {
		switch (*it)
		{
		case 0:
			ret.append("\0");
			break;
		case '\n':
			ret.append("\\n");
			break;
		case '\'':
			ret.append("''");
			break;
		case '\0x00':
			ret.append("\\0x00");
			break;
		default:
			ret += *it;
		}
	}
	return ret;
};

inline bool GetNWBool(lua_State* state, const char* str, bool default) {
	LUA->GetField(1, "GetNWBool");
	LUA->Push(1);
	LUA->PushString(str);
	LUA->PushBool(default);
	LUA->Call(3, 1);
	bool bl = LUA->GetBool(-1);
	LUA->Pop();
	return bl;
}

inline void SetNWBool(lua_State* state, const char* str, bool set) {
	LUA->GetField(1, "SetNWBool");
	LUA->Push(1);
	LUA->PushString(str);
	LUA->PushBool(set);
	LUA->Call(3, 0);
}

inline float GetFloat(lua_State* state, int stack, const char * get) {
	LUA->GetField(stack, get);
	LUA->Push(stack);
	LUA->Call(1, 1);
	float flt = LUA->GetNumber(-1);
	LUA->Pop();
	return flt;
}

inline int GetInt(lua_State* state, int stack, const char * get) {
	LUA->GetField(stack, get);
	LUA->Push(stack);
	LUA->Call(1, 1);
	int flt = LUA->GetNumber(-1);
	LUA->Pop();
	return flt;
}

inline bool GetBool(lua_State* state, int stack, const char * get) {
	LUA->GetField(stack, get);
	LUA->Push(stack);
	LUA->Call(1, 1);
	bool flt = LUA->GetBool(-1);
	LUA->Pop();
	return flt;
}

inline const char * GetString(lua_State* state, int stack, const char * get) {
	LUA->GetField(stack, get);
	LUA->Push(stack);
	LUA->Call(1, 1);
	const char * flt = LUA->GetString(-1);
	LUA->Pop();
	return flt;
}

inline bool Cheated(lua_State* state) {
	if (GetNWBool(state, "cheated", false) == true) {
		return true;
	}
	else if (GetInt(state, 1, "GetMoveType") == MOVETYPE_NOCLIP_ENUM) {
		SetNWBool(state, "cheated", true);
		return true;
	}
	return false;
}

class bot
{
public:
	bot() {};
	int reference;
	int index;
	std::chrono::time_point<std::chrono::steady_clock> wait;
};

bot table[10];

int PushRecordTable(lua_State* state) {
	LUA->CheckType(1, GarrysMod::Lua::Type::TABLE); // check if type is table
	LUA->CheckType(2, GarrysMod::Lua::Type::NUMBER); // check if type is table
	int Team = LUA->GetNumber(2);
	LUA->Push(1); // push to make a reference

	table[Team].reference = LUA->ReferenceCreate();
	table[Team].index = 1;

	table[Team].wait = std::chrono::steady_clock::now();
	return 0;
}

int RunBot(lua_State* state) {

	if (!GetBool(state, 1, "Alive")) return 0;

	int Team = GetInt(state, 1, "Team"); // Get team

	if (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - table[Team].wait).count() < 5) { // if time < 5 we dont want the bot to run. See this as a cooldown.
		return 0;
	}

	LUA->ReferencePush(table[Team].reference);
		if (!LUA->IsType(-1, GarrysMod::Lua::Type::TABLE)) {
			LUA->Pop(); // We need to Pop once
			return 0; // We can only continue if type is table
		}
		LUA->PushNumber(table[Team].index); // Push index we want
		LUA->GetTable(-2); // Get index 1 from table
			if (!LUA->IsType(-1, GarrysMod::Lua::Type::TABLE)) {
				LUA->Pop(); //We need to Pop twice
				LUA->Pop();
				return 0; // We can only continue if type is table
			}

			CMoveData * mv = *reinterpret_cast<CMoveData **>(LUA->GetUserdata(2));
			LUA->GetField(-1, "k"); // Get Angles from table[1]
			if (LUA->IsType(-1, GarrysMod::Lua::Type::ANGLE)) {
				int angles = LUA->ReferenceCreate(); //Creates a reference and pops the stack
				LUA->ReferencePush(angles);
				QAngle Angle = **reinterpret_cast<QAngle **>(LUA->GetUserdata(-1));
				mv->m_vecAngles = Angle;
				mv->m_vecViewAngles = Angle;
				LUA->GetField(1, "SetEyeAngles"); // Get function
				LUA->Push(1); // Push player
				LUA->ReferencePush(angles); // Push Angles
				LUA->Call(2, 0); // Call function
				LUA->ReferenceFree(angles);
			}
			LUA->Pop();

			LUA->GetField(-1, "l"); // Get Buttons from table[1]
			if (LUA->IsType(-1, GarrysMod::Lua::Type::NUMBER)) {
				int buttons = LUA->GetNumber(-1); //Creates a reference and pops the stack
				mv->m_flSideMove = 0.0f;
				mv->m_flForwardMove = 0.0f;
				mv->m_nButtons = buttons;
				if (buttons & IN_MOVELEFT) {
					mv->m_flSideMove += -10000.0f;
				}
				if (buttons & IN_MOVERIGHT) {
					mv->m_flSideMove += 10000.0f;
				}
				if (buttons & IN_FORWARD) {
					mv->m_flForwardMove += -10000.0f;
				}
				if (buttons & IN_BACK) {
					mv->m_flForwardMove += 10000.0f;
				}
			}
			LUA->Pop();

			LUA->GetField(-1, "u"); // Get Origin from table[1]
			if (LUA->IsType(-1, GarrysMod::Lua::Type::VECTOR)) {
				mv->SetAbsOrigin(**reinterpret_cast<Vector **>(LUA->GetUserdata(-1)));
			}
			LUA->Pop();

			LUA->GetField(-1, "x"); // Get Velocity from table[1]
			if (LUA->IsType(-1, GarrysMod::Lua::Type::VECTOR)) {
				mv->m_vecVelocity = **reinterpret_cast<Vector **>(LUA->GetUserdata(-1));
			}
			LUA->Pop();
		LUA->Pop(); // Pop table[1] from stack

		++table[Team].index;
	LUA->PushNumber(table[Team].index); // Push index we want
	LUA->GetTable(-2); // Get index 1 from table
	if (!LUA->IsType(-1, GarrysMod::Lua::Type::TABLE)) {
		table[Team].index = 1; // reset table for next botrun
		table[Team].wait = std::chrono::steady_clock::now(); // next botrun is in 5 seconds
	}
	LUA->Pop(); // Pop table from stack

	return 0;
}

#define _pre_format_ "\"1\":{\"Model\":\"%s\",\"Nick\":\"%s\",\"SteamID\":\"%s\"}"
#define _format_ ",\"%u\":{\"k\":\"{%.6g %.6g %.6g}\",\"l\":%u,\"x\":\"[%.6g %.6g %.6g]\",\"u\":\"[%.6g %.6g %.6g]\"}"

class UserTable {
public:
	UserTable() {
		index = 0;
		json = "{";
	}
	void Append(char *AYE) {
		//std::string app(AYE);
		++index;
		json.append(AYE);
	}
	std::string GetJson() {
		std::string copy = json;
		return copy += "}";
	}
	int GetIndex() {
		return index;
	}
	void Reset(lua_State* state) {
		Delete();
		index = 1;
		json = "{";

		//create char
		char modelbuffer[200];

		//format
		std::sprintf(modelbuffer, _pre_format_, escape_string(GetString(state, 1, "GetModel")).c_str(), escape_string(GetString(state, 1, "Nick")).c_str(), GetString(state, 1, "SteamID"));

		//Store data
		Append(modelbuffer);
	}
	void Delete() {
		if (index > 0) {
			json.clear();
			index = 0;
			json = std::string("{");
		}
	}
private:
	int index;
	std::string json;
};

UserTable DataStore[129]; //We store the table index in this. Makes it simple.
float LeaderBoard[10];

int MoveToJSON(lua_State* state) {
	LUA->CheckType(1, GarrysMod::Lua::Type::ENTITY);
	LUA->CheckType(2, GarrysMod::Lua::Type::MOVEDATA);

	if (GetBool(state, 1, "IsBot")) {
		RunBot(state); // "player" is a bot so we can control him.
		return 0;
	}

	//index for array
	int ArrayIndex = GetInt(state, 1, "EntIndex");

	//check teams.
	int Team = GetInt(state, 1, "Team");

	if (Cheated(state) || GetFloat(state, 1, "GetTime") > LeaderBoard[Team] || LeaderBoard[Team] == 0.0f || !GetBool(state, 1, "Alive")) {
		DataStore[ArrayIndex].Delete();
		return 0;
	}

	//table index
	int index = DataStore[ArrayIndex].GetIndex();

	CMoveData * mv = *reinterpret_cast<CMoveData **>(LUA->GetUserdata(2));

	//checks checks checks
	if (index <= 1 || (GetNWBool(state, "Bhop.InStartingZone", false) == true && mv->m_vecVelocity.Length2D() < 25)) {
		DataStore[ArrayIndex].Reset(state);
		return 0; //return since we are most likely not moving.
	}

	//origin/position
	Vector O = mv->GetAbsOrigin();

	//create char
	char buf[250];

	//format
	sprintf(buf, _format_, index, GoodRound(mv->m_vecAngles.x), GoodRound(mv->m_vecAngles.y), GoodRound(mv->m_vecAngles.z), mv->m_nButtons, GoodRound(mv->m_vecVelocity.x), GoodRound(mv->m_vecVelocity.y), GoodRound(mv->m_vecVelocity.z), GoodRound(O.x), GoodRound(O.y), GoodRound(O.z));

	DataStore[ArrayIndex].Append(buf);

	return 0;
}

int GetJson(lua_State* state) {
	int ArrayIndex = GetInt(state, 1, "EntIndex");
	if (DataStore[ArrayIndex].GetIndex() > 0) {
		LUA->PushString(DataStore[ArrayIndex].GetJson().c_str());
		return 1;
	}
	LUA->PushString("{}");
	return 1;
}

int SetLeaderBoardTime(lua_State* state) {
	LUA->CheckType(1, GarrysMod::Lua::Type::NUMBER);
	LUA->CheckType(2, GarrysMod::Lua::Type::NUMBER);
	int Team = LUA->GetNumber(1);
	float MaxTime = LUA->GetNumber(2);
	LeaderBoard[Team] = MaxTime;
	return 0;
}

int ResetJSON(lua_State* state) {
	int ArrayIndex = GetInt(state, 1, "EntIndex");
	DataStore[ArrayIndex].Reset(state);
	return 0;
}

int GetRecordTable(lua_State* state) {
	LUA->CheckType(1, GarrysMod::Lua::Type::NUMBER); // check if type is table
	int Team = LUA->GetNumber(1);

	std::string str = "{\"1\":{\"Model\":\"Unknown\",\"Nick\":\"Unknown\",\"SteamID\":\"Unknown\"}";

	LUA->ReferencePush(table[Team].reference);
	int index = 1;
		LUA->PushNumber(index); // Push index we want
		LUA->GetTable(-2); // Get index 1 from table
		while (LUA->IsType(-1, GarrysMod::Lua::Type::TABLE)) {

			QAngle A;
			Vector O;
			Vector V;
			int B;

			LUA->GetField(-1, "k"); // Get Angles from table[1]
			if (LUA->IsType(-1, GarrysMod::Lua::Type::ANGLE)) {
				A = **reinterpret_cast<QAngle **>(LUA->GetUserdata(-1));
			}
			LUA->Pop();

			LUA->GetField(-1, "l"); // Get Buttons from table[1]
			if (LUA->IsType(-1, GarrysMod::Lua::Type::NUMBER)) {
				B = LUA->GetNumber(-1); //Creates a reference and pops the stack
			}
			LUA->Pop();

			LUA->GetField(-1, "u"); // Get Origin from table[1]
			if (LUA->IsType(-1, GarrysMod::Lua::Type::VECTOR)) {
				O = **reinterpret_cast<Vector **>(LUA->GetUserdata(-1));
			}
			LUA->Pop();

			LUA->GetField(-1, "x"); // Get Velocity from table[1]
			if (LUA->IsType(-1, GarrysMod::Lua::Type::VECTOR)) {
				V = **reinterpret_cast<Vector **>(LUA->GetUserdata(-1));
			}
			LUA->Pop();

			char buf[250];
			++index;
			sprintf(buf, _format_, index, A.x, A.y, A.z, B, V.x, V.y, V.z, O.x, O.y, O.z);
			str.append(buf);

			LUA->Pop(); // Pops index from table
			LUA->PushNumber(index); // Push index we want
			LUA->GetTable(-2); // Get index 1 from table
		}
		LUA->Pop();
	LUA->Pop();
	str.append("}");
	LUA->PushString(str.c_str());
	return 1;
}

GMOD_MODULE_OPEN() {
	LUA->PushSpecial(GarrysMod::Lua::SPECIAL_GLOB);

	LUA->GetField(-1, "hook");

		LUA->GetField(-1, "Add");
		LUA->PushString("PlayerRestart");
		LUA->PushString("RESET_JSON");
		LUA->PushCFunction(ResetJSON);
		LUA->Call(3,0);

		LUA->GetField(-1, "Add");
		LUA->PushString("SetupMove");
		LUA->PushString("C++Recording");
		LUA->PushCFunction(MoveToJSON);
		LUA->PushNumber(-21);
		LUA->Call(4, 0);

	LUA->Pop();

	LUA->PushCFunction(GetJson);
	LUA->SetField(-2, "GetJSON");

	LUA->PushCFunction(PushRecordTable);
	LUA->SetField(-2, "PushRecordTable");

	LUA->PushCFunction(GetRecordTable);
	LUA->SetField(-2, "GetRecordTable");

	LUA->PushCFunction(SetLeaderBoardTime);
	LUA->SetField(-2, "SetLeaderBoardTime");

	LUA->GetField(-1, "MOVETYPE_NOCLIP");
	MOVETYPE_NOCLIP_ENUM = LUA->GetNumber(-1);
	LUA->Pop();

	LUA->GetField(-1, "IN_MOVELEFT");
	IN_MOVELEFT = LUA->GetNumber(-1);
	LUA->Pop();

	LUA->GetField(-1, "IN_MOVERIGHT");
	IN_MOVERIGHT = LUA->GetNumber(-1);
	LUA->Pop();

	LUA->GetField(-1, "IN_FORWARD");
	IN_FORWARD = LUA->GetNumber(-1);
	LUA->Pop();

	LUA->GetField(-1, "IN_BACK");
	IN_BACK = LUA->GetNumber(-1);
	LUA->Pop();

	LUA->Pop();

	return 0;
}

GMOD_MODULE_CLOSE() {
	for (int i = 0; i < 10; i++) {
		LUA->ReferenceFree(table[i].reference); // Get rid of all references.
	}
	return 0;
}