text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_Object2689449295.h"
#include "Mono_Security_U3CPrivateImplementationDetailsU3E_U1892466092.h"
#include "Mono_Security_U3CPrivateImplementationDetailsU3E_U2038352954.h"
#include "Mono_Security_U3CPrivateImplementationDetailsU3E_U2540610921.h"
#include "Mono_Security_U3CPrivateImplementationDetailsU3E_U3672778804.h"
#include "Mono_Security_U3CPrivateImplementationDetailsU3E_U2896841275.h"
#include "Mono_Security_U3CPrivateImplementationDetailsU3E_U2866209745.h"
#include "Mono_Security_U3CPrivateImplementationDetailsU3E_U3672778802.h"
#include "Mono_Security_U3CPrivateImplementationDetailsU3E_U1703410334.h"
#include "Mono_Security_U3CPrivateImplementationDetailsU3E_U1957337331.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// <PrivateImplementationDetails>
struct  U3CPrivateImplementationDetailsU3E_t1486305139  : public Il2CppObject
{
public:

public:
};

struct U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields
{
public:
	// <PrivateImplementationDetails>/$ArrayType$3132 <PrivateImplementationDetails>::$$field-0
	U24ArrayTypeU243132_t1892466093  ___U24U24fieldU2D0_0;
	// <PrivateImplementationDetails>/$ArrayType$256 <PrivateImplementationDetails>::$$field-5
	U24ArrayTypeU24256_t2038352955  ___U24U24fieldU2D5_1;
	// <PrivateImplementationDetails>/$ArrayType$20 <PrivateImplementationDetails>::$$field-6
	U24ArrayTypeU2420_t540610922  ___U24U24fieldU2D6_2;
	// <PrivateImplementationDetails>/$ArrayType$32 <PrivateImplementationDetails>::$$field-7
	U24ArrayTypeU2432_t3672778805  ___U24U24fieldU2D7_3;
	// <PrivateImplementationDetails>/$ArrayType$48 <PrivateImplementationDetails>::$$field-8
	U24ArrayTypeU2448_t896841276  ___U24U24fieldU2D8_4;
	// <PrivateImplementationDetails>/$ArrayType$64 <PrivateImplementationDetails>::$$field-9
	U24ArrayTypeU2464_t2866209746  ___U24U24fieldU2D9_5;
	// <PrivateImplementationDetails>/$ArrayType$64 <PrivateImplementationDetails>::$$field-11
	U24ArrayTypeU2464_t2866209746  ___U24U24fieldU2D11_6;
	// <PrivateImplementationDetails>/$ArrayType$64 <PrivateImplementationDetails>::$$field-12
	U24ArrayTypeU2464_t2866209746  ___U24U24fieldU2D12_7;
	// <PrivateImplementationDetails>/$ArrayType$64 <PrivateImplementationDetails>::$$field-13
	U24ArrayTypeU2464_t2866209746  ___U24U24fieldU2D13_8;
	// <PrivateImplementationDetails>/$ArrayType$12 <PrivateImplementationDetails>::$$field-14
	U24ArrayTypeU2412_t3672778806  ___U24U24fieldU2D14_9;
	// <PrivateImplementationDetails>/$ArrayType$12 <PrivateImplementationDetails>::$$field-15
	U24ArrayTypeU2412_t3672778806  ___U24U24fieldU2D15_10;
	// <PrivateImplementationDetails>/$ArrayType$12 <PrivateImplementationDetails>::$$field-16
	U24ArrayTypeU2412_t3672778806  ___U24U24fieldU2D16_11;
	// <PrivateImplementationDetails>/$ArrayType$16 <PrivateImplementationDetails>::$$field-17
	U24ArrayTypeU2416_t1703410335  ___U24U24fieldU2D17_12;
	// <PrivateImplementationDetails>/$ArrayType$4 <PrivateImplementationDetails>::$$field-21
	U24ArrayTypeU244_t1957337331  ___U24U24fieldU2D21_13;
	// <PrivateImplementationDetails>/$ArrayType$4 <PrivateImplementationDetails>::$$field-22
	U24ArrayTypeU244_t1957337331  ___U24U24fieldU2D22_14;

public:
	inline static int32_t get_offset_of_U24U24fieldU2D0_0() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D0_0)); }
	inline U24ArrayTypeU243132_t1892466093  get_U24U24fieldU2D0_0() const { return ___U24U24fieldU2D0_0; }
	inline U24ArrayTypeU243132_t1892466093 * get_address_of_U24U24fieldU2D0_0() { return &___U24U24fieldU2D0_0; }
	inline void set_U24U24fieldU2D0_0(U24ArrayTypeU243132_t1892466093  value)
	{
		___U24U24fieldU2D0_0 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D5_1() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D5_1)); }
	inline U24ArrayTypeU24256_t2038352955  get_U24U24fieldU2D5_1() const { return ___U24U24fieldU2D5_1; }
	inline U24ArrayTypeU24256_t2038352955 * get_address_of_U24U24fieldU2D5_1() { return &___U24U24fieldU2D5_1; }
	inline void set_U24U24fieldU2D5_1(U24ArrayTypeU24256_t2038352955  value)
	{
		___U24U24fieldU2D5_1 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D6_2() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D6_2)); }
	inline U24ArrayTypeU2420_t540610922  get_U24U24fieldU2D6_2() const { return ___U24U24fieldU2D6_2; }
	inline U24ArrayTypeU2420_t540610922 * get_address_of_U24U24fieldU2D6_2() { return &___U24U24fieldU2D6_2; }
	inline void set_U24U24fieldU2D6_2(U24ArrayTypeU2420_t540610922  value)
	{
		___U24U24fieldU2D6_2 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D7_3() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D7_3)); }
	inline U24ArrayTypeU2432_t3672778805  get_U24U24fieldU2D7_3() const { return ___U24U24fieldU2D7_3; }
	inline U24ArrayTypeU2432_t3672778805 * get_address_of_U24U24fieldU2D7_3() { return &___U24U24fieldU2D7_3; }
	inline void set_U24U24fieldU2D7_3(U24ArrayTypeU2432_t3672778805  value)
	{
		___U24U24fieldU2D7_3 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D8_4() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D8_4)); }
	inline U24ArrayTypeU2448_t896841276  get_U24U24fieldU2D8_4() const { return ___U24U24fieldU2D8_4; }
	inline U24ArrayTypeU2448_t896841276 * get_address_of_U24U24fieldU2D8_4() { return &___U24U24fieldU2D8_4; }
	inline void set_U24U24fieldU2D8_4(U24ArrayTypeU2448_t896841276  value)
	{
		___U24U24fieldU2D8_4 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D9_5() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D9_5)); }
	inline U24ArrayTypeU2464_t2866209746  get_U24U24fieldU2D9_5() const { return ___U24U24fieldU2D9_5; }
	inline U24ArrayTypeU2464_t2866209746 * get_address_of_U24U24fieldU2D9_5() { return &___U24U24fieldU2D9_5; }
	inline void set_U24U24fieldU2D9_5(U24ArrayTypeU2464_t2866209746  value)
	{
		___U24U24fieldU2D9_5 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D11_6() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D11_6)); }
	inline U24ArrayTypeU2464_t2866209746  get_U24U24fieldU2D11_6() const { return ___U24U24fieldU2D11_6; }
	inline U24ArrayTypeU2464_t2866209746 * get_address_of_U24U24fieldU2D11_6() { return &___U24U24fieldU2D11_6; }
	inline void set_U24U24fieldU2D11_6(U24ArrayTypeU2464_t2866209746  value)
	{
		___U24U24fieldU2D11_6 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D12_7() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D12_7)); }
	inline U24ArrayTypeU2464_t2866209746  get_U24U24fieldU2D12_7() const { return ___U24U24fieldU2D12_7; }
	inline U24ArrayTypeU2464_t2866209746 * get_address_of_U24U24fieldU2D12_7() { return &___U24U24fieldU2D12_7; }
	inline void set_U24U24fieldU2D12_7(U24ArrayTypeU2464_t2866209746  value)
	{
		___U24U24fieldU2D12_7 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D13_8() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D13_8)); }
	inline U24ArrayTypeU2464_t2866209746  get_U24U24fieldU2D13_8() const { return ___U24U24fieldU2D13_8; }
	inline U24ArrayTypeU2464_t2866209746 * get_address_of_U24U24fieldU2D13_8() { return &___U24U24fieldU2D13_8; }
	inline void set_U24U24fieldU2D13_8(U24ArrayTypeU2464_t2866209746  value)
	{
		___U24U24fieldU2D13_8 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D14_9() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D14_9)); }
	inline U24ArrayTypeU2412_t3672778806  get_U24U24fieldU2D14_9() const { return ___U24U24fieldU2D14_9; }
	inline U24ArrayTypeU2412_t3672778806 * get_address_of_U24U24fieldU2D14_9() { return &___U24U24fieldU2D14_9; }
	inline void set_U24U24fieldU2D14_9(U24ArrayTypeU2412_t3672778806  value)
	{
		___U24U24fieldU2D14_9 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D15_10() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D15_10)); }
	inline U24ArrayTypeU2412_t3672778806  get_U24U24fieldU2D15_10() const { return ___U24U24fieldU2D15_10; }
	inline U24ArrayTypeU2412_t3672778806 * get_address_of_U24U24fieldU2D15_10() { return &___U24U24fieldU2D15_10; }
	inline void set_U24U24fieldU2D15_10(U24ArrayTypeU2412_t3672778806  value)
	{
		___U24U24fieldU2D15_10 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D16_11() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D16_11)); }
	inline U24ArrayTypeU2412_t3672778806  get_U24U24fieldU2D16_11() const { return ___U24U24fieldU2D16_11; }
	inline U24ArrayTypeU2412_t3672778806 * get_address_of_U24U24fieldU2D16_11() { return &___U24U24fieldU2D16_11; }
	inline void set_U24U24fieldU2D16_11(U24ArrayTypeU2412_t3672778806  value)
	{
		___U24U24fieldU2D16_11 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D17_12() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D17_12)); }
	inline U24ArrayTypeU2416_t1703410335  get_U24U24fieldU2D17_12() const { return ___U24U24fieldU2D17_12; }
	inline U24ArrayTypeU2416_t1703410335 * get_address_of_U24U24fieldU2D17_12() { return &___U24U24fieldU2D17_12; }
	inline void set_U24U24fieldU2D17_12(U24ArrayTypeU2416_t1703410335  value)
	{
		___U24U24fieldU2D17_12 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D21_13() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D21_13)); }
	inline U24ArrayTypeU244_t1957337331  get_U24U24fieldU2D21_13() const { return ___U24U24fieldU2D21_13; }
	inline U24ArrayTypeU244_t1957337331 * get_address_of_U24U24fieldU2D21_13() { return &___U24U24fieldU2D21_13; }
	inline void set_U24U24fieldU2D21_13(U24ArrayTypeU244_t1957337331  value)
	{
		___U24U24fieldU2D21_13 = value;
	}

	inline static int32_t get_offset_of_U24U24fieldU2D22_14() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t1486305139_StaticFields, ___U24U24fieldU2D22_14)); }
	inline U24ArrayTypeU244_t1957337331  get_U24U24fieldU2D22_14() const { return ___U24U24fieldU2D22_14; }
	inline U24ArrayTypeU244_t1957337331 * get_address_of_U24U24fieldU2D22_14() { return &___U24U24fieldU2D22_14; }
	inline void set_U24U24fieldU2D22_14(U24ArrayTypeU244_t1957337331  value)
	{
		___U24U24fieldU2D22_14 = value;
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif

repository: HackingForGood/GoogleyEyes

repo_name: HackingForGood/GoogleyEyes

extension: h


text:
package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
	"strconv"
)

var INF int = 1 << 31

type pair struct {
	total int
	next  int
}

func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
}

type PriorityQueue []pair

func (pq PriorityQueue) Len() int { return len(pq) }

func (pq PriorityQueue) Less(i, j int) bool {
	return pq[i].total <= pq[j].total
}

func (pq *PriorityQueue) Push(x interface{}) {
	item := x.(pair)
	*pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

type edge struct {
	to   int
	cost int
}

var sc = bufio.NewScanner(os.Stdin)

func next() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i

}

func main() {
	sc.Split(bufio.ScanWords)

	var V, E, r int
	fmt.Scanf("%d %d %d", &V, &E, &r)

	edges := make([][]*edge, V)
	dist := make([]int, V)
	done := make([]bool, V)
	queue := make(PriorityQueue, 0, V)

	for i := 0; i < E; i++ {
		var s, t, cost int
		s, t, cost = next(), next(), next()
		edges[s] = append(edges[s], &edge{to: t, cost: cost})

	}

	for i := 0; i < V; i++ {
		dist[i] = INF
	}

	heap.Push(&queue, pair{total: 0, next: r})

	for queue.Len() > 0 {
		item := heap.Pop(&queue).(pair)
		if done[item.next] {
			continue
		}
		done[item.next] = true
		dist[item.next] = item.total

		for _, edge := range edges[item.next] {
			heap.Push(&queue, pair{
				total: edge.cost + item.total,
				next:  edge.to,
			})

		}

	}

	for _, node := range dist {
		if node >= INF {
			fmt.Printf("INF\n")
		} else {
			fmt.Printf("%d\n", node)
		}
	}

}

license: MIT

license_type: permissive

branch_name: refs/heads/master

extension: go


text:
DEPENDS = "python-native"
PACKAGES = "${PN}"
PACKAGE_ARCH = "all"
MODULE = "pyvalerie/src"
require valerie.inc
PLUGINDIR = "/usr/lib/enigma2/python/Plugins/Extensions/ProjectValerieSync"

do_compile() {
	python -O -m compileall ${S}
}

do_install() {
	install -d ${D}${PLUGINDIR}
	install -m 644 *.py* ${D}${PLUGINDIR}
	install -d ${D}${PLUGINDIR}/cache
	install -d ${D}${PLUGINDIR}/db
	install -d ${D}${PLUGINDIR}/db/episodes
	install -d ${D}${PLUGINDIR}/dl
}

repository: libo/openembedded

repo_name: libo/openembedded

branch_name: HEAD

extension: bb


text:
// Code generated by MockGen. DO NOT EDIT.
// Source: testutil/io_interfaces.go

// Package mocks is a generated GoMock package.
package mocks

import (
	reflect "reflect"

	gomock "github.com/golang/mock/gomock"
)

// MockReadCloser is a mock of ReadCloser interface.
type MockReadCloser struct {
	ctrl     *gomock.Controller
	recorder *MockReadCloserMockRecorder
}

// MockReadCloserMockRecorder is the mock recorder for MockReadCloser.
type MockReadCloserMockRecorder struct {
	mock *MockReadCloser
}

// NewMockReadCloser creates a new mock instance.
func NewMockReadCloser(ctrl *gomock.Controller) *MockReadCloser {
	mock := &MockReadCloser{ctrl: ctrl}
	mock.recorder = &MockReadCloserMockRecorder{mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockReadCloser) EXPECT() *MockReadCloserMockRecorder {
	return m.recorder
}

// Close mocks base method.
func (m *MockReadCloser) Close() error {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Close")
	ret0, _ := ret[0].(error)
	return ret0
}

// Close indicates an expected call of Close.
func (mr *MockReadCloserMockRecorder) Close() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockReadCloser)(nil).Close))
}

// Read mocks base method.
func (m *MockReadCloser) Read(p []byte) (int, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Read", p)
	ret0, _ := ret[0].(int)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

// Read indicates an expected call of Read.
func (mr *MockReadCloserMockRecorder) Read(p interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockReadCloser)(nil).Read), p)
}

// MockFileReader is a mock of FileReader interface.
type MockFileReader struct {
	ctrl     *gomock.Controller
	recorder *MockFileReaderMockRecorder
}

// MockFileReaderMockRecorder is the mock recorder for MockFileReader.
type MockFileReaderMockRecorder struct {
	mock *MockFileReader
}

// NewMockFileReader creates a new mock instance.
func NewMockFileReader(ctrl *gomock.Controller) *MockFileReader {
	mock := &MockFileReader{ctrl: ctrl}
	mock.recorder = &MockFileReaderMockRecorder{mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockFileReader) EXPECT() *MockFileReaderMockRecorder {
	return m.recorder
}

// Close mocks base method.
func (m *MockFileReader) Close() error {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Close")
	ret0, _ := ret[0].(error)
	return ret0
}

// Close indicates an expected call of Close.
func (mr *MockFileReaderMockRecorder) Close() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockFileReader)(nil).Close))
}

// Fd mocks base method.
func (m *MockFileReader) Fd() uintptr {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Fd")
	ret0, _ := ret[0].(uintptr)
	return ret0
}

// Fd indicates an expected call of Fd.
func (mr *MockFileReaderMockRecorder) Fd() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fd", reflect.TypeOf((*MockFileReader)(nil).Fd))
}

// Read mocks base method.
func (m *MockFileReader) Read(p []byte) (int, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Read", p)
	ret0, _ := ret[0].(int)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

// Read indicates an expected call of Read.
func (mr *MockFileReaderMockRecorder) Read(p interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockFileReader)(nil).Read), p)
}

// MockFileWriter is a mock of FileWriter interface.
type MockFileWriter struct {
	ctrl     *gomock.Controller
	recorder *MockFileWriterMockRecorder
}

// MockFileWriterMockRecorder is the mock recorder for MockFileWriter.
type MockFileWriterMockRecorder struct {
	mock *MockFileWriter
}

// NewMockFileWriter creates a new mock instance.
func NewMockFileWriter(ctrl *gomock.Controller) *MockFileWriter {
	mock := &MockFileWriter{ctrl: ctrl}
	mock.recorder = &MockFileWriterMockRecorder{mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockFileWriter) EXPECT() *MockFileWriterMockRecorder {
	return m.recorder
}

// Fd mocks base method.
func (m *MockFileWriter) Fd() uintptr {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Fd")
	ret0, _ := ret[0].(uintptr)
	return ret0
}

// Fd indicates an expected call of Fd.
func (mr *MockFileWriterMockRecorder) Fd() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Fd", reflect.TypeOf((*MockFileWriter)(nil).Fd))
}

// Write mocks base method.
func (m *MockFileWriter) Write(p []byte) (int, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Write", p)
	ret0, _ := ret[0].(int)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

// Write indicates an expected call of Write.
func (mr *MockFileWriterMockRecorder) Write(p interface{}) *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockFileWriter)(nil).Write), p)
}

repository: furkanefe-oss/kit

repo_name: furkanefe-oss/kit


text:
@INPROCEEDINGS{8241590,
  author={S. {Mujumdar} and N. {Gupta} and A. {Jain} and S. {Mehta}},
  booktitle={2017 IEEE International Symposium on Multimedia (ISM)},
  title={Coherent Visual Description of Textual Instructions},
  year={2017},
  volume={},
  number={},
  pages={122-129},}

repository: jabhinav/academic-kickstart

repo_name: jabhinav/academic-kickstart

extension: bib


text:
package main

import (
	"testing"
)

func TestGormTableName(t *testing.T) {
	var testdata = []struct {
		in  string
		out string
	}{
		{"events", "Event"},
		{"post_comments", "PostComment"},
	}

	for _, td := range testdata {
		s := gormTableName(td.in)

		if s != td.out {
			t.Fatalf("Table name does not match. expect: %s, actual: %s", td.out, s)
		}
	}
}

func TestGormColumnName(t *testing.T) {
	var testdata = []struct {
		in  string
		out string
	}{
		{"description", "Description"},
		{"user_id", "UserID"},
		{"facebook_uid", "FacebookUID"},
		{"candidacy", "Candidacy"},
		{"video_id", "VideoID"},
		{"image_url", "ImageURL"},
		{"curl_name", "CurlName"},
	}

	for _, td := range testdata {
		s := gormColumnName(td.in)

		if s != td.out {
			t.Fatalf("Field name does not match. expect: %s, actual: %s", td.out, s)
		}
	}
}

gha_license_id: MIT


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/system/input_device_settings/input_device_tracker.h"

#include "ash/constants/ash_features.h"
#include "ash/public/mojom/input_device_settings.mojom.h"
#include "ash/session/session_controller_impl.h"
#include "ash/shell.h"
#include "ash/system/input_device_settings/input_device_settings_pref_names.h"
#include "ash/test/ash_test_base.h"
#include "base/containers/contains.h"
#include "base/strings/string_piece_forward.h"
#include "base/test/scoped_feature_list.h"
#include "components/account_id/account_id.h"
#include "components/prefs/pref_service.h"

namespace ash {

using InputDeviceCategory = InputDeviceTracker::InputDeviceCategory;

namespace {
const base::StringPiece kDeviceKey1 = "5555:1111";
const base::StringPiece kDeviceKey2 = "3333:22aa";
const base::StringPiece kDeviceKey3 = "aa22:eeff";

constexpr char kUserEmail1[] = "email1@peripherals";
constexpr char kUserEmail2[] = "email2@peripherals";
}  // namespace

class InputDeviceTrackerTest
    : public AshTestBase,
      public ::testing::WithParamInterface<
          std::pair<InputDeviceCategory, base::StringPiece>> {
 public:
  InputDeviceTrackerTest() = default;
  InputDeviceTrackerTest(const InputDeviceTrackerTest&) = delete;
  InputDeviceTrackerTest& operator=(const InputDeviceTrackerTest&) = delete;
  ~InputDeviceTrackerTest() override = default;

  // testing::Test:
  void SetUp() override {
    feature_list_.InitAndDisableFeature(features::kInputDeviceSettingsSplit);
    AshTestBase::SetUp();
    std::tie(category_, pref_path_) = GetParam();
    tracker_ = std::make_unique<InputDeviceTracker>();
    SimulateUserLogin(GetAccountId(kUserEmail1));
  }

  void TearDown() override {
    tracker_.reset();
    AshTestBase::TearDown();
  }

  AccountId GetAccountId(base::StringPiece email) {
    return AccountId::FromUserEmail(std::string(email));
  }

  void CheckObservedDevicesList(
      std::vector<base::StringPiece> expected_devices) {
    pref_service_ = Shell::Get()->session_controller()->GetActivePrefService();
    const auto& list = pref_service_->GetList(pref_path_);
    EXPECT_EQ(expected_devices.size(), list.size());

    for (const auto& device : expected_devices) {
      EXPECT_TRUE(base::Contains(list, device));
    }
  }

  void CallOnDeviceConnected(base::StringPiece device_key) {
    switch (category_) {
      case InputDeviceCategory::kKeyboard: {
        mojom::Keyboard keyboard;
        keyboard.device_key = std::string(device_key);
        tracker_->OnKeyboardConnected(keyboard);
        break;
      }
      case InputDeviceCategory::kMouse: {
        mojom::Mouse mouse;
        mouse.device_key = std::string(device_key);
        tracker_->OnMouseConnected(mouse);
        break;
      }
      case InputDeviceCategory::kTouchpad: {
        mojom::Touchpad touchpad;
        touchpad.device_key = std::string(device_key);
        tracker_->OnTouchpadConnected(touchpad);
        break;
      }
      case InputDeviceCategory::kPointingStick:
        mojom::PointingStick pointing_stick;
        pointing_stick.device_key = std::string(device_key);
        tracker_->OnPointingStickConnected(pointing_stick);
        break;
    }
  }

 protected:
  base::test::ScopedFeatureList feature_list_;
  std::unique_ptr<InputDeviceTracker> tracker_;
  raw_ptr<PrefService, DanglingUntriaged | ExperimentalAsh> pref_service_;

  InputDeviceCategory category_;
  base::StringPiece pref_path_;
};

INSTANTIATE_TEST_SUITE_P(
    ,
    InputDeviceTrackerTest,
    testing::ValuesIn(
        std::vector<std::pair<InputDeviceCategory, base::StringPiece>>{
            {InputDeviceCategory::kKeyboard,
             prefs::kKeyboardObservedDevicesPref},
            {InputDeviceCategory::kMouse, prefs::kMouseObservedDevicesPref},
            {InputDeviceCategory::kTouchpad,
             prefs::kTouchpadObservedDevicesPref},
            {InputDeviceCategory::kPointingStick,
             prefs::kPointingStickObservedDevicesPref}}));

TEST_P(InputDeviceTrackerTest, RecordDevices) {
  CallOnDeviceConnected(kDeviceKey1);
  CallOnDeviceConnected(kDeviceKey2);
  CallOnDeviceConnected(kDeviceKey3);
  CheckObservedDevicesList({kDeviceKey1, kDeviceKey2, kDeviceKey3});
}

TEST_P(InputDeviceTrackerTest, RecordDuplicateDevices) {
  CallOnDeviceConnected(kDeviceKey1);
  CallOnDeviceConnected(kDeviceKey2);
  CallOnDeviceConnected(kDeviceKey3);

  CheckObservedDevicesList({kDeviceKey1, kDeviceKey2, kDeviceKey3});

  CallOnDeviceConnected(kDeviceKey1);
  CallOnDeviceConnected(kDeviceKey2);
  CallOnDeviceConnected(kDeviceKey3);

  CheckObservedDevicesList({kDeviceKey1, kDeviceKey2, kDeviceKey3});
}

TEST_P(InputDeviceTrackerTest, RecordDevicesTwoUsers) {
  CallOnDeviceConnected(kDeviceKey1);
  CallOnDeviceConnected(kDeviceKey2);
  CallOnDeviceConnected(kDeviceKey3);

  CheckObservedDevicesList({kDeviceKey1, kDeviceKey2, kDeviceKey3});

  // Switch account
  SimulateUserLogin(GetAccountId(kUserEmail2));
  CheckObservedDevicesList({});

  CallOnDeviceConnected(kDeviceKey1);
  CheckObservedDevicesList({kDeviceKey1});

  CallOnDeviceConnected(kDeviceKey2);
  CheckObservedDevicesList({kDeviceKey1, kDeviceKey2});

  CallOnDeviceConnected(kDeviceKey3);
  CheckObservedDevicesList({kDeviceKey1, kDeviceKey2, kDeviceKey3});
}

TEST_P(InputDeviceTrackerTest, WasDevicePreviouslyConnected) {
  EXPECT_FALSE(tracker_->WasDevicePreviouslyConnected(category_, kDeviceKey1));
  CallOnDeviceConnected(kDeviceKey1);
  EXPECT_TRUE(tracker_->WasDevicePreviouslyConnected(category_, kDeviceKey1));
}

}  // namespace ash

repository: chromium/chromium

repo_name: chromium/chromium

branch_name: refs/heads/main

extension: cc


text:
include ${PN}.inc

SRC_URI = "${HANDHELDS_CVS};tag=${TAG};module=opie/core/applets/vtapplet \
           ${HANDHELDS_CVS};tag=${TAG};module=opie/apps"

repository: Terentyev/familiar-linux

repo_name: Terentyev/familiar-linux


text:
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: optics_db_info.proto

package cisco_ios_xr_controller_optics_oper_optics_oper_optics_ports_optics_port_optics_db_info

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package

//  Optics DB Info
type OpticsDbInfo_KEYS struct {
	Name                 string   `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *OpticsDbInfo_KEYS) Reset()         { *m = OpticsDbInfo_KEYS{} }
func (m *OpticsDbInfo_KEYS) String() string { return proto.CompactTextString(m) }
func (*OpticsDbInfo_KEYS) ProtoMessage()    {}
func (*OpticsDbInfo_KEYS) Descriptor() ([]byte, []int) {
	return fileDescriptor_optics_db_info_32eccb062a78f912, []int{0}
}
func (m *OpticsDbInfo_KEYS) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_OpticsDbInfo_KEYS.Unmarshal(m, b)
}
func (m *OpticsDbInfo_KEYS) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_OpticsDbInfo_KEYS.Marshal(b, m, deterministic)
}
func (dst *OpticsDbInfo_KEYS) XXX_Merge(src proto.Message) {
	xxx_messageInfo_OpticsDbInfo_KEYS.Merge(dst, src)
}
func (m *OpticsDbInfo_KEYS) XXX_Size() int {
	return xxx_messageInfo_OpticsDbInfo_KEYS.Size(m)
}
func (m *OpticsDbInfo_KEYS) XXX_DiscardUnknown() {
	xxx_messageInfo_OpticsDbInfo_KEYS.DiscardUnknown(m)
}

var xxx_messageInfo_OpticsDbInfo_KEYS proto.InternalMessageInfo

func (m *OpticsDbInfo_KEYS) GetName() string {
	if m != nil {
		return m.Name
	}
	return ""
}

type OpticsDbInfo struct {
	// Transport Admin State
	TransportAdminState string `protobuf:"bytes,50,opt,name=transport_admin_state,json=transportAdminState,proto3" json:"transport_admin_state,omitempty"`
	// Optics controller state: Up, Down or Administratively Down
	ControllerState string `protobuf:"bytes,51,opt,name=controller_state,json=controllerState,proto3" json:"controller_state,omitempty"`
	// Network SRLG information
	NetworkSrlgInfo      *OpticsEdmNetworkSrlgInfo `protobuf:"bytes,52,opt,name=network_srlg_info,json=networkSrlgInfo,proto3" json:"network_srlg_info,omitempty"`
	XXX_NoUnkeyedLiteral struct{}                  `json:"-"`
	XXX_unrecognized     []byte                    `json:"-"`
	XXX_sizecache        int32                     `json:"-"`
}

func (m *OpticsDbInfo) Reset()         { *m = OpticsDbInfo{} }
func (m *OpticsDbInfo) String() string { return proto.CompactTextString(m) }
func (*OpticsDbInfo) ProtoMessage()    {}
func (*OpticsDbInfo) Descriptor() ([]byte, []int) {
	return fileDescriptor_optics_db_info_32eccb062a78f912, []int{1}
}
func (m *OpticsDbInfo) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_OpticsDbInfo.Unmarshal(m, b)
}
func (m *OpticsDbInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_OpticsDbInfo.Marshal(b, m, deterministic)
}
func (dst *OpticsDbInfo) XXX_Merge(src proto.Message) {
	xxx_messageInfo_OpticsDbInfo.Merge(dst, src)
}
func (m *OpticsDbInfo) XXX_Size() int {
	return xxx_messageInfo_OpticsDbInfo.Size(m)
}
func (m *OpticsDbInfo) XXX_DiscardUnknown() {
	xxx_messageInfo_OpticsDbInfo.DiscardUnknown(m)
}

var xxx_messageInfo_OpticsDbInfo proto.InternalMessageInfo

func (m *OpticsDbInfo) GetTransportAdminState() string {
	if m != nil {
		return m.TransportAdminState
	}
	return ""
}

func (m *OpticsDbInfo) GetControllerState() string {
	if m != nil {
		return m.ControllerState
	}
	return ""
}

func (m *OpticsDbInfo) GetNetworkSrlgInfo() *OpticsEdmNetworkSrlgInfo {
	if m != nil {
		return m.NetworkSrlgInfo
	}
	return nil
}

// Network SRLG Information
type OpticsEdmNetworkSrlgStructure struct {
	// Array to maintain set number
	SetNumber uint32 `protobuf:"varint,1,opt,name=set_number,json=setNumber,proto3" json:"set_number,omitempty"`
	// Network Srlg
	NetworkSrlg          []uint32 `protobuf:"varint,2,rep,packed,name=network_srlg,json=networkSrlg,proto3" json:"network_srlg,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *OpticsEdmNetworkSrlgStructure) Reset()         { *m = OpticsEdmNetworkSrlgStructure{} }
func (m *OpticsEdmNetworkSrlgStructure) String() string { return proto.CompactTextString(m) }
func (*OpticsEdmNetworkSrlgStructure) ProtoMessage()    {}
func (*OpticsEdmNetworkSrlgStructure) Descriptor() ([]byte, []int) {
	return fileDescriptor_optics_db_info_32eccb062a78f912, []int{2}
}
func (m *OpticsEdmNetworkSrlgStructure) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_OpticsEdmNetworkSrlgStructure.Unmarshal(m, b)
}
func (m *OpticsEdmNetworkSrlgStructure) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_OpticsEdmNetworkSrlgStructure.Marshal(b, m, deterministic)
}
func (dst *OpticsEdmNetworkSrlgStructure) XXX_Merge(src proto.Message) {
	xxx_messageInfo_OpticsEdmNetworkSrlgStructure.Merge(dst, src)
}
func (m *OpticsEdmNetworkSrlgStructure) XXX_Size() int {
	return xxx_messageInfo_OpticsEdmNetworkSrlgStructure.Size(m)
}
func (m *OpticsEdmNetworkSrlgStructure) XXX_DiscardUnknown() {
	xxx_messageInfo_OpticsEdmNetworkSrlgStructure.DiscardUnknown(m)
}

var xxx_messageInfo_OpticsEdmNetworkSrlgStructure proto.InternalMessageInfo

func (m *OpticsEdmNetworkSrlgStructure) GetSetNumber() uint32 {
	if m != nil {
		return m.SetNumber
	}
	return 0
}

func (m *OpticsEdmNetworkSrlgStructure) GetNetworkSrlg() []uint32 {
	if m != nil {
		return m.NetworkSrlg
	}
	return nil
}

// Network SRLG Information Array
type OpticsEdmNetworkSrlgInfo struct {
	// Network Srlg Array
	NetworkSrlgArray     []*OpticsEdmNetworkSrlgStructure `protobuf:"bytes,1,rep,name=network_srlg_array,json=networkSrlgArray,proto3" json:"network_srlg_array,omitempty"`
	XXX_NoUnkeyedLiteral struct{}                         `json:"-"`
	XXX_unrecognized     []byte                           `json:"-"`
	XXX_sizecache        int32                            `json:"-"`
}

func (m *OpticsEdmNetworkSrlgInfo) Reset()         { *m = OpticsEdmNetworkSrlgInfo{} }
func (m *OpticsEdmNetworkSrlgInfo) String() string { return proto.CompactTextString(m) }
func (*OpticsEdmNetworkSrlgInfo) ProtoMessage()    {}
func (*OpticsEdmNetworkSrlgInfo) Descriptor() ([]byte, []int) {
	return fileDescriptor_optics_db_info_32eccb062a78f912, []int{3}
}
func (m *OpticsEdmNetworkSrlgInfo) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_OpticsEdmNetworkSrlgInfo.Unmarshal(m, b)
}
func (m *OpticsEdmNetworkSrlgInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_OpticsEdmNetworkSrlgInfo.Marshal(b, m, deterministic)
}
func (dst *OpticsEdmNetworkSrlgInfo) XXX_Merge(src proto.Message) {
	xxx_messageInfo_OpticsEdmNetworkSrlgInfo.Merge(dst, src)
}
func (m *OpticsEdmNetworkSrlgInfo) XXX_Size() int {
	return xxx_messageInfo_OpticsEdmNetworkSrlgInfo.Size(m)
}
func (m *OpticsEdmNetworkSrlgInfo) XXX_DiscardUnknown() {
	xxx_messageInfo_OpticsEdmNetworkSrlgInfo.DiscardUnknown(m)
}

var xxx_messageInfo_OpticsEdmNetworkSrlgInfo proto.InternalMessageInfo

func (m *OpticsEdmNetworkSrlgInfo) GetNetworkSrlgArray() []*OpticsEdmNetworkSrlgStructure {
	if m != nil {
		return m.NetworkSrlgArray
	}
	return nil
}

func init() {
	proto.RegisterType((*OpticsDbInfo_KEYS)(nil), "cisco_ios_xr_controller_optics_oper.optics_oper.optics_ports.optics_port.optics_db_info.optics_db_info_KEYS")
	proto.RegisterType((*OpticsDbInfo)(nil), "cisco_ios_xr_controller_optics_oper.optics_oper.optics_ports.optics_port.optics_db_info.optics_db_info")
	proto.RegisterType((*OpticsEdmNetworkSrlgStructure)(nil), "cisco_ios_xr_controller_optics_oper.optics_oper.optics_ports.optics_port.optics_db_info.optics_edm_network_srlg_structure")
	proto.RegisterType((*OpticsEdmNetworkSrlgInfo)(nil), "cisco_ios_xr_controller_optics_oper.optics_oper.optics_ports.optics_port.optics_db_info.optics_edm_network_srlg_info")
}

func init() {
	proto.RegisterFile("optics_db_info.proto", fileDescriptor_optics_db_info_32eccb062a78f912)
}

var fileDescriptor_optics_db_info_32eccb062a78f912 = []byte{
	// 321 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xbc, 0x52, 0x3d, 0x4e, 0xf3, 0x40,
	0x10, 0xd5, 0x26, 0x9f, 0x3e, 0x29, 0x13, 0x42, 0xc2, 0x06, 0x24, 0x17, 0x20, 0x39, 0xa9, 0x9c,
	0xc6, 0x85, 0xc3, 0x05, 0x52, 0x50, 0x20, 0x24, 0x0a, 0xa7, 0x40, 0x54, 0xab, 0x8d, 0xbd, 0x44,
	0x16, 0xf6, 0xae, 0x35, 0x3b, 0x16, 0x3f, 0xd7, 0xe0, 0x04, 0x74, 0x5c, 0x85, 0x5b, 0x21, 0x6f,
	0x42, 0xb0, 0xc5, 0x4f, 0x07, 0xdd, 0xce, 0x9b, 0x37, 0xf3, 0xde, 0x3c, 0x2d, 0x1c, 0x9a, 0x92,
	0xb2, 0xc4, 0x8a, 0x74, 0x25, 0x32, 0x7d, 0x63, 0xc2, 0x12, 0x0d, 0x19, 0x7e, 0x95, 0x64, 0x36,
	0x31, 0x22, 0x33, 0x56, 0xdc, 0xa3, 0x48, 0x8c, 0x26, 0x34, 0x79, 0xae, 0x50, 0x6c, 0xd9, 0xa6,
	0x54, 0x18, 0x7e, 0xf1, 0x2e, 0x0d, 0x92, 0x6d, 0x16, 0x61, 0x7b, 0xfd, 0x74, 0x06, 0xe3, 0x36,
	0x22, 0x2e, 0xce, 0xae, 0x97, 0x9c, 0xc3, 0x3f, 0x2d, 0x0b, 0xe5, 0x31, 0x9f, 0x05, 0xbd, 0xd8,
	0xbd, 0xa7, 0x4f, 0x1d, 0xd8, 0x6f, 0x73, 0x79, 0x04, 0x47, 0x84, 0x52, 0xdb, 0x7a, 0xb3, 0x90,
	0x69, 0x91, 0x69, 0x61, 0x49, 0x92, 0xf2, 0x22, 0x37, 0x37, 0xde, 0x35, 0x17, 0x75, 0x6f, 0x59,
	0xb7, 0xf8, 0x0c, 0x46, 0x0d, 0xff, 0x1b, 0xfa, 0xdc, 0xd1, 0x87, 0x1f, 0xf8, 0x86, 0xfa, 0xcc,
	0xe0, 0x40, 0x2b, 0xba, 0x33, 0x78, 0x2b, 0x2c, 0xe6, 0x6b, 0x27, 0xea, 0x9d, 0xfa, 0x2c, 0xe8,
	0x47, 0x55, 0xf8, 0x4b, 0x91, 0xbc, 0x97, 0x2a, 0x2d, 0xc4, 0x27, 0xf1, 0x78, 0xb8, 0x85, 0x96,
	0x98, 0xaf, 0xcf, 0xeb, 0x00, 0x15, 0x4c, 0xbe, 0x1b, 0xb0, 0x84, 0x55, 0x42, 0x15, 0x2a, 0x7e,
	0x02, 0x60, 0x15, 0x09, 0x5d, 0x15, 0x2b, 0x85, 0x2e, 0xd4, 0x41, 0xdc, 0xb3, 0x8a, 0x2e, 0x1d,
	0xc0, 0x27, 0xb0, 0xd7, 0x1c, 0xf4, 0x3a, 0x7e, 0x37, 0x18, 0xc4, 0xfd, 0x86, 0xd4, 0xf4, 0x95,
	0xc1, 0xf1, 0x4f, 0xc6, 0xf8, 0x0b, 0x03, 0xde, 0x42, 0x25, 0xa2, 0x7c, 0xf0, 0x98, 0xdf, 0x0d,
	0xfa, 0xd1, 0xe3, 0x9f, 0x87, 0xb5, 0xbb, 0x3d, 0x1e, 0x35, 0xce, 0x58, 0xd4, 0x9e, 0x56, 0xff,
	0xdd, 0x9f, 0x9e, 0xbf, 0x05, 0x00, 0x00, 0xff, 0xff, 0x18, 0x67, 0xf5, 0x59, 0xeb, 0x02, 0x00,
	0x00,
}

repository: nleiva/telemetry-proto

repo_name: nleiva/telemetry-proto


text:
package servicefoundation

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestLoggerImpl_GetLogger_DebugLevel(t *testing.T) {
	factory := NewLogFactory("Debug", make(map[string]string))
	sut := factory.NewLogger(make(map[string]string))

	// Act
	sut.Debug("event", "msg %s %s", "arg1", "arg2")
	sut.Info("event", "msg %s %s", "arg1", "arg2")
	sut.Warn("event", "msg %s %s", "arg1", "arg2")
	sut.Error("event", "msg %s %s", "arg1", "arg2")
	logger := sut.(*loggerImpl).logger

	assert.NotNil(t, logger)
}

func TestLoggerImpl_GetLogger_ErrorLevel(t *testing.T) {
	factory := NewLogFactory("Error", make(map[string]string))
	sut := factory.NewLogger(make(map[string]string))

	// Act
	sut.Debug("event", "msg %s %s", "arg1", "arg2")
	sut.Info("event", "msg %s %s", "arg1", "arg2")
	sut.Warn("event", "msg %s %s", "arg1", "arg2")
	sut.Error("event", "msg %s %s", "arg1", "arg2")
	logger := sut.(*loggerImpl).logger

	assert.NotNil(t, logger)
}

func TestLoggerImpl_GetLogger_UnknownLevel(t *testing.T) {
	factory := NewLogFactory("Whatevah", make(map[string]string))
	sut := factory.NewLogger(make(map[string]string))

	// Act
	sut.Debug("event", "msg %s %s", "arg1", "arg2")
	sut.Info("event", "msg %s %s", "arg1", "arg2")
	sut.Warn("event", "msg %s %s", "arg1", "arg2")
	sut.Error("event", "msg %s %s", "arg1", "arg2")
	logger := sut.(*loggerImpl).logger

	assert.NotNil(t, logger)
}

func TestLoggerImpl_GetLogger_StaticMsg(t *testing.T) {
	factory := NewLogFactory("Debug", make(map[string]string))
	sut := factory.NewLogger(make(map[string]string))

	// Act
	sut.Debug("event", "msg")
	sut.Info("event", "msg")
	sut.Warn("event", "msg")
	sut.Error("event", "msg")
	logger := sut.(*loggerImpl).logger

	assert.NotNil(t, logger)
}

func TestLoggerImpl_GetLogger_CombineMetas(t *testing.T) {
	meta1 := make(map[string]string)
	meta1["key1"] = "value1"
	meta1["key2"] = "value2"
	meta2 := make(map[string]string)
	meta2["key3"] = "value3"
	meta1["key2"] = "value2b"
	factory := NewLogFactory("Debug", meta1)
	sut := factory.NewLogger(meta2)

	// Act
	sut.Debug("event", "msg %s %s", "arg1", "arg2")
	sut.Info("event", "msg %s %s", "arg1", "arg2")
	sut.Warn("event", "msg %s %s", "arg1", "arg2")
	sut.Error("event", "msg %s %s", "arg1", "arg2")
	logger := sut.(*loggerImpl).logger

	assert.NotNil(t, logger)
}

gha_language: Go


text:
# Copyright (c) 2013-2014, Richard Wiedenhöft <richard@wiedenhoeft.xyz>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

if (NOT DEFINED INSTALL_PREFIX)
	set (INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}")
endif ()

if (NOT DEFINED INSTALL_EXEC_PREFIX)
	set (INSTALL_EXEC_PREFIX "${INSTALL_PREFIX}")
endif ()

if (NOT DEFINED INSTALL_BINDIR)
	set (INSTALL_BINDIR "${INSTALL_EXEC_PREFIX}/bin")
endif ()

if (NOT DEFINED INSTALL_SBINDIR)
	set (INSTALL_SBINDIR "${INSTALL_EXEC_PREFIX}/sbin")
endif ()

if (NOT DEFINED INSTALL_LIBDIR)
	set (INSTALL_LIBDIR "${INSTALL_EXEC_PREFIX}/lib")
endif ()

if (NOT DEFINED INSTALL_LIBEXECDIR)
	set (INSTALL_LIBEXECDIR "${INSTALL_EXEC_PREFIX}/libexec")
endif ()

if (NOT DEFINED INSTALL_SYSCONFDIR)
	set (INSTALL_SYSCONFDIR "${INSTALL_PREFIX}/etc")
endif ()

if (NOT DEFINED INSTALL_SHAREDSTATEDIR)
	set (INSTALL_SHAREDSTATEDIR "${INSTALL_PREFIX}/com")
endif ()

if (NOT DEFINED INSTALL_LOCALSTATEDIR)
	set (INSTALL_LOCALSTATEDIR "${INSTALL_PREFIX}/var")
endif ()

if (NOT DEFINED INSTALL_RUNSTATEDIR)
	set (INSTALL_RUNSTATEDIR "${INSTALL_LOCALSTATEDIR}/run")
endif ()

if (NOT DEFINED INSTALL_INCLUDEDIR)
	set (INSTALL_INCLUDEDIR "${INSTALL_PREFIX}/include")
endif ()

if (NOT DEFINED INSTALL_DATAROOTDIR)
	set (INSTALL_DATAROOTDIR "${INSTALL_PREFIX}/share")
endif ()

if (NOT DEFINED INSTALL_DATADIR)
	set (INSTALL_DATADIR "${INSTALL_DATAROOTDIR}")
endif ()

if (NOT DEFINED INSTALL_INFODIR)
	set (INSTALL_INFODIR "${INSTALL_DATAROOTDIR}/info")
endif ()

if (NOT DEFINED INSTALL_LOCALEDIR)
	set (INSTALL_LOCALEDIR "${INSTALL_DATAROOTDIR}/locale")
endif ()

if (NOT DEFINED INSTALL_MANDIR)
	set (INSTALL_MANDIR "${INSTALL_DATAROOTDIR}/man")
endif ()

if (NOT DEFINED INSTALL_DOCDIR)
	set (INSTALL_DOCDIR "${INSTALL_DATAROOTDIR}/doc")
endif ()

if (NOT DEFINED INSTALL_HTMLDIR)
	set (INSTALL_HTMLDIR "${INSTALL_DOCDIR}")
endif ()

if (NOT DEFINED INSTALL_DVIDIR)
	set (INSTALL_DVIDIR "${INSTALL_DOCDIR}")
endif ()

if (NOT DEFINED INSTALL_PDFDIR)
	set (INSTALL_PDFDIR "${INSTALL_DOCDIR}")
endif ()

if (NOT DEFINED INSTALL_PSDIR)
	set (INSTALL_PSDIR "${INSTALL_DOCDIR}")
endif ()

# Suppress unused-warning
set (DUMMY "${INSTALL_PREFIX} ${INSTALL_EXEC_PREFIX} ${INSTALL_BINDIR} ${INSTALL_SBINDIR} ${INSTALL_LIBDIR} ${INSTALL_LIBEXECDIR} ${INSTALL_SYSCONFDIR} ${INSTALL_SHAREDSTATEDIR} ${INSTALL_LOCALSTATEDIR} ${INSTALL_RUNSTATEDIR} ${INSTALL_INCLUDEDIR} ${INSTALL_OLDINCLUDEDIR} ${INSTALL_DATAROOTDIR} ${INSTALL_DATADIR} ${INSTALL_INFODIR} ${INSTALL_LOCALEDIR} ${INSTALL_MANDIR} ${INSTALL_DOCDIR} ${INSTALL_HTMLDIR}${INSTALL_DVIDIR} ${INSTALL_PDFDIR} ${INSTALL_PSDIR}")

mark_as_advanced (DUMMY)

repository: Richard-W/cmake-configure-wrapper

repo_name: Richard-W/cmake-configure-wrapper

gha_language: Perl

extension: cmake


text:
#include <algorithm>
#include <filesystem>
#include <functional>
#include <iostream>
#include <memory>
#include <vector>

#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"

#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <glm/glm.hpp>
#include <glm/gtc/constants.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/random.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <assimp/scene.h>

#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"

#include "camera.h"
#include "cloth.h"
#include "hand_mesh.h"
#include "light.h"
#include "mesh.h"
#include "misc.h"
#include "model.h"
#include "object.h"
#include "shader.h"
#include "stb_image.h"
#include "time.h"

using namespace std;

// --------------------
// Classes
// --------------------
class MainContext {
public:
  static const int HEIGHT = 600;
  static const int WIDTH = 800;

  GLFWwindow *window;

  // Frame count and time information
  int num_frames = 0;
  double realtime_ms = 0.0f;
  double last_time_ms = 0.0f;
  double delta_ms = 0.0f;

  bool debug = false;
  bool move_light = false;
  bool light_directional = false;
  bool light_spotlight = false;
  bool pendulumSpotLights = false;
  bool drawBorder = false;

  Timer graphicsTimer;
  Timer physicsTimer;
  Timer inputTimer;
  VirtualClock graphicsClock;
  VirtualClock physicsClock;
  GlfwClock realtimeClock;
  FrameCounter physicsFrameCounter;
  FrameCounter graphicsFrameCounter;
  FrameCounter realtimeFrameCounter;
  FrameCounter inputFrameCounter;

  int _do_input;
  int _do_physics;
  int _do_render;

  MainContext() {
    graphicsTimer.setIntervalMillis(1000 / 30.0);
    physicsTimer.setIntervalMillis(1000 / 30.0);
    inputTimer.setIntervalMillis(1000 / 30.0);
  }

  void updateTime() {
    realtime_ms = realtimeClock.getTimeMillis();
    delta_ms = realtime_ms - last_time_ms;
    last_time_ms = realtime_ms;

    graphicsTimer.tickWithClock(graphicsClock);
    physicsTimer.tickWithClock(physicsClock);
    inputTimer.tickWithClock(realtimeClock);
    realtimeFrameCounter.tick(realtime_ms);
    _do_input = inputTimer.passed();
    _do_render = graphicsTimer.passed();
    _do_physics = physicsTimer.passed();

    // if (realtimeFrameCounter.tick(realtime_ms)) {
    //  printf("%10.2fs l:%5.0f fps, i:%3.0f fps, r:%3.0f fps, p:%3.0f fps, "
    //         "delta:%8fs\n",
    //         realtime_ms / 1000, realtimeFrameCounter.fps(),
    //         inputFrameCounter.fps(), graphicsFrameCounter.fps(),
    //         physicsFrameCounter.fps(), delta_ms / 1000);
    //}
  }

  int do_input() { return _do_input; }
  int do_physics() { return _do_physics; }
  int do_render() { return _do_render; }
  float delta_time() {
    // return delta_ms;
    // printf("%f\n", inputTimer.getIntervalMillis());
    return (inputTimer.getIntervalMillis() / 1000);
  };

  float aspect_ratio() const {
    return float(MainContext::WIDTH) / float(MainContext::HEIGHT);
  }
};

class Input {
public:
  bool keys[1024];
  bool prevKeys[1024];
  bool shift = false;
  bool ctrl = false;

  double mouse_x;
  double mouse_y;
  double prev_mouse_x;
  double prev_mouse_y;
  bool mouse_left;
  bool mouse_right;

  static Input *get() {
    static Input input;
    return &input;
  }

private:
  Input() {
    for (int i = 0; i < 1024; i++) {
      keys[i] = false;
      prevKeys[i] = false;
    }
  }
  ~Input() {}
};

std::ostream &operator<<(std::ostream &os, const glm::vec3 &v) {
  os << "(" << v.x << "," << v.y << "," << v.z << ")";
  return os;
}

// Function Defs
// ----------------------------------
// void process_input(const MainContext& context, const Input& input, Camera*
// cam);
void process_input(MainContext &context, const Input &input, Camera *cam);

// Input callbacks
// ------------------
void key_callback(GLFWwindow *window, int key, int scancode, int action,
                  int mods);
void mouse_callback(GLFWwindow *window, double x, double y);
void error_callback(int error, const char *description);

// --------------------------
// CALLBACKS
// --------------------------
void error_callback(int error, const char *description) {
  fprintf(stderr, "Error: %s\n", description);
}

void key_callback(GLFWwindow *window, int key, int scancode, int action,
                  int mods) {
  if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
    glfwSetWindowShouldClose(window, GLFW_TRUE);
  }

  Input *input = Input::get();

  input->shift = mods & GLFW_MOD_SHIFT;
  input->ctrl = mods & GLFW_MOD_CONTROL;

  if (action == GLFW_PRESS || action == GLFW_REPEAT) {
    // input->prevKeys[key] = input->keys[key];
    input->keys[key] = true;
  } else if (action == GLFW_RELEASE) {
    // input->prevKeys[key] = input->keys[key];
    input->keys[key] = false;
  }
}

void mouse_callback(GLFWwindow *window, double xpos, double ypos) {
  return;
  Input *input = Input::get();

  static bool first_mouse = true;
  if (first_mouse) {
    first_mouse = false;
    input->prev_mouse_x = xpos;
    input->prev_mouse_y = ypos;
  }
  input->prev_mouse_x = input->mouse_x;
  input->prev_mouse_y = input->mouse_y;
  input->mouse_x = xpos;
  input->mouse_y = ypos;

  // printf("Mouse: %.2f,%.2f\n", xpos, ypos);
}

void mouse_button_callback(GLFWwindow *window, int button, int action,
                           int mods) {
  return;
  Input *input = Input::get();
  if (action == GLFW_PRESS) {
    input->mouse_left = button == GLFW_MOUSE_BUTTON_LEFT;
    input->mouse_right = button == GLFW_MOUSE_BUTTON_RIGHT;
  } else {
    input->mouse_left = false;
    input->mouse_right = false;
  }
}

void process_input(MainContext &context, const Input &input, Camera *cam) {
  if (input.keys[GLFW_KEY_W]) {
    cam->process_input(Camera::FORWARD, context.delta_time());
  } else if (input.keys[GLFW_KEY_S]) {
    cam->process_input(Camera::BACKWARD, context.delta_time());
  }

  if (input.keys[GLFW_KEY_D]) {
    cam->process_input(Camera::RIGHT, context.delta_time());
  } else if (input.keys[GLFW_KEY_A]) {
    cam->process_input(Camera::LEFT, context.delta_time());
  }

  if (input.keys[GLFW_KEY_SPACE]) {
    if (input.shift) {
      cam->process_input(Camera::DOWN, context.delta_time());
    } else {
      cam->process_input(Camera::UP, context.delta_time());
    }
  }

  if (input.keys[GLFW_KEY_LEFT]) {
    cam->process_rotate(Camera::YAW_LEFT, context.delta_time());
  } else if (input.keys[GLFW_KEY_RIGHT]) {
    cam->process_rotate(Camera::YAW_RIGHT, context.delta_time());
  } else if (input.keys[GLFW_KEY_UP]) {
    cam->process_rotate(Camera::PITCH_UP, context.delta_time());
  } else if (input.keys[GLFW_KEY_DOWN]) {
    cam->process_rotate(Camera::PITCH_DOWN, context.delta_time());
  } else if (input.keys[GLFW_KEY_PERIOD]) {
    cam->process_rotate(Camera::ROLL_CLOCKWISE, context.delta_time());
  } else if (input.keys[GLFW_KEY_COMMA]) {
    cam->process_rotate(Camera::ROLL_COUNTER_CLOCKWISE, context.delta_time());
  }

  if (input.keys[GLFW_KEY_T]) {
    context.debug = !context.debug;
  }
  if (input.keys[GLFW_KEY_L]) {
    context.move_light = !context.move_light;
  }
  if (input.keys[GLFW_KEY_B]) {
    context.light_directional = true;
  }
  if (input.keys[GLFW_KEY_N]) {
    context.light_directional = false;
  }
  if (input.keys[GLFW_KEY_G]) {
    context.light_spotlight = true;
  }
  if (input.keys[GLFW_KEY_H]) {
    context.light_spotlight = false;
  }

  if (input.keys[GLFW_KEY_1]) {
    cam->reset();
  }
  if (input.keys[GLFW_KEY_2]) {
    cam->reset();
    cam->translator.move_to(glm::vec3(0, 0, 3.f));
    cam->rotator.rotateY(0);
  }
  if (input.keys[GLFW_KEY_3]) {
    cam->reset();
    cam->translator.move_to(glm::vec3(3, 3, 3));
    // cam->rotator.reset();
    cam->rotator.rotateY(-45);
    cam->rotator.rotateX(-45);
  }
  if (input.keys[GLFW_KEY_4]) {
    cam->reset();
    cam->translator.move_to(glm::vec3(-3, 3, -3));
    // cam->rotator.reset();
    cam->rotator.rotateY(180);
    cam->rotator.rotateY(-45);
    cam->rotator.rotateX(-45);
  }

  // double x_offset = input.mouse_x - input.prev_mouse_x;
  // double y_offset = input.prev_mouse_y - input.mouse_y;
  // cam->process_mouse(x_offset, y_offset);
}

void updatePendulumSpotLights(MainContext &ctx, vector<Light> &spotLights) {
  glm::vec3 attachPoint = glm::vec3(0, 5, 0);
  float theta_0s[] = {25, -25, 45, 65};
  float Ls[] = {3, 2, 0.5, 1};
  for (int i = 0; i < spotLights.size(); i++) {
    Light &sl = spotLights[i];
    float t = ctx.physicsClock.getTimeSecs() * 1.5;
    float theta_0 = glm::radians(theta_0s[i]);
    float g = 9.81;
    float L = Ls[i];
    float w = glm::sqrt(g / L);
    float theta_t = theta_0 * cos(w * t);

    sl.rotation.reset();
    sl.rotation.rotateX(90.0f);
    sl.rotation.rotateY(glm::degrees(theta_t));
    sl.position.move_to(attachPoint + sl.rotation.front() * L);
  }
}

void drawImGui(MainContext &ctx, Camera &cam) {
  // printf("%10.2fs l:%5.0f fps, i:%3.0f fps, r:%3.0f fps, p:%3.0f fps, "
  //     "delta:%8fs\n",
  //     realtime_ms / 1000, realtimeFrameCounter.fps(),
  //     inputFrameCounter.fps(), graphicsFrameCounter.fps(),
  // physicsFrameCounter.fps(), delta_ms / 1000);
  // absl::StrFormat("%10.2fs delta:%8fs", ctx.realtime_ms / 1000,
  // ctx.delta_ms); absl::StrFormat("%10.2fs l:%5.0f fps, i:%3.0f fps, r:%3.0f
  // fps, p:%3.0f fps, "
  ImGui::Begin("Information");
  ImGui::Text("Time: %5.2fs Delta: %8fs", ctx.realtime_ms / 1000, ctx.delta_ms);
  ImGui::Text("l:%5.0f fps, i:%3.0f fps, r:%3.0f fps, p:%3.0f fps",
              ctx.realtimeFrameCounter.fps(), ctx.inputFrameCounter.fps(),
              ctx.graphicsFrameCounter.fps(), ctx.physicsFrameCounter.fps());
  ImGui::BeginChild("Camera", ImVec2(250, 100), true);
  ImGui::Text("Camera");
  ImGui::Text(" pos  (%5.2f,%5.2f,%5.2f)", cam.translator.pos.x,
              cam.translator.pos.y, cam.translator.pos.z);
  ImGui::Text(" front(%5.2f,%5.2f,%5.2f)", cam.rotator.front().x,
              cam.rotator.front().y, cam.rotator.front().z);
  ImGui::Text(" up   (%5.2f,%5.2f,%5.2f)", cam.rotator.up().x,
              cam.rotator.up().y, cam.rotator.up().z);
  ImGui::Text(" right(%5.2f,%5.2f,%5.2f)", cam.rotator.right().x,
              cam.rotator.right().y, cam.rotator.right().z);
  ImGui::EndChild();
  if (ImGui::Button("F1")) {
    cam.reset();
  }
  ImGui::SameLine();
  ImGui::Checkbox("Debug", &ctx.debug);
  ImGui::End();
}

// --------------------------
// MAIN
// --------------------------

int main(int argc, char **argv) {
  if (!glfwInit()) {
    fprintf(stderr, "Failed to initialize GLFW\n");
    getchar();
    return -1;
  }

  const char *glsl_version = "#version 130";
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Important in Mac
  glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

  MainContext ctx;
  Camera cam;
  cam.reset();

  ctx.window = glfwCreateWindow(MainContext::WIDTH, MainContext::HEIGHT,
                                "Cloth", NULL, NULL);
  if (ctx.window == NULL) {
    fprintf(stderr, "Failed to create GLFW window\n");
    glfwTerminate();
    return -1;
  }
  glfwMakeContextCurrent(ctx.window);
  glfwSetErrorCallback(error_callback);
  glfwSetKeyCallback(ctx.window, key_callback);
  glfwSetCursorPosCallback(ctx.window, mouse_callback);
  glfwSetMouseButtonCallback(ctx.window, mouse_button_callback);
  glewExperimental = GL_TRUE;

  if (glewInit() != GLEW_OK) {
    fprintf(stderr, "Failed to initialize GLEW\n");
    return -1;
  }

  IMGUI_CHECKVERSION();
  ImGui::CreateContext();
  ImGuiIO &io = ImGui::GetIO();
  (void)io;
  ImGui::StyleColorsDark();
  ImGui_ImplGlfw_InitForOpenGL(ctx.window, true);
  ImGui_ImplOpenGL3_Init(glsl_version);

  // Viewport
  glViewport(0, 0, MainContext::WIDTH, MainContext::HEIGHT);
  glEnable(GL_DEPTH_TEST);
  //glDisable(GL_STENCIL_TEST);
  glPointSize(5);
  glLineWidth(5);
  glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
  glEnable(GL_CULL_FACE);
  glCullFace(GL_BACK);
  //glPolygonMode(GL_FRONT, GL_FILL);
  // glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);
  // glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

  // Shader reading
  Shader shader("shaders/vs.glsl", "shaders/fs.glsl");
  Shader light_shader("shaders/vs.glsl", "shaders/light_fs.glsl");
  Shader debug_shader("shaders/debug_vs.glsl", "shaders/debug_fs.glsl",
                      "shaders/debug_gs.glsl");
  Shader shaderSingleColor("shaders/vs.glsl",
                           "shaders/shader_single_color_fs.glsl");
  printf("Program start.\n");

  // Load a texture
  // unsigned int texture1 = load_texture("res/container.jpg");
  // unsigned int texture2 = load_texture("res/awesomeface.png");
  unsigned int texture3 = load_texture("res/container2.png");
  unsigned int texture4 = load_texture("res/container2_specular.png");
  unsigned int texture5 = load_texture("res/matrix.jpg");

  // Objects and meshes
  Mesh cubeMesh = create_cube_mesh2({
      {"texture_diffuse", texture3}, {"texture_specular", texture4},
      //{"texture_emission", texture5},
  });
  Model cube = Model(cubeMesh);
  // Model backpack = Model("res/backpack/backpack.obj");

  vector<Object> objects;
  glm::vec3 cubePositions[] = {
      glm::vec3(0.0f, 0.0f, 0.0f),    glm::vec3(2.0f, 5.0f, -15.0f),
      glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f),
      glm::vec3(2.4f, -0.4f, -3.5f),  glm::vec3(-1.7f, 3.0f, -7.5f),
      glm::vec3(1.3f, -2.0f, -2.5f),  glm::vec3(1.5f, 2.0f, -2.5f),
      glm::vec3(1.5f, 0.2f, -1.5f),   glm::vec3(-1.3f, 1.0f, -1.5f)};
  for (int i = 0; i < 10; i++) {
    // Object o = Object(cube);
    Object o = Object(cube);
    o.position.move_to(cubePositions[i]);
    float angle = 20.0f * i;
    o.rotation.rotate(glm::vec3(1.0f, 0.3f, 0.5f), angle);
    objects.push_back(o);
  }
  objects.clear();
  // objects.push_back(Object(backpack));
  objects.push_back(Object(cube));
  objects.push_back(Object(cube));
  // objects.push_back(Object(cube));
  objects[0].position.move_to(glm::vec3(1, 0, 0));
  objects[1].position.move_to(glm::vec3(-1, 0, 0));
  // objects[2].position.move_to(glm::vec3(0, 0, 3));
  // objects[3].position.move_to(glm::vec3(0, 0, -3));
  // objects.clear();
  // objects.push_back(Object(cube));
  // objects.push_back(Object(cube));
  // objects.push_back(Object(cube));
  // objects.push_back(Object(cube));
  // objects[1].position.move_to(glm::vec3(1,0,0));
  // objects[1].rotation.rotateX(20);
  // objects[2].position.move_to(glm::vec3(2,0,0));
  // objects[2].rotation.rotateY(20);
  // objects[3].position.move_to(glm::vec3(3,0,0));
  // objects[3].rotation.rotateZ(20);

  vector<Light> dirLights;
  vector<Light> spotLights;
  vector<Light> pointLights;

  dirLights.push_back(Light(cube, Light::DIRECTIONAL));
  dirLights[0].rotation.rotateY(90.0f);
  dirLights[0].position.move_to(-dirLights[0].rotation.front());
  dirLights[0].scale.scale(0.1);

  spotLights.push_back(Light(cube, Light::SPOT));
  spotLights.push_back(Light(cube, Light::SPOT));
  spotLights.push_back(Light(cube, Light::SPOT));
  spotLights.push_back(Light(cube, Light::SPOT));
  spotLights[0].scale.scale(0.1);
  spotLights[1].scale.scale(0.1);
  spotLights[2].scale.scale(0.1);
  spotLights[3].scale.scale(0.1);
  // spotLights[0].position.move_to(glm::vec3(0, 1.5, 0));
  // spotLights[0].rotation.rotateX(90.0f);

  glm::vec3 pointLightPositions[] = {
      glm::vec3(1, 1, 1), glm::vec3(0.7f, 0.2f, 2.0f),
      glm::vec3(2.3f, -3.3f, -4.0f), glm::vec3(-4.0f, 2.0f, -12.0f),
      glm::vec3(0.0f, 0.0f, -3.0f)};
  for (int i = 0; i < 4; i++) {
    Light l = Light(cube);
    l.position.move_to(pointLightPositions[i]);
    l.scale.scale(0.1);
    pointLights.push_back(l);
  }

  dirLights.clear();
  spotLights.clear();
  //pointLights.clear();

  // Setup shaders
  shader.use();
  shader.setInt("numDirLights", dirLights.size());
  shader.setInt("numSpotLights", spotLights.size());
  shader.setInt("numPointLights", pointLights.size());

  // Main loop
  while (!glfwWindowShouldClose(ctx.window)) {
    ctx.updateTime();
    // cout << cam.rotator << endl;

    // Input
    if (ctx.do_input()) {
      ctx.inputFrameCounter.tick(ctx.realtime_ms);
      process_input(ctx, *Input::get(), &cam);
    }

    // Physics
    if (ctx.do_physics()) {
      if (ctx.physicsFrameCounter.tick(ctx.realtime_ms) && false) {
        printf("Do physics: fps: %f, time: %f, rate = %f \n",
               ctx.physicsFrameCounter.fps(),
               ctx.physicsTimer.getCurrentMillis(), ctx.physicsClock.getRate());
      }
      if (ctx.move_light && pointLights.size() > 0) {
        float time_secs = ctx.physicsClock.getTimeSecs();
        // float time_secs = current_time_ms / 1000;
        pointLights[0].position.move_to(glm::vec3(
            cos(time_secs * 1.5) * 2.5, 1.25f, sin(time_secs * 1.5) * 2.5));
      }
      if (ctx.light_spotlight && spotLights.size() > 0) {
        spotLights[0].position.move_to(
            (cam.translator.pos - 2.0f * cam.rotator.front()));
        spotLights[0].rotation = cam.rotator;
      }

      if (ctx.pendulumSpotLights) {
        updatePendulumSpotLights(ctx, spotLights);
      }

      // Update all the lights
      for (int i = 0; i < dirLights.size(); i++) {
        dirLights[i].use(&shader, i);
      }
      for (int i = 0; i < spotLights.size(); i++) {
        spotLights[i].use(&shader, i);
      }
      for (int i = 0; i < pointLights.size(); i++) {
        pointLights[i].use(&shader, i);
      }
    }

    // Render
    if (ctx.do_render()) {
      if (ctx.graphicsFrameCounter.tick(ctx.realtime_ms) && false) {
        printf("Do graphics: fps: %f, time: %f, rate = %f \n",
               ctx.graphicsFrameCounter.fps(),
               ctx.graphicsTimer.getCurrentMillis(),
               ctx.graphicsClock.getRate());
      }

      glClearColor(0, 0, 0, 0);
      //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER);
      glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

      // Draw
      ImGui_ImplOpenGL3_NewFrame();
      ImGui_ImplGlfw_NewFrame();
      ImGui::NewFrame();
      drawImGui(ctx, cam);
      ImGui::Render();

      glEnable(GL_STENCIL_TEST);
      glStencilMask(0xFF); // enable writing to the stencil buffer

      shader.use();
      cam.use(ctx.aspect_ratio(), &shader);
      glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP);
      glStencilOpSeparate(GL_FRONT, GL_REPLACE, GL_REPLACE, GL_REPLACE);
      glStencilFuncSeparate(GL_BACK, GL_NEVER, 1, 0xFF); // all fragments should pass the stencil test
      glStencilFuncSeparate(GL_FRONT, GL_ALWAYS, 1, 0xFF); // all fragments should pass the stencil test
      for (Object &obj : objects) {
        obj.draw(shader);
      }

      if (ctx.drawBorder) {
        shaderSingleColor.use();
        shaderSingleColor.set4Float("customColor", 0.3, 0,0.5, 1.0);
        cam.use(ctx.aspect_ratio(), &shaderSingleColor);
        //glStencilMask(0x00);
        glStencilOpSeparate(GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP);
        glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP);
        glStencilFuncSeparate(GL_BACK, GL_NEVER, 1, 0xFF); // all fragments should pass the stencil test
        glStencilFuncSeparate(GL_FRONT, GL_NOTEQUAL, 1, 0xFF); // all fragments should pass the stencil test
        for (Object &obj : objects) {
          obj.scale.scale(1.05f);
          obj.draw(shaderSingleColor);
          obj.scale.scale(1.0f);
        }
        glStencilMask(0xFF);
        glStencilFunc(GL_ALWAYS, 1, 0xFF);
        glEnable(GL_DEPTH_TEST);
      }

      // Draw lights
      light_shader.use();
      cam.use(ctx.aspect_ratio(), &light_shader);
      for (Light &obj : pointLights) {
        obj.draw(light_shader);
      }
      for (Light &obj : spotLights) {
        obj.draw(light_shader);
      }
      for (Light &obj : dirLights) {
        obj.draw(light_shader);
      }

      // Draw debug if requested
      if (ctx.debug) {
        debug_shader.use();
        cam.use(ctx.aspect_ratio(), &debug_shader);
        for (Object &obj : objects) {
          obj.draw(debug_shader);
        }
      }

      ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
      glfwSwapBuffers(ctx.window);
    }

    glfwPollEvents();
  }

  ImGui_ImplOpenGL3_Shutdown();
  ImGui_ImplGlfw_Shutdown();
  ImGui::DestroyContext();
  glfwDestroyWindow(ctx.window);
  glfwTerminate();
  return 0;
}

repository: Stymphalian/LearnOpenGL

repo_name: Stymphalian/LearnOpenGL

extension: cpp


text:
package kata

import "regexp"

func Solution(str string) (output []string) {
  re, _ := regexp.Compile(`\w{2}`)
  output = re.FindAllString(str, -1)
  if len(str) & 1 == 1 {
    output = append(output, string(str[len(str)-1])+"_")
  }
  return
}

repository: stevejaxon/learning-go-lang

repo_name: stevejaxon/learning-go-lang


text:
SUMMARY = "An image with a development/debug \
environment suitable for building GNSS-SDR."

EXTRA_IMAGE_FEATURES += "tools-debug tools-profile tools-sdk dev-pkgs"
LICENSE = "MIT"

require gnuradio-dev-image.bb

RDEPENDS_packagegroup-sdr-base-python += " python3-six"

SDK_EXTRA_TOOLS += "nativesdk-python3-six"

CORE_IMAGE_EXTRA_INSTALL += " \
    packagegroup-gnss-sdr-base \
"

repository: zarym/meta-gnss-sdr

repo_name: zarym/meta-gnss-sdr


text:
package cli

import (
	"context"

	"github.com/cosmos/cosmos-sdk/client"
	"github.com/cosmos/cosmos-sdk/client/flags"
	"github.com/spf13/cobra"

	types "github.com/ovrclk/akash/x/deployment/types/v1beta2"
)

// GetQueryCmd returns the query commands for the deployment module
func GetQueryCmd() *cobra.Command {

	cmd := &cobra.Command{
		Use:                        types.ModuleName,
		Short:                      "Deployment query commands",
		SuggestionsMinimumDistance: 2,
		RunE:                       client.ValidateCmd,
	}

	cmd.AddCommand(
		cmdDeployments(),
		cmdDeployment(),
		getGroupCmd(),
	)

	return cmd
}

func cmdDeployments() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "list",
		Short: "Query for all deployments",
		Args:  cobra.ExactArgs(0),
		RunE: func(cmd *cobra.Command, args []string) error {
			clientCtx, err := client.GetClientQueryContext(cmd)
			if err != nil {
				return err
			}

			queryClient := types.NewQueryClient(clientCtx)

			dfilters, err := DepFiltersFromFlags(cmd.Flags())
			if err != nil {
				return err
			}

			pageReq, err := client.ReadPageRequest(cmd.Flags())
			if err != nil {
				return err
			}

			params := &types.QueryDeploymentsRequest{
				Filters:    dfilters,
				Pagination: pageReq,
			}

			res, err := queryClient.Deployments(context.Background(), params)
			if err != nil {
				return err
			}

			return clientCtx.PrintProto(res)
		},
	}

	flags.AddQueryFlagsToCmd(cmd)
	flags.AddPaginationFlagsToCmd(cmd, "deployments")
	AddDeploymentFilterFlags(cmd.Flags())

	return cmd
}

func cmdDeployment() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "get",
		Short: "Query deployment",
		Args:  cobra.ExactArgs(0),
		RunE: func(cmd *cobra.Command, args []string) error {
			clientCtx, err := client.GetClientQueryContext(cmd)
			if err != nil {
				return err
			}

			queryClient := types.NewQueryClient(clientCtx)

			id, err := DeploymentIDFromFlags(cmd.Flags())
			if err != nil {
				return err
			}

			res, err := queryClient.Deployment(context.Background(), &types.QueryDeploymentRequest{ID: id})
			if err != nil {
				return err
			}

			return clientCtx.PrintProto(res)
		},
	}

	flags.AddQueryFlagsToCmd(cmd)
	AddDeploymentIDFlags(cmd.Flags())
	MarkReqDeploymentIDFlags(cmd)

	return cmd
}

func getGroupCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:                        "group",
		Short:                      "Deployment group query commands",
		SuggestionsMinimumDistance: 2,
		RunE:                       client.ValidateCmd,
	}

	cmd.AddCommand(
		cmdGetGroup(),
	)

	return cmd
}

func cmdGetGroup() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "get",
		Short: "Query group of deployment",
		Args:  cobra.ExactArgs(0),
		RunE: func(cmd *cobra.Command, args []string) error {
			clientCtx, err := client.GetClientQueryContext(cmd)
			if err != nil {
				return err
			}

			queryClient := types.NewQueryClient(clientCtx)

			id, err := GroupIDFromFlags(cmd.Flags())
			if err != nil {
				return err
			}

			res, err := queryClient.Group(context.Background(), &types.QueryGroupRequest{ID: id})
			if err != nil {
				return err
			}

			return clientCtx.PrintProto(&res.Group)
		},
	}

	flags.AddQueryFlagsToCmd(cmd)
	AddGroupIDFlags(cmd.Flags())
	MarkReqGroupIDFlags(cmd)

	return cmd
}

repository: ChandraStation/akash

repo_name: ChandraStation/akash


text:
package ocmprovider

import (
	"fmt"
	"log"
	"sort"

	"github.com/Masterminds/semver/v3"
	v1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"
	viper "github.com/openshift/osde2e/pkg/common/concurrentviper"
	"github.com/openshift/osde2e/pkg/common/config"
	"github.com/openshift/osde2e/pkg/common/spi"
	"github.com/openshift/osde2e/pkg/common/util"
)

const (
	// VersionPrefix is the string that every OSD version begins with.
	VersionPrefix = "openshift-"

	// PageSize is the number of results to get per page from the cluster versions endpoint
	PageSize = 100

	// NoVersionFound is the value placed into a version string when no valid Cincinnati version can be selected.
	NoVersionFound = "NoVersionFound"
)

// Versions will return all of the available version and a default override of the production default version
// if using a non-production environment.
func (o *OCMProvider) Versions() (*spi.VersionList, error) {
	var err error

	versions := []*spi.Version{}
	page := 1
	log.Printf("Querying cluster versions endpoint.")
	for {
		var resp *v1.VersionsListResponse
		err = retryer().Do(func() error {
			var err error

			resp, err = o.conn.ClustersMgmt().V1().Versions().List().Page(page).Size(PageSize).Send()

			if err != nil {
				return err
			}

			if resp != nil && resp.Error() != nil {
				return errResp(resp.Error())
			}

			return nil
		})

		if err != nil {
			err = fmt.Errorf("failed getting list of OSD versions: %v", err)
		} else if resp != nil {
			err = errResp(resp.Error())
		}

		if err != nil {
			log.Print("error getting cluster versions from getSemverList.Response")
			log.Printf("Response Headers: %v", resp.Header())
			log.Printf("Response Error(s): %v", resp.Error())
			log.Printf("HTTP Code: %d", resp.Status())
			log.Printf("Size of response: %d", resp.Size())

			return nil, fmt.Errorf("couldn't retrieve available versions: %v", err)
		}

		// parse versions, filter for major+minor nightlies, then sort
		resp.Items().Each(func(v *v1.Version) bool {
			if version, err := util.OpenshiftVersionToSemver(v.ID()); err != nil {
				log.Printf("could not parse version '%s': %v", v.ID(), err)
			} else if v.Enabled() {
				if v.ChannelGroup() == "stable" || v.ChannelGroup() == viper.GetString(config.Cluster.Channel) {
					spiVersion := spi.NewVersionBuilder().
						Version(version).
						Default(v.Default()).
						Build()

					for _, upgrade := range v.AvailableUpgrades() {
						if version, err := util.OpenshiftVersionToSemver(upgrade); err == nil {
							spiVersion.AddUpgradePath(version)
						}
					}

					versions = append(versions, spiVersion)
				}
			}
			return true
		})

		// If we've looked at all the results, stop collecting them.
		if page*PageSize >= resp.Total() {
			break
		}
		page++
	}

	sort.Slice(versions, func(i, j int) bool {
		return versions[i].Version().GreaterThan(versions[j].Version())
	})

	var defaultVersionOverride *semver.Version = nil

	if o.env != prod {
		var versionList *spi.VersionList
		versionList, err = o.prodProvider.Versions()

		if err != nil {
			return nil, fmt.Errorf("error getting production default: %v", err)
		}

		defaultVersionOverride = versionList.Default()
	}

	return spi.NewVersionListBuilder().
		AvailableVersions(versions).
		DefaultVersionOverride(defaultVersionOverride).
		Build(), nil
}


text:
require midori.inc

PARALLEL_MAKE = ""

SRC_URI = "http://archive.xfce.org/src/apps/midori/0.4/midori-${PV}.tar.bz2;name=midori \
          "
SRC_URI[midori.md5sum] = "a6578ebfd237c0f22cce49113b95f70c"
SRC_URI[midori.sha256sum] = "fadd43f76c1c9f6a16483e60a804e58fb6817c6a595b1acdd59bcbdd7b35bca2"


text:
package types

import (
	"github.com/cosmos/cosmos-sdk/codec"
	"github.com/cosmos/cosmos-sdk/codec/types"
	cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec"
	sdk "github.com/cosmos/cosmos-sdk/types"
	"github.com/cosmos/cosmos-sdk/types/msgservice"
)

func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
	cdc.RegisterInterface((*Period)(nil), nil)
	cdc.RegisterConcrete(&BlockPeriod{}, "payments/BlockPeriod", nil)
	cdc.RegisterConcrete(&TimePeriod{}, "payments/TimePeriod", nil)

	cdc.RegisterConcrete(&MsgCreatePaymentTemplate{}, "payments/MsgCreatePaymentTemplate", nil)
	cdc.RegisterConcrete(&MsgCreatePaymentContract{}, "payments/MsgCreatePaymentContract", nil)
	cdc.RegisterConcrete(&MsgCreateSubscription{}, "payments/MsgCreateSubscription", nil)
	cdc.RegisterConcrete(&MsgSetPaymentContractAuthorisation{}, "payments/MsgSetPaymentContractAuthorisation", nil)
	cdc.RegisterConcrete(&MsgGrantDiscount{}, "payments/MsgGrantDiscount", nil)
	cdc.RegisterConcrete(&MsgRevokeDiscount{}, "payments/MsgRevokeDiscount", nil)
	cdc.RegisterConcrete(&MsgEffectPayment{}, "payments/MsgEffectPayment", nil)
}

func RegisterInterfaces(registry types.InterfaceRegistry) {
	registry.RegisterImplementations((*sdk.Msg)(nil),
		&MsgSetPaymentContractAuthorisation{},
		&MsgCreatePaymentTemplate{},
		&MsgCreatePaymentContract{},
		&MsgCreateSubscription{},
		&MsgGrantDiscount{},
		&MsgRevokeDiscount{},
		&MsgEffectPayment{},
	)
	registry.RegisterInterface(
		"payments.Period",
		(*Period)(nil),
		&BlockPeriod{},
		&TimePeriod{},
		&TestPeriod{},
	)

	msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc)
}

var (
	amino = codec.NewLegacyAmino()

	// ModuleCdc references the global x/payments module codec. Note, the codec should
	// ONLY be used in certain instances of tests and for JSON encoding as Amino is
	// still used for that purpose.
	//
	// The actual codec used for serialization should be provided to x/gov and
	// defined at the application level.
	ModuleCdc = codec.NewAminoCodec(amino)
)

func init() {
	RegisterLegacyAminoCodec(amino)
	cryptocodec.RegisterCrypto(amino)
}

repository: franono/ixo-blockchain

repo_name: franono/ixo-blockchain


text:
package github

import (
	"context"
	"errors"
	"net/http"

	"github.com/google/go-github/github"
	"golang.org/x/oauth2"
)

var client *github.Client

// ErrNotFound is not found error.
var ErrNotFound = errors.New("not found")

// ConnectOption specifies optional parameter to connect github.
type ConnectOption struct {
	AccessToken string
}

// Connect creates github client.
func Connect(op *ConnectOption) {
	var tc *http.Client
	if op != nil && op.AccessToken != "" {
		ts := oauth2.StaticTokenSource(
			&oauth2.Token{AccessToken: op.AccessToken},
		)
		tc = oauth2.NewClient(context.Background(), ts)
	}

	client = github.NewClient(tc)
}

// Disconnect releases github client.
func Disconnect() {
	client = nil
}

// GetOwner gets owner info.
func GetOwner(ctx context.Context, name string) (*github.User, error) {
	owner, res, err := client.Users.Get(ctx, name)
	if res != nil && res.StatusCode == 404 {
		return nil, ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	return owner, nil
}

// LatestRelease fetches latest release of specified repository.
func LatestRelease(ctx context.Context, owner string, name string) (*github.RepositoryRelease, error) {
	release, res, err := client.Repositories.GetLatestRelease(ctx, owner, name)
	if res != nil && res.StatusCode == 404 {
		return nil, ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	return release, nil
}

// LatestCommit fetches latest tag of specified repository.
func LatestCommit(ctx context.Context, owner string, name string) (*github.RepositoryCommit, error) {
	commits, res, err := client.Repositories.ListCommits(ctx, owner, name, &github.CommitsListOptions{
		ListOptions: github.ListOptions{
			Page:    0,
			PerPage: 1,
		},
	})
	if res != nil && res.StatusCode == 404 || len(commits) == 0 {
		return nil, ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	return commits[0], nil
}

// LatestIssue fetches latest issue of specified repository.
func LatestIssue(ctx context.Context, owner string, name string) (*github.Issue, error) {
	page := 0

	for {
		issues, res, err := client.Issues.ListByRepo(ctx, owner, name, &github.IssueListByRepoOptions{
			State: "all",
			ListOptions: github.ListOptions{
				Page:    page,
				PerPage: 20,
			},
		})
		if res != nil && res.StatusCode == 404 || len(issues) == 0 {
			return nil, ErrNotFound
		}
		if err != nil {
			return nil, err
		}

		for _, issue := range issues {
			// if PullRequestLinks is not nil, that's pull request.
			if issue.PullRequestLinks == nil {
				return issue, nil
			}
		}

		page++
	}
}

// LatestPRIssue fetches latest pr of specified repository.
// PR is every pull request is an issue. see https://godoc.org/github.com/google/go-github/github/issues.go?s=780:2350#L16
func LatestPRIssue(ctx context.Context, owner string, name string) (*github.Issue, error) {
	page := 0

	for {
		issues, res, err := client.Issues.ListByRepo(ctx, owner, name, &github.IssueListByRepoOptions{
			State: "all",
			ListOptions: github.ListOptions{
				Page:    page,
				PerPage: 20,
			},
		})
		if res != nil && res.StatusCode == 404 || len(issues) == 0 {
			return nil, ErrNotFound
		}
		if err != nil {
			return nil, err
		}

		for _, issue := range issues {
			// if PullRequestLinks is not nil, this is a pull request.
			if issue.PullRequestLinks != nil {
				return issue, nil
			}
		}

		page++
	}
}

// LatestTag fetches latest tag of specified repository.
func LatestTag(ctx context.Context, owner string, name string) (*github.RepositoryTag, error) {
	tags, res, err := client.Repositories.ListTags(ctx, owner, name, &github.ListOptions{
		Page:    0,
		PerPage: 1,
	})
	if res != nil && res.StatusCode == 404 || len(tags) == 0 {
		return nil, ErrNotFound
	}
	if err != nil {
		return nil, err
	}
	return tags[0], nil
}

repository: kudohamu/watchcat

repo_name: kudohamu/watchcat


text:
package metering

import (
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/golang/glog"
	"github.com/open-horizon/anax/persistence"
	"github.com/open-horizon/anax/policy"
	"golang.org/x/crypto/sha3"
	"time"
)

// The purpose of this module is to encapsulate the metering notification object as much as possible. This
// object is sent as the body of metering notification messages from the consumer to the producer. The Producer
// can use this object to form a blockchain transaction that will permanently record the meter notification
// on the blockchain.

type MeteringNotification struct {
	Amount                 uint64 `json:"amount"`       // The number of tokens granted by this notification, rounded to the nearest minute
	StartTime              uint64 `json:"start_time"`   // The time when the agreement started, in seconds since 1970.
	CurrentTime            uint64 `json:"current_time"` // The time when the notification was sent, in seconds since 1970.
	MissedTime             uint64 `json:"missed_time"`  // The amount of time in seconds that the consumer detected missing data
	AgreementId            string `json:"agreement_id"` // Hex encoded string of a 32 byte number indicating the agreement that this notification is related to.
	meterHash              string // Not serialized in the message, just saved for efficiency
	ConsumerMeterSignature string `json:"consumer_meter_signature"`     // The consumer's signature of the meter (amount, current time, agreement Id)
	AgreementHash          string `json:"agreement_hash"`               // The 32 byte SHA3 FIPS 202 hash of the proposal for the agreement.
	ConsumerSignature      string `json:"consumer_agreement_signature"` // The consumer's signature of the agreement hash.
	ConsumerAddress        string `json:"consumer_address"`             // The consumer's blockchain account/address.
	ProducerSignature      string `json:"producer_agreement_signature"` // The producer's signature of the agreement
	BlockchainType         string `json:"blockchain_type"`              // The type of the blockchain that this notification is intended to work with
}

func (m MeteringNotification) String() string {
	return fmt.Sprintf("Amount: %v, "+
		"StartTime: %v, "+
		"CurrentTime: %v, "+
		"Missed Time: %v, "+
		"AgreementId: %v, "+
		"Meter Hash: %v, "+
		"ConsumerMeterSignature: %v, "+
		"AgreementHash: %v, "+
		"ConsumerSignature: %v, "+
		"ConsumerAddress: %v, "+
		"ProducerSignature: %v, "+
		"BlockchainType: %v",
		m.Amount, m.StartTime, m.CurrentTime, m.MissedTime, m.AgreementId, m.meterHash, m.ConsumerMeterSignature,
		m.AgreementHash, m.ConsumerSignature, m.ConsumerAddress, m.ProducerSignature,
		m.BlockchainType)
}

func (m MeteringNotification) IsValid() (bool, error) {
	if m.StartTime == 0 {
		return false, errors.New(fmt.Sprintf("start time must be non-zero"))
	} else if m.CurrentTime == 0 {
		return false, errors.New(fmt.Sprintf("current time must be non-zero"))
	} else if len(m.AgreementId) == 0 {
		return false, errors.New(fmt.Sprintf("agreement id is empty"))
	} else if len(m.ConsumerMeterSignature) == 0 {
		return false, errors.New(fmt.Sprintf("consumer signature of meter is empty"))
	} else if len(m.AgreementHash) == 0 {
		return false, errors.New(fmt.Sprintf("agreement hash is empty"))
	} else if len(m.ConsumerSignature) == 0 {
		return false, errors.New(fmt.Sprintf("consumer signature of agreement is empty"))
	} else if len(m.ConsumerAddress) == 0 {
		return false, errors.New(fmt.Sprintf("consumer address is empty"))
	} else if len(m.ProducerSignature) == 0 {
		return false, errors.New(fmt.Sprintf("producer signature of agreement is empty"))
	} else if len(m.BlockchainType) == 0 {
		return false, errors.New(fmt.Sprintf("block chain type is empty"))
	}
	return true, nil

}

// This function creates a Metering notification object. Everything but the meter signature is created at this time.
// Once this object is created, the meter hash can be signed and set into the object.
func NewMeteringNotification(meterPolicy policy.Meter, startTime uint64, checkRate uint64, missedChecks uint64, agId string, agHash string, cSig string, cAddr string, pSig string, bcType string) (*MeteringNotification, error) {

	m := new(MeteringNotification)
	m.CurrentTime = uint64(time.Now().Unix())
	m.StartTime = startTime
	m.AgreementId = agId
	m.AgreementHash = agHash
	m.ConsumerSignature = cSig
	m.ConsumerAddress = cAddr
	m.ProducerSignature = pSig
	m.BlockchainType = bcType
	if err := m.calculateAmount(meterPolicy, startTime, checkRate, missedChecks); err != nil {
		return nil, err
	}
	m.meterHash = m.GetMeterHash()

	glog.V(5).Infof("Created Metering Notification: %v", m)

	return m, nil

}

func (m *MeteringNotification) SetConsumerMeterSignature(sig string) {
	m.ConsumerMeterSignature = sig
}

// The persistent form of the Metering notification is nearly identical to the wire form. In fact,
// it is a subset of the wire form, so it should be possible to just unmarshal the wire form
// directly to the persistent form.
func ConvertToPersistent(mnString string) (*persistence.MeteringNotification, error) {
	m := new(persistence.MeteringNotification)
	if err := json.Unmarshal([]byte(mnString), m); err != nil {
		return nil, err
	}
	return m, nil
}

// The persistent form of the metering notification is a subset of the wire form, so the conversion
// to wire form only requires the addition of a few fields.
func ConvertFromPersistent(mn persistence.MeteringNotification, agId string) *MeteringNotification {
	m := new(MeteringNotification)
	m.Amount = mn.Amount
	m.StartTime = mn.StartTime
	m.CurrentTime = mn.CurrentTime
	m.MissedTime = mn.MissedTime
	m.AgreementId = agId
	m.ConsumerMeterSignature = mn.ConsumerMeterSignature
	m.AgreementHash = mn.AgreementHash
	m.ConsumerSignature = mn.ConsumerSignature
	m.ConsumerAddress = mn.ConsumerAddress
	m.ProducerSignature = mn.ProducerSignature
	m.BlockchainType = mn.BlockchainType
	return m
}

// This function returns the stringified hash of the meter notification. This is the thing that
// the consumer signs to produce the consumer meter signature.
func (m *MeteringNotification) GetMeterHash() string {

	if len(m.meterHash) != 0 {
		return m.meterHash
	} else {
		binaryAgreementId, _ := hex.DecodeString(m.AgreementId)

		theMeter := make([]byte, 0, 96)
		theMeter = append(theMeter, toBuffer(m.Amount)...)
		theMeter = append(theMeter, toBuffer(m.CurrentTime)...)
		theMeter = append(theMeter, binaryAgreementId...)

		hash := sha3.Sum256(theMeter)
		return "0x" + hex.EncodeToString(hash[:])
	}
}

// This is an internal function used to calculate the amount of tokens to send in the notification message. The
// results of the calculation are set directly onto the object.
//
// The amount is the full amount earned since the agreement started.
func (m *MeteringNotification) calculateAmount(meterPolicy policy.Meter, startTime uint64, checkRate uint64, missedChecks uint64) error {

	normalize := map[string]float64{"min": 1.0, "hour": 60.0, "day": 1440.0}

	// Find the number of mins per check for data
	minPerCheck := float64(checkRate) / 60.0

	// Find the amount of missed time
	missedDataMin := float64(missedChecks) * minPerCheck

	// Find the number of mins since the agreement was made minus the missed data time
	agreementDurationMins := (float64(m.CurrentTime-startTime) / 60.0) - missedDataMin

	// Find the payment rate per minute
	paymentPerMin := float64(meterPolicy.Tokens) / normalize[meterPolicy.PerTimeUnit]

	// Find the total number of tokens to be given
	m.Amount = uint64(agreementDurationMins * paymentPerMin)
	m.MissedTime = uint64(missedDataMin * 60)

	return nil

}

func toBuffer(seq uint64) []byte {
	buf := make([]byte, 32)
	for i := len(buf) - 1; seq != 0; i-- {
		buf[i] = byte(seq & 0xff)
		seq >>= 8
	}
	return buf
}

repository: open-horizon/anax

repo_name: open-horizon/anax