text:
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.

using System;
using System.Buffers;
using System.Buffers.Binary;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using LibObjectFile.Utils;

namespace LibObjectFile
{
    /// <summary>
    /// Base class used for reading / writing an object file to/from a stream.
    /// </summary>
    public abstract class ObjectFileReaderWriter
    {
        private Stream _stream;

        protected ObjectFileReaderWriter(Stream stream)
        {
            Stream = stream ?? throw new ArgumentNullException(nameof(stream));
            Diagnostics = new DiagnosticBag();
            IsLittleEndian = true;
        }

        /// <summary>
        /// Gets or sets stream of the object file.
        /// </summary>
        public Stream Stream
        {
            get => _stream;
            set => _stream = value ?? throw new ArgumentNullException(nameof(value));
        }

        public ulong Offset
        {
            get => (ulong) Stream.Position;
            set => Stream.Position = (long) value;
        }

        public ulong Length
        {
            get => (ulong) Stream.Length;
        }

        /// <summary>
        /// The diagnostics while read/writing this object file.
        /// </summary>
        public DiagnosticBag Diagnostics { get; }

        /// <summary>
        /// Gets a boolean indicating if this reader is operating in read-only mode.
        /// </summary>
        public abstract bool IsReadOnly { get; }

        public bool IsLittleEndian { get; protected set; }

        /// <summary>
        /// Reads from the <see cref="Stream"/> and current position to the specified buffer.
        /// </summary>
        /// <param name="buffer">The buffer to receive the content of the read.</param>
        /// <param name="offset">The offset into the buffer.</param>
        /// <param name="count">The number of bytes to write from the buffer.</param>
        public int Read(byte[] buffer, int offset, int count)
        {
            return Stream.Read(buffer, offset, count);
        }

        /// <summary>
        /// Reads a null terminated UTF8 string from the stream.
        /// </summary>
        /// <returns><c>true</c> if the string was successfully read from the stream, false otherwise</returns>
        public string ReadStringUTF8NullTerminated()
        {
            if (!TryReadStringUTF8NullTerminated(out var text))
            {
                throw new EndOfStreamException();
            }
            return text;
        }

        /// <summary>
        /// Reads a null terminated UTF8 string from the stream.
        /// </summary>
        /// <returns><c>true</c> if the string was successfully read from the stream, false otherwise</returns>
        public bool TryReadStringUTF8NullTerminated(out string text)
        {
            text = null;
            var buffer = ArrayPool<byte>.Shared.Rent((int)128);
            int textLength = 0;
            try
            {
                while (true)
                {
                    // TODO: not efficient to read byte by byte
                    int nextByte = Stream.ReadByte();
                    if (nextByte < 0)
                    {
                        return false;
                    }

                    if (nextByte == 0)
                    {
                        break;
                    }

                    if (textLength > buffer.Length)
                    {
                        var newBuffer = ArrayPool<byte>.Shared.Rent((int)textLength * 2);
                        Array.Copy(buffer, 0, newBuffer, 0, buffer.Length);
                        ArrayPool<byte>.Shared.Return(buffer);
                        buffer = newBuffer;
                    }

                    buffer[textLength++] = (byte)nextByte;
                }

                text = Encoding.UTF8.GetString(buffer, 0, textLength);
            }
            finally
            {
                ArrayPool<byte>.Shared.Return(buffer);
            }

            return true;
        }

        /// <summary>
        /// Reads a null terminated UTF8 string from the stream.
        /// </summary>
        /// <param name="byteLength">The number of bytes to read including the null</param>
        /// <returns>A string</returns>
        public string ReadStringUTF8NullTerminated(uint byteLength)
        {
            if (byteLength == 0) return string.Empty;

            var buffer = ArrayPool<byte>.Shared.Rent((int)byteLength);
            try
            {
                var dataLength = Stream.Read(buffer, 0, (int) byteLength);
                if (dataLength < 0) throw new EndOfStreamException("Unexpected end of stream while trying to read data");

                var byteReadLength = (uint) dataLength;
                if (byteReadLength != byteLength) throw new EndOfStreamException($"Not enough data read {byteReadLength} bytes while expecting to read {byteLength} bytes");

                var isNullTerminated = buffer[byteReadLength - 1] == 0;

                var text = Encoding.UTF8.GetString(buffer, 0, (int) (isNullTerminated ? byteReadLength - 1 : byteReadLength));
                return text;
            }
            finally
            {
                ArrayPool<byte>.Shared.Return(buffer);
            }
        }

        public bool TryReadU8(out byte value)
        {
            value = 0;
            int nextValue = Stream.ReadByte();
            if (nextValue < 0) return false;
            value = (byte)nextValue;

            return true;
        }

        /// <summary>
        /// Read little endian from the stream
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool TryReadU16(out ushort value)
        {
            return TryReadU16(IsLittleEndian, out value);
        }

        public byte ReadU8()
        {
            if (TryReadU8(out var value))
            {
                return value;
            }
            throw new EndOfStreamException();
        }

        public ushort ReadU16()
        {
            if (TryReadU16(out var value))
            {
                return value;
            }
            throw new EndOfStreamException();
        }

        public uint ReadU32()
        {
            if (TryReadU32(out var value))
            {
                return value;
            }
            throw new EndOfStreamException();
        }

        public ulong ReadU64()
        {
            if (TryReadU64(out var value))
            {
                return value;
            }
            throw new EndOfStreamException();
        }

        public bool TryReadU16(bool isLittleEndian, out ushort value)
        {
            value = 0;
            int nextValue = Stream.ReadByte();
            if (nextValue < 0) return false;
            value = (byte)nextValue;

            nextValue = Stream.ReadByte();
            if (nextValue < 0) return false;
            value = (ushort)((nextValue << 8) | (byte)value);

            if (isLittleEndian != BitConverter.IsLittleEndian)
            {
                value = BinaryPrimitives.ReverseEndianness(value);
            }

            return true;
        }

        public unsafe bool TryReadU32(out uint value)
        {
            return TryReadU32(IsLittleEndian, out value);
        }

        public unsafe bool TryReadU32(bool isLittleEndian, out uint value)
        {
            fixed (uint* pBufferInt = &value)
            {
                var span = new Span<byte>((byte*) pBufferInt, sizeof(uint));
                if (Stream.Read(span) != sizeof(uint))
                {
                    return false;
                }

                if (isLittleEndian != BitConverter.IsLittleEndian)
                {
                    value = BinaryPrimitives.ReverseEndianness(value);
                }
            }
            return true;
        }

        public unsafe bool TryReadU64(out ulong value)
        {
            return TryReadU64(IsLittleEndian, out value);
        }

        public unsafe bool TryReadU64(bool isLittleEndian, out ulong value)
        {
            fixed (ulong* pBufferInt = &value)
            {
                var span = new Span<byte>((byte*)pBufferInt, sizeof(ulong));
                if (Stream.Read(span) != sizeof(ulong))
                {
                    return false;
                }

                if (isLittleEndian != BitConverter.IsLittleEndian)
                {
                    value = BinaryPrimitives.ReverseEndianness(value);
                }
            }
            return true;
        }

        public unsafe void WriteU16(bool isLittleEndian, ushort value)
        {
            if (isLittleEndian != BitConverter.IsLittleEndian)
            {
                value = BinaryPrimitives.ReverseEndianness(value);
            }
            var span = new Span<byte>((byte*)&value, sizeof(ushort));
            Stream.Write(span);
        }

        public unsafe void WriteU32(bool isLittleEndian, uint value)
        {
            if (isLittleEndian != BitConverter.IsLittleEndian)
            {
                value = BinaryPrimitives.ReverseEndianness(value);
            }
            var span = new Span<byte>((byte*)&value, sizeof(uint));
            Stream.Write(span);
        }

        public unsafe void WriteU64(bool isLittleEndian, ulong value)
        {
            if (isLittleEndian != BitConverter.IsLittleEndian)
            {
                value = BinaryPrimitives.ReverseEndianness(value);
            }
            var span = new Span<byte>((byte*)&value, sizeof(ulong));
            Stream.Write(span);
        }

        /// <summary>
        /// Writes a null terminated UTF8 string to the stream.
        /// </summary>
        public void WriteStringUTF8NullTerminated(string text)
        {
            if (text == null) throw new ArgumentNullException(nameof(text));

            int byteLength = Encoding.UTF8.GetByteCount(text);
            var buffer = ArrayPool<byte>.Shared.Rent(byteLength + 1);
            try
            {
                Encoding.UTF8.GetBytes(text, 0, text.Length, buffer, 0);
                buffer[byteLength] = 0;
                Stream.Write(buffer, 0, byteLength + 1);
            }
            finally
            {
                ArrayPool<byte>.Shared.Return(buffer);
            }
        }

        /// <summary>
        /// Tries to read an element of type <paramref name="{T}"/> with a specified size.
        /// </summary>
        /// <typeparam name="T">Type of the element to read.</typeparam>
        /// <param name="sizeToRead">Size of the element to read (might be smaller or bigger).</param>
        /// <param name="data">The data read.</param>
        /// <returns><c>true</c> if reading was successful. <c>false</c> otherwise.</returns>
        public unsafe bool TryReadInteger<T>(int sizeToRead, out T data) where T : unmanaged
        {
            if (sizeToRead <= 0) throw new ArgumentOutOfRangeException(nameof(sizeToRead));

            int dataByteCount = sizeof(T);
            int byteRead;

            // If we are requested to read more data than the sizeof(T)
            // we need to read it to an intermediate buffer before transferring it to T data
            if (sizeToRead > dataByteCount)
            {
                var buffer = ArrayPool<byte>.Shared.Rent(sizeToRead);
                var span = new Span<byte>(buffer);
                byteRead = Stream.Read(span);
                data = MemoryMarshal.Cast<byte, T>(span)[0];
                ArrayPool<byte>.Shared.Return(buffer);
            }
            else
            {
                // Clear the data if the size requested is less than the expected struct to read
                if (sizeToRead < dataByteCount)
                {
                    data = default;
                }

                fixed (void* pData = &data)
                {
                    var span = new Span<byte>(pData, sizeToRead);
                    byteRead = Stream.Read(span);
                }
            }
            return byteRead == sizeToRead;
        }

        /// <summary>
        /// Reads from the current <see cref="Stream"/> <see cref="size"/> bytes and return the data as
        /// a <see cref="SliceStream"/> if <see cref="IsReadOnly"/> is <c>false</c> otherwise as a
        /// <see cref="MemoryStream"/>.
        /// </summary>
        /// <param name="size">Size of the data to read.</param>
        /// <returns>A <see cref="SliceStream"/> if <see cref="IsReadOnly"/> is <c>false</c> otherwise as a
        /// <see cref="MemoryStream"/>.</returns>
        public Stream ReadAsStream(ulong size)
        {
            if (IsReadOnly)
            {
                var stream = ReadAsSliceStream(size);
                Stream.Position += (long)size;
                return stream;
            }

            return ReadAsMemoryStream(size);
        }

        /// <summary>
        /// Writes to the <see cref="Stream"/> and current position from the specified buffer.
        /// </summary>
        /// <param name="buffer">The buffer to write the content from.</param>
        /// <param name="offset">The offset into the buffer.</param>
        /// <param name="count">The number of bytes to read from the buffer and write to the stream.</param>
        public void Write(byte[] buffer, int offset, int count)
        {
            Stream.Write(buffer, offset, count);
        }

        /// <summary>
        /// Writes an element of type <paramref name="{T}"/> to the stream.
        /// </summary>
        /// <typeparam name="T">Type of the element to read.</typeparam>
        /// <param name="data">The data to write.</param>
        public unsafe void Write<T>(in T data) where T : unmanaged
        {
            fixed (void* pData = &data)
            {
                var span = new ReadOnlySpan<byte>(pData, sizeof(T));
                Stream.Write(span);
            }
        }

        /// <summary>
        /// Writes from the specified stream to the current <see cref="Stream"/> of this instance.
        /// The position of the input stream is set to 0 before writing and reset back to 0 after writing.
        /// </summary>
        /// <param name="inputStream">The input stream to read from and write to <see cref="Stream"/></param>
        /// <param name="size">The amount of data to read from the input stream (if == 0, by default, it will read the entire input stream)</param>
        /// <param name="bufferSize">The size of the intermediate buffer used to transfer the data.</param>
        public void Write(Stream inputStream, ulong size = 0, int bufferSize = 4096)
        {
            if (inputStream == null) throw new ArgumentNullException(nameof(inputStream));
            if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize));

            inputStream.Position = 0;
            size = size == 0 ? (ulong)inputStream.Length : size;
            var buffer = ArrayPool<byte>.Shared.Rent(bufferSize);

            while (size != 0)
            {
                var sizeToRead = size >= (ulong)buffer.Length ? buffer.Length : (int)size;
                var sizeRead = inputStream.Read(buffer, 0, sizeToRead);
                if (sizeRead <= 0) break;

                Stream.Write(buffer, 0, sizeRead);
                size -= (ulong)sizeRead;
            }

            inputStream.Position = 0;
            if (size != 0)
            {
                throw new InvalidOperationException("Unable to write stream entirely");
            }
        }

        private SliceStream ReadAsSliceStream(ulong size)
        {
            return new SliceStream(Stream, Stream.Position, (long)size);
        }

        private MemoryStream ReadAsMemoryStream(ulong size)
        {
            var memoryStream = new MemoryStream((int)size);
            if (size == 0) return memoryStream;

            memoryStream.SetLength((long)size);

            var buffer = memoryStream.GetBuffer();
            while (size != 0)
            {
                var lengthToRead = size >= int.MaxValue ? int.MaxValue : (int)size;
                var lengthRead = Stream.Read(buffer, 0, lengthToRead);
                if (lengthRead < 0) break;
                if ((uint)lengthRead >= size)
                {
                    size -= (uint)lengthRead;
                }
                else
                {
                    break;
                }
            }
            return memoryStream;
        }
    }
}

repository: jangocheng/LibObjectFile

repo_name: jangocheng/LibObjectFile


text:
// Copyright 2018 GRAIL, Inc. All rights reserved.
// Use of this source code is governed by the Apache-2.0
// license that can be found in the LICENSE file.

//go:build !unit
// +build !unit

package s3file

import (
	"context"
	"crypto/md5"
	"crypto/sha256"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"runtime/debug"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	awsrequest "github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/service/s3/s3iface"
	"github.com/grailbio/base/errors"
	"github.com/grailbio/base/file"
	"github.com/grailbio/base/file/internal/s3bufpool"
	"github.com/grailbio/base/file/internal/testutil"
	"github.com/grailbio/base/file/s3file/s3transport"
	"github.com/grailbio/base/log"
	"github.com/grailbio/base/retry"
	"github.com/grailbio/testutil/assert"
	"github.com/grailbio/testutil/s3test"
)

var (
	s3BucketFlag = flag.String("s3-bucket", "", "If set, run a unittest against a real S3 bucket named in this flag")
	s3DirFlag    = flag.String("s3-dir", "", "S3 directory under -s3-bucket used by some unittests")
)

type failingContentAt struct {
	prob        float64 // probability of failing requests
	content     []byte
	failWithErr error

	randMu sync.Mutex
	rand   *rand.Rand
}

func doReadAt(src []byte, off64 int64, dest []byte) (int, error) {
	off := int(off64)
	remaining := len(src) - off
	if remaining <= 0 {
		return 0, io.EOF
	}
	if len(dest) < remaining {
		remaining = len(dest)
	}
	copy(dest, src[off:])
	return remaining, nil
}

func doWriteAt(src []byte, off64 int64, dest *[]byte) (int, error) {
	off := int(off64)
	if len(*dest) < off+len(src) {
		tmp := make([]byte, off+len(src))
		copy(tmp, *dest)
		*dest = tmp
	}
	copy((*dest)[off:], src)
	return len(src), nil
}

func (c *failingContentAt) ReadAt(p []byte, off64 int64) (int, error) {
	c.randMu.Lock()
	pr := c.rand.Float64()
	c.randMu.Unlock()
	if pr < c.prob {
		return 0, c.failWithErr
	}
	n := len(p)
	if n > 1 {
		c.randMu.Lock()
		n = 1 + c.rand.Intn(n-1)
		c.randMu.Unlock()
	}
	return doReadAt(c.content, off64, p[:n])
}

func (c *failingContentAt) WriteAt(p []byte, off64 int64) (int, error) {
	return doWriteAt(p, off64, &c.content)
}

func (c *failingContentAt) Size() int64 {
	return int64(len(c.content))
}

func (c *failingContentAt) Checksum() string {
	return fmt.Sprintf("%x", md5.Sum(c.content))
}

type pausingContentAt struct {
	ready   chan bool
	content []byte
}

// ReadAt implements io.ReaderAt.
func (c *pausingContentAt) ReadAt(p []byte, off64 int64) (int, error) {
	<-c.ready
	return doReadAt(c.content, off64, p)
}

// WriteAt implements io.WriterAt
func (c *pausingContentAt) WriteAt(p []byte, off64 int64) (int, error) {
	return doWriteAt(p, off64, &c.content)
}

// Size returns the size of the fake content.
func (c *pausingContentAt) Size() int64 {
	return int64(len(c.content))
}

func (c *pausingContentAt) Checksum() string {
	return fmt.Sprintf("%x", md5.Sum(c.content))
}

func newImpl(clients ...s3iface.S3API) *s3Impl {
	return &s3Impl{
		clientsForAction: func(_ context.Context, _, _, _ string) ([]s3iface.S3API, error) {
			return clients, nil
		},
	}
}

func newClient(t *testing.T) *s3test.Client { return s3test.NewClient(t, "b") }
func errorClient(t *testing.T, err error) s3iface.S3API {
	c := s3test.NewClient(t, "b")
	c.Err = func(api string, input interface{}) error {
		return err
	}
	return c
}

func TestS3(t *testing.T) {
	ctx := context.Background()
	impl := newImpl(
		errorClient(t, awserr.New(
			"", // TODO(swami): Use an AWS error code that represents a permission error.
			"test permission error",
			nil,
		)),
		newClient(t),
	)
	testutil.TestStandard(ctx, t, impl, "s3://b/dir")
	t.Run("readat", func(t *testing.T) {
		testutil.TestConcurrentOffsetReads(ctx, t, impl, "s3://b/dir/readats.txt")
	})
}

func TestS3WithRetries(t *testing.T) {
	tearDown := setZeroBackoffPolicy()
	defer tearDown()

	ctx := context.Background()
	for iter := 0; iter < 50; iter++ {
		randIntsC := make(chan int)
		go func() {
			r := rand.New(rand.NewSource(int64(iter)))
			for {
				randIntsC <- r.Intn(20)
			}
		}()
		client := newClient(t)
		client.Err = func(api string, input interface{}) error {
			switch <-randIntsC {
			case 0:
				return awserr.New(awsrequest.ErrCodeSerialization, "injected serialization failure", nil)
			case 1:
				return awserr.New("RequestError", "send request failed", readConnResetError{})
			}
			return nil
		}
		impl := newImpl(client)
		testutil.TestStandard(ctx, t, impl, "s3://b/dir")
		t.Run("readat", func(t *testing.T) {
			testutil.TestConcurrentOffsetReads(ctx, t, impl, "s3://b/dir/readats.txt")
		})
	}
}

// WriteFile creates a file with the given contents. Path should be of form
// s3://bucket/key.
func writeFile(ctx context.Context, t *testing.T, impl file.Implementation, path, data string) {
	f, err := impl.Create(ctx, path)
	assert.NoError(t, err)
	_, err = f.Writer(ctx).Write([]byte(data))
	assert.NoError(t, err)
	assert.NoError(t, f.Close(ctx))
}
func TestListBucketRoot(t *testing.T) {
	ctx := context.Background()
	impl := newImpl(newClient(t))
	writeFile(ctx, t, impl, "s3://b/0.txt", "data")

	l := impl.List(ctx, "s3://b", true)
	assert.True(t, l.Scan(), "err: %v", l.Err())
	assert.EQ(t, "s3://b/0.txt", l.Path())
	assert.False(t, l.Scan())
	assert.NoError(t, l.Err())
}

type readConnResetError struct{}

func (c readConnResetError) Temporary() bool { return false }
func (c readConnResetError) Error() string   { return "read: connection reset" }

func TestErrors(t *testing.T) {
	ctx := context.Background()
	impl := newImpl(
		errorClient(t,
			awserr.New("", // TODO(swami): Use an AWS error code that represents a permission error.
				fmt.Sprintf("test permission error: %s", string(debug.Stack())),
				nil,
			),
		),
	)

	_, err := impl.Create(ctx, "s3://b/junk0.txt")
	assert.Regexp(t, err, "test permission error")

	_, err = impl.Stat(ctx, "s3://b/junk0.txt")
	assert.Regexp(t, err, "test permission error")

	l := impl.List(ctx, "s3://b/foo", true)
	assert.False(t, l.Scan())
	assert.Regexp(t, l.Err(), "test permission error")
}

func TestTransientErrors(t *testing.T) {
	impl := newImpl(errorClient(t, awserr.New("RequestError", "send request failed", readConnResetError{})))
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	_, err := impl.Stat(ctx, "s3://b/junk0.txt")
	assert.True(t, errors.Is(errors.Canceled, err), "expected cancellation")

	ctx, cancel = context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()
	_, err = impl.Stat(ctx, "s3://b/junk0.txt")
	assert.Regexp(t, err, "ran out of time while waiting")
}

func TestWriteRetryAfterError(t *testing.T) {
	tearDown := setZeroBackoffPolicy()
	defer tearDown()

	client := newClient(t)
	impl := newImpl(client)
	ctx := context.Background()
	for i := 0; i < 10; i++ {
		r := rand.New(rand.NewSource(0))
		client.Err = func(api string, input interface{}) error {
			if r.Intn(3) == 0 {
				fmt.Printf("write: api %s\n", api)
				return awserr.New(awsrequest.ErrCodeSerialization, "test failure", nil)
			}
			return nil
		}
		writeFile(ctx, t, impl, "s3://b/0.txt", "data")
	}
}

func TestReadRetryAfterError(t *testing.T) {
	for errIdx, failWithErr := range []error{
		fmt.Errorf("failingContentAt synthetic error"),
		readConnResetError{},
	} {
		t.Run(fmt.Sprintf("error_%d", errIdx), func(t *testing.T) {
			tearDown := setZeroBackoffPolicy()
			defer tearDown()

			client := newClient(t)
			setContent := func(path string, prob float64, data string) {
				c := &failingContentAt{
					prob:        prob,
					rand:        rand.New(rand.NewSource(0)),
					content:     []byte(data),
					failWithErr: failWithErr,
				}
				checksum := sha256.Sum256(c.content)
				client.SetFileContentAt(path, c, fmt.Sprintf("%x", checksum[:]))
			}

			var contents string
			{
				l := []string{}
				for i := 0; i < 1000; i++ {
					l = append(l, fmt.Sprintf("D%d", i))
				}
				contents = strings.Join(l, ",")
			}
			// Exercise parallel reading including partial last chunk.
			tearDownRCB := setReadChunkBytes()
			defer tearDownRCB()

			assert.GT(t, len(contents)%ReadChunkBytes(), 0)

			impl := newImpl(client)
			ctx := context.Background()

			setContent("junk0.txt", 0.3, contents)
			for i := 0; i < 10; i++ {
				f, err := impl.Open(ctx, "b/junk0.txt")
				assert.NoError(t, err)
				r := f.Reader(ctx)
				data, err := ioutil.ReadAll(r)
				assert.NoError(t, err)
				assert.EQ(t, contents, string(data))
				assert.NoError(t, f.Close(ctx))
			}

			// Simulate exhausting all allowed retries. Since the number of retries is unrestricted,
			// the request is capped by MaxRetryDuration. To avoid a flaky time dependency, instead
			// of using an actual deadline we just cancel the context.
			tearDown = setFakeWithDeadline()
			defer tearDown()
			setContent("junk1.txt", 1.0 /*fail everything*/, contents)
			{
				f, err := impl.Open(ctx, "b/junk1.txt")
				assert.NoError(t, err)
				r := f.Reader(ctx)
				_, err = ioutil.ReadAll(r)
				assert.Regexp(t, err, failWithErr.Error())
				assert.NoError(t, f.Close(ctx))
			}
		})
	}
}

func TestRetryWhenNotFound(t *testing.T) {
	client := s3test.NewClient(t, "b")

	impl := newImpl(client)

	ctx := context.Background()
	// By default, there is no retry.
	_, err := impl.Open(ctx, "s3://b/file.txt")
	assert.Regexp(t, err, "NoSuchKey")

	doneCh := make(chan bool)
	go func() {
		_, err := impl.Open(ctx, "s3://b/file.txt", file.Opts{RetryWhenNotFound: true})
		assert.NoError(t, err)
		doneCh <- true
	}()
	time.Sleep(1 * time.Second)
	select {
	case <-doneCh:
		t.Fatal("should not reach here")
	default:
	}
	writeFile(ctx, t, impl, "s3://b/file.txt", "data")
	fmt.Println("wrote file")
	<-doneCh
}

func TestCancellation(t *testing.T) {
	client := s3test.NewClient(t, "b")

	setContent := func(path, data string) *pausingContentAt {
		c := &pausingContentAt{ready: make(chan bool, 1), content: []byte(data)}
		checksum := sha256.Sum256(c.content)
		client.SetFileContentAt(path, c, fmt.Sprintf("%x", checksum[:]))
		return c
	}
	c0 := setContent("test0.txt", "hello")
	_ = setContent("test1.txt", "goodbye")

	impl := newImpl(client)
	{
		c0.ready <- true
		// Reading c0 completes immediately.
		ctx := context.Background()
		f, err := impl.Open(ctx, "s3://b/test0.txt")
		assert.NoError(t, err)
		r := f.Reader(ctx)
		data, err := ioutil.ReadAll(r)
		assert.NoError(t, err)
		assert.EQ(t, "hello", string(data))
		assert.NoError(t, f.Close(ctx))
	}
	{
		// Reading c1 will block.
		f, err := impl.Open(context.Background(), "s3://b/test1.txt")
		assert.NoError(t, err)
		ctx, cancel := context.WithTimeout(context.Background(), time.Second)
		defer cancel()
		r := f.Reader(ctx)
		_, err = ioutil.ReadAll(r)
		assert.True(t, errors.Is(errors.Canceled, err), "expected cancellation")
		assert.True(t, errors.Is(errors.Canceled, f.Close(ctx)), "expected cancellation")
	}
}

func testOverwriteWhileReading(t *testing.T, impl file.Implementation, pathPrefix string) {
	ctx := context.Background()
	path := pathPrefix + "/test.txt"
	writeFile(ctx, t, impl, path, "test0")
	f, err := impl.Open(ctx, path)
	assert.NoError(t, err)

	r := f.Reader(ctx)
	data, err := ioutil.ReadAll(r)
	assert.NoError(t, err)
	assert.EQ(t, "test0", string(data))

	_, err = r.Seek(0, io.SeekStart)
	assert.NoError(t, err)

	writeFile(ctx, t, impl, path, "test0")

	data, err = ioutil.ReadAll(r)
	assert.NoError(t, err)
	assert.EQ(t, "test0", string(data))

	_, err = r.Seek(0, io.SeekStart)
	assert.NoError(t, err)
	writeFile(ctx, t, impl, path, "test1")
	_, err = ioutil.ReadAll(r)
	assert.True(t, errors.Is(errors.Precondition, err), "err=%v", err)
}

func TestWriteLargeFile(t *testing.T) {
	// Reduce the upload chunk size to issue concurrent upload requests to S3.
	oldUploadPartSize := UploadPartSize
	UploadPartSize = 128
	defer func() {
		UploadPartSize = oldUploadPartSize
	}()

	ctx := context.Background()
	impl := newImpl(s3test.NewClient(t, "b"))
	path := "s3://b/test.txt"
	f, err := impl.Create(ctx, path)
	assert.NoError(t, err)
	r := rand.New(rand.NewSource(0))
	var want []byte
	const iters = 400
	for i := 0; i < iters; i++ {
		n := r.Intn(1024) + 100
		data := make([]byte, n)
		n, err := r.Read(data)
		assert.EQ(t, n, len(data))
		assert.NoError(t, err)
		n, err = f.Writer(ctx).Write(data)
		assert.EQ(t, n, len(data))
		assert.NoError(t, err)
		want = append(want, data...)
	}
	assert.NoError(t, f.Close(ctx))

	// Read the file back and verify contents.
	f, err = impl.Open(ctx, path)
	assert.NoError(t, err)
	got := make([]byte, len(want))
	n, _ := f.Reader(ctx).Read(got)
	assert.EQ(t, n, len(want))
	assert.EQ(t, got, want)
	assert.NoError(t, f.Close(ctx))
}

func TestOverwriteWhileReading(t *testing.T) {
	impl := newImpl(s3test.NewClient(t, "b"))
	testOverwriteWhileReading(t, impl, "s3://b/test")
}

func TestNotExist(t *testing.T) {
	impl := newImpl(s3test.NewClient(t, "b"))
	ctx := context.Background()
	// The s3test client fails tests for requests that attempt to
	// access buckets other than the one specified, so we can
	// test only missing keys here.
	_, err := impl.Open(ctx, "b/notexist")
	assert.True(t, errors.Is(errors.NotExist, err))
}

func realBucketProviderOrSkip(t *testing.T) SessionProvider {
	if *s3BucketFlag == "" {
		t.Skip("Skipping. Set -s3-bucket to run the test.")
	}
	return NewDefaultProvider(
		aws.NewConfig().WithHTTPClient(s3transport.DefaultClient()),
	)
}

func TestOverwriteWhileReadingAWS(t *testing.T) {
	provider := realBucketProviderOrSkip(t)
	impl := NewImplementation(provider, Options{})
	testOverwriteWhileReading(t, impl, fmt.Sprintf("s3://%s/tmp/testoverwrite", *s3BucketFlag))
}

func TestPresignRequestsAWS(t *testing.T) {
	provider := realBucketProviderOrSkip(t)
	impl := NewImplementation(provider, Options{})
	ctx := context.Background()
	const content = "file for testing presigned URLs\n"
	path := fmt.Sprintf("s3://%s/tmp/testpresigned", *s3BucketFlag)

	// Write the dummy file.
	url, err := impl.Presign(ctx, path, "PUT", time.Minute)
	if err != nil {
		t.Fatal(err)
	}
	req, err := http.NewRequest(http.MethodPut, url, strings.NewReader(content))
	if err != nil {
		t.Fatal(err)
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	resp.Body.Close()

	// Read the dummy file.
	url, err = impl.Presign(ctx, path, "GET", time.Minute)
	if err != nil {
		t.Fatal(err)
	}
	resp, err = http.Get(url)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatal(err)
	}
	if content != string(respBytes) {
		t.Errorf("got: %q, want: %q", string(respBytes), content)
	}

	// Delete the dummy file.
	url, err = impl.Presign(ctx, path, "DELETE", time.Minute)
	if err != nil {
		t.Fatal(err)
	}
	req, err = http.NewRequest(http.MethodDelete, url, strings.NewReader(""))
	if err != nil {
		t.Fatal(err)
	}
	resp, err = http.DefaultClient.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	resp.Body.Close()
	if _, err := impl.Stat(ctx, path); !errors.Is(errors.NotExist, err) {
		t.Errorf("got: %v\nwant an error of kind NotExist", err)
	}
}

func TestAWS(t *testing.T) {
	provider := realBucketProviderOrSkip(t)
	ctx := context.Background()
	impl := NewImplementation(provider, Options{})
	testutil.TestStandard(ctx, t, impl, "s3://"+*s3BucketFlag+"/tmp")
	t.Run("readat", func(t *testing.T) {
		testutil.TestConcurrentOffsetReads(ctx, t, impl, "s3://"+*s3BucketFlag+"/tmp")
	})
}

func TestConcurrentUploadsAWS(t *testing.T) {
	provider := realBucketProviderOrSkip(t)
	impl := NewImplementation(provider, Options{})

	if *s3DirFlag == "" {
		t.Skip("Skipping. Set -s3-bucket and -s3-dir to run the test.")
	}
	path := fmt.Sprintf("s3://%s/%s/test.txt", *s3BucketFlag, *s3DirFlag)
	ctx := context.Background()

	upload := func() {
		f, err := impl.Create(ctx, path, file.Opts{IgnoreNoSuchUpload: true})
		if err != nil {
			log.Panic(err)
		}
		_, err = f.Writer(ctx).Write([]byte("hello"))
		if err != nil {
			log.Panic(err)
		}
		if err := f.Close(ctx); err != nil {
			log.Panic(err)
		}
	}

	wg := sync.WaitGroup{}
	n := uint64(0)
	for i := 0; i < 4000; i++ {
		wg.Add(1)
		go func() {
			upload()
			if x := atomic.AddUint64(&n, 1); x%100 == 0 {
				log.Printf("%d done", x)
			}
			wg.Done()
		}()
	}
	wg.Wait()
}

func ExampleParseURL() {
	scheme, bucket, key, err := ParseURL("s3://grail-bucket/dir/file")
	fmt.Printf("scheme: %s, bucket: %s, key: %s, err: %v\n", scheme, bucket, key, err)
	scheme, bucket, key, err = ParseURL("s3://grail-bucket/dir/")
	fmt.Printf("scheme: %s, bucket: %s, key: %s, err: %v\n", scheme, bucket, key, err)
	scheme, bucket, key, err = ParseURL("s3://grail-bucket")
	fmt.Printf("scheme: %s, bucket: %s, key: %s, err: %v\n", scheme, bucket, key, err)
	// Output:
	// scheme: s3, bucket: grail-bucket, key: dir/file, err: <nil>
	// scheme: s3, bucket: grail-bucket, key: dir/, err: <nil>
	// scheme: s3, bucket: grail-bucket, key: , err: <nil>
}

func setZeroBackoffPolicy() (tearDown func()) {
	oldPolicy := BackoffPolicy
	BackoffPolicy = retry.Backoff(0, 0, 1.0)
	return func() { BackoffPolicy = oldPolicy }
}

func setReadChunkBytes() (tearDown func()) {
	old := s3bufpool.BufBytes
	s3bufpool.SetBufSize(100)
	return func() { s3bufpool.SetBufSize(old) }
}

func setFakeWithDeadline() (tearDown func()) {
	old := WithDeadline
	WithDeadline = func(ctx context.Context, deadline time.Time) (context.Context, context.CancelFunc) {
		ctx, cancel := context.WithDeadline(ctx, deadline)
		cancel()
		return ctx, cancel
	}
	return func() { WithDeadline = old }
}

repository: jcharum/base

license_type: permissive

repo_name: jcharum/base

branch_name: refs/heads/master

extension: go


text:
/*
      求两个数最大公约数
*/
package main

import "fmt"

//每次循环交换两个位置值，对两个整数求模并交换值。
func gcd(x, y int) int {
      for y != 0 {
        x, y = y, x %y
      }
      return x
}
func main() {
    fmt.Println(gcd(12, 18))
}

license: MIT

repository: PachVerb/go-golong

repo_name: PachVerb/go-golong


text:
package tmallservice

import (
	"github.com/bububa/opentaobao/core"
	"github.com/bububa/opentaobao/model/tmallservice"
)

// TmallServicecenterWorkcardSuspend 工单挂起
// tmall.servicecenter.workcard.suspend
//
// 工单挂起
func TmallServicecenterWorkcardSuspend(clt *core.SDKClient, req *tmallservice.TmallServicecenterWorkcardSuspendAPIRequest, session string) (*tmallservice.TmallServicecenterWorkcardSuspendAPIResponse, error) {
	var resp tmallservice.TmallServicecenterWorkcardSuspendAPIResponse
	err := clt.Post(req, &resp, session)
	if err != nil {
		return nil, err
	}
	return &resp, nil
}

repository: bububa/opentaobao

repo_name: bububa/opentaobao

branch_name: refs/heads/main

gha_language: Go


text:
require wpewebkit.inc
require conf/include/devupstream.inc

SRC_URI = "https://wpewebkit.org/releases/${BPN}-${PV}.tar.xz"

SRC_URI[sha256sum] = "785d83b99cd45cedb7c4f1f697db773a5a81eb0a42aeeafa3c623053f6fde87a"

DEPENDS += " libwpe"
RCONFLICTS_${PN} = "libwpe (< 1.2) wpebackend-fdo (< 1.2)"

SRC_URI_class-devupstream = "git://git.webkit.org/WebKit.git;branch=master"
SRCREV_class-devupstream = "4d2d7cbbdbfef826e5f35107e71d908a87a86e92"

repository: matthewbauer/meta-webkit

repo_name: matthewbauer/meta-webkit

extension: bb


text:
// Copyright (c) 2017 - The Event Horizon authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package waiter

import (
	"context"
	"errors"
	"reflect"
	"testing"

	"time"

	eh "github.com/looplab/eventhorizon"
	"github.com/looplab/eventhorizon/mocks"
	"github.com/looplab/eventhorizon/uuid"
)

func TestEventHandler(t *testing.T) {
	h := NewEventHandler()

	if err := h.HandleEvent(context.Background(), nil); !errors.Is(err, eh.ErrMissingEvent) {
		t.Error("there should be a missing event error:", err)
	}

	// Event should match when waiting.
	timestamp := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
	expectedEvent := eh.NewEvent(mocks.EventType, nil, timestamp,
		eh.ForAggregate(mocks.AggregateType, uuid.New(), 1))

	go func() {
		time.Sleep(time.Millisecond)

		if err := h.HandleEvent(context.Background(), expectedEvent); err != nil {
			t.Error("there should be no error:", err)
		}
	}()

	l := h.Listen(func(event eh.Event) bool {
		if event.EventType() == mocks.EventType {
			return true
		}

		return false
	})
	defer l.Close()

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()

	event, err := l.Wait(ctx)
	if err != nil {
		t.Error(err)
	}

	if !reflect.DeepEqual(event, expectedEvent) {
		t.Error("the event should be correct:", event)
	}

	// Other events should not match.
	otherEvent := eh.NewEvent(mocks.EventOtherType, nil, timestamp,
		eh.ForAggregate(mocks.AggregateType, uuid.New(), 1))

	go func() {
		time.Sleep(time.Millisecond)

		if err := h.HandleEvent(context.Background(), otherEvent); err != nil {
			t.Error("there should be no error:", err)
		}
	}()

	ctx, cancel = context.WithTimeout(context.Background(), 10*time.Millisecond)
	defer cancel()

	deadlineExceededErr := context.DeadlineExceeded

	event, err = l.Wait(ctx)
	if !errors.Is(err, deadlineExceededErr) {
		t.Error("there should be a context deadline exceeded error")
	}

	if event != nil {
		t.Error("the event should be nil:", event)
	}
}

repository: looplab/eventhorizon

repo_name: looplab/eventhorizon


text:
package main

import (
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"log"
	"os"

	"github.com/davecgh/go-spew/spew"

	"github.com/ghostiam/binstruct"
)

// Portable Network Graphics (PNG) Specification: https://www.w3.org/TR/PNG/
func main() {
	file, err := os.Open("sample.png")
	if err != nil {
		log.Fatal(err)
	}

	var png PNG
	decoder := binstruct.NewDecoder(file, binary.BigEndian)
	// decoder.SetDebug(true)
	err = decoder.Decode(&png)
	if err != nil {
		log.Fatal(err)
	}

	spew.Dump(png)
}

type PNG struct {
	Header [8]byte // Magic: 0x89 0x50 0x4E 0x47 0x0D 0x0A 0x1A 0x0A
	IHDR   IHDR
	Chunks []Chunk `bin:"ReadChunks"`
}

func (png *PNG) ReadChunks(r binstruct.Reader) error {
	for {
		var c Chunk
		err := r.Unmarshal(&c)
		if errors.Is(err, io.EOF) {
			return nil
		}
		if err != nil {
			return fmt.Errorf("failed read png chunk: %w", err)
		}

		png.Chunks = append(png.Chunks, c)
	}
}

// https://www.w3.org/TR/PNG/#11IHDR
type IHDR struct {
	Len  int32
	Type string `bin:"len:4"`
	Data IHDRData
	CRC  [4]byte
}

type IHDRData struct {
	Width             int32
	Height            int32
	BitDepth          int8
	ColorType         PNGColorType
	CompressionMethod int8
	FilterMethod      int8
	InterlaceMethod   int8
}

type PNGColorType int8

func (t PNGColorType) String() string {
	colors := [...]string{
		"Greyscale",            // 0
		"Invalid",              // 1
		"Truecolor",            // 2
		"Indexed",              // 3
		"Greyscale with alpha", // 4
		"Invalid",              // 5
		"Truecolor with alpha", // 6
	}
	return colors[t]
}

type Chunk struct {
	Len  int32
	Type string      `bin:"len:4"`
	Data interface{} `bin:"ReadChunkData"`
	CRC  [4]byte
}

func (c *Chunk) ReadChunkData(r binstruct.Reader) (interface{}, error) {
	switch c.Type {
	case "PLTE": // https://www.w3.org/TR/PNG/#11PLTE
		v := PaletteData{DataLen: c.Len}
		err := r.Unmarshal(&v)
		return v, err
	case "cHRM": // https://www.w3.org/TR/PNG/#11cHRM
		var v ChromaticData
		err := r.Unmarshal(&v)
		return v, err
	case "gAMA": // https://www.w3.org/TR/PNG/#11gAMA
		gamma, err := r.ReadInt32()
		return GammaData(gamma), err
		// case "sRGB": // https://www.w3.org/TR/PNG/#11sRGB
		// case "bKGD": // https://www.w3.org/TR/PNG/#11bKGD
	case "pHYs": // https://www.w3.org/TR/PNG/#11pHYs
		var v PhysicalPixelData
		err := r.Unmarshal(&v)
		return v, err

		// case "tIME": // https://www.w3.org/TR/PNG/#11tIME
	case "iTXt": // https://www.w3.org/TR/PNG/#11iTXt
		v := InternationalTextData{DataLen: c.Len}
		err := r.Unmarshal(&v)
		return v, err
		// case "tEXt": // https://www.w3.org/TR/PNG/#11tEXt
		// case "zTXt": // https://www.w3.org/TR/PNG/#11zTXt
	default:
		// IDAT, IEND and others
		// read raw
		_, b, err := r.ReadBytes(int(c.Len))
		return RawData(b), err
	}
}

type RawData []byte

func (RawData) String() string {
	return "<skip>"
}

type PaletteData struct {
	DataLen int32 `bin:"-"` // Helper
	Entries []RGB `bin:"len:DataLen/3"`
}

type RGB struct {
	R int8
	G int8
	B int8
}

type ChromaticData struct {
	White Point
	Red   Point
	Green Point
	Blue  Point
}

type Point struct {
	X int32
	Y int32
}

type GammaData int32

type PhysicalPixelData struct {
	Point
	Unit int8
}

type InternationalTextData struct {
	DataLen           int32  `bin:"-"` // Helper
	Keyword           string `bin:"NullTerminatedString"`
	CompressionFlag   byte
	CompressionMethod byte
	LanguageTag       string `bin:"NullTerminatedString"`
	TranslatedKeyword string `bin:"NullTerminatedString"`
	Text              string `bin:"len:DataLen-2"` // DataLen - CompressionFlag - CompressionMethod
}

func (d *InternationalTextData) NullTerminatedString(r binstruct.Reader) (string, error) {
	var b []byte

	var readCount int32
	for {
		readByte, err := r.ReadByte()
		if errors.Is(err, io.EOF) {
			break
		}
		if err != nil {
			return "", err
		}

		readCount++

		if readByte == 0x00 {
			break
		}

		b = append(b, readByte)
	}

	d.DataLen -= readCount

	return string(b), nil
}

repository: ghostiam/binstruct

repo_name: ghostiam/binstruct

gha_license_id: MIT


text:
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Game.Beatmaps.Timing;
using osu.Game.Database;

namespace osu.Game.Modes.Taiko.Objects
{
    public class BarLine
    {
        /// <summary>
        /// The start time of the control point this bar line represents.
        /// </summary>
        public double StartTime;

        /// <summary>
        /// The time to scroll in the bar line.
        /// </summary>
        public double PreEmpt;

        public void ApplyDefaults(TimingInfo timing, BeatmapDifficulty difficulty)
        {
            PreEmpt = 600 / (timing.SliderVelocityAt(StartTime) * difficulty.SliderMultiplier) * 1000;
        }
    }
}

repository: Xenocidel/osu

repo_name: Xenocidel/osu

extension: cs


text:
package main

import "fmt"

func reverseArray__float64(a []float64) {
	i := 0
	u := len(a) - 1
	for i < u {
		a[i], a[u] = a[u], a[i]
		i, u = i+1, u-1
	}
}
func reverseArray__int(a []int) {
	i := 0
	u := len(a) - 1
	for i < u {
		a[i], a[u] = a[u], a[i]
		i, u = i+1, u-1
	}
}
func reverseArray__string(a []string) {
	i := 0
	u := len(a) - 1
	for i < u {
		a[i], a[u] = a[u], a[i]
		i, u = i+1, u-1
	}
}

func main() {
	ia := []int{1, 2, 3}
	reverseArray__int(ia)
	fmt.Println(ia)

	sa := []string{"a", "b", "c"}
	reverseArray__string(sa)
	fmt.Println(sa)

	ra := []float64{1.1, 2.2, 3.3}
	reverseArray__float64(ra)
	fmt.Println(ra)
}

repository: mandolyte/fo-experiments

repo_name: mandolyte/fo-experiments


text:
using System;
using System.Diagnostics.CodeAnalysis;
using Xunit;

namespace BinaryFog.NameParser.Tests {

	/// <summary>
	///This is a test class for FullNameParserTest and is intended
	///to contain all FullNameParserTest Unit Tests
	///</summary>
	public class InitialAsMiddleNameTests
    {
		[Fact]
		public void Parse_MrJonADOTvanderWaalJr() {
			var fullName = "Mr. Jon A. van der Waal Jr.";
			var target = new FullNameParser(fullName);
			target.Parse();

			Assert.Equal("Jon", target.FirstName);
			Assert.Equal("van der Waal", target.LastName);
            Assert.Equal("A.", target.MiddleName);
            Assert.Equal("Mr.", target.Title);
            Assert.Equal("Jr.", target.Suffix);

        }

        [Fact]
        public void Parse_MrJonADOTWaalJr()
        {
            var fullName = "Mr. Jon A. Waal Jr.";
            var target = new FullNameParser(fullName);
            target.Parse();

            Assert.Equal("Jon", target.FirstName);
            Assert.Equal("Waal", target.LastName);
            Assert.Equal("A.", target.MiddleName);
            Assert.Equal("Mr.", target.Title);
            Assert.Equal("Jr.", target.Suffix);

        }

        [Fact]
        public void Parse_JonADOTvanderWaalJr()
        {
            var fullName = "Jon A. van der Waal Jr.";
            var target = new FullNameParser(fullName);
            target.Parse();

            Assert.Equal("Jon", target.FirstName);
            Assert.Equal("van der Waal", target.LastName);
            Assert.Equal("A.", target.MiddleName);
            Assert.Equal("Jr.", target.Suffix);

        }

        [Fact]
        public void Parse_JonADOTWaalJr()
        {
            var fullName = "Jon A. Waal Jr.";
            var target = new FullNameParser(fullName);
            target.Parse();

            Assert.Equal("Jon", target.FirstName);
            Assert.Equal("Waal", target.LastName);
            Assert.Equal("A.", target.MiddleName);
            Assert.Equal("Jr.", target.Suffix);

        }

        [Fact]
        public void Parse_JamesAAdams()
        {
            var fullName = "James A Adams";
            var target = new FullNameParser(fullName);
            target.Parse();

            Assert.Equal("James", target.FirstName);
            Assert.Equal("A Adams", target.LastName);

        }

        [Fact]
        public void Parse_JamesADOTAdams()
        {
            var fullName = "James A. Adams";
            var target = new FullNameParser(fullName);
            target.Parse();

            Assert.Equal("James", target.FirstName);
            Assert.Equal("Adams", target.LastName);
            Assert.Equal("A.", target.MiddleName);
        }

    }
}

repository: JaminQuimby/NameParser

repo_name: JaminQuimby/NameParser

gha_license_id: NOASSERTION


text:
SECTION = "devel/chicken"
DESCRIPTION = "Levenshtein edit distance"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://levenshtein.meta;md5=e18714b0e671a02ade3351c825e4fc9a"
DEPENDS_append_class-cross = " chicken-egg-setup-helper-cross chicken-egg-check-errors-cross chicken-egg-vector-lib-cross chicken-egg-srfi-63-cross chicken-egg-utf8-cross chicken-egg-numbers-cross chicken-egg-miscmacros-cross chicken-egg-moremacros-cross"
DEPENDS_append_class-crosssdk = " chicken-egg-setup-helper-crosssdk chicken-egg-check-errors-crosssdk chicken-egg-vector-lib-crosssdk chicken-egg-srfi-63-crosssdk chicken-egg-utf8-crosssdk chicken-egg-numbers-crosssdk chicken-egg-miscmacros-crosssdk chicken-egg-moremacros-crosssdk"
DEPENDS_append_class-nativesdk = " nativesdk-chicken-egg-setup-helper nativesdk-chicken-egg-check-errors nativesdk-chicken-egg-vector-lib nativesdk-chicken-egg-srfi-63 nativesdk-chicken-egg-utf8 nativesdk-chicken-egg-numbers nativesdk-chicken-egg-miscmacros nativesdk-chicken-egg-moremacros chicken-egg-setup-helper-crosssdk chicken-egg-check-errors-crosssdk chicken-egg-vector-lib-crosssdk chicken-egg-srfi-63-crosssdk chicken-egg-utf8-crosssdk chicken-egg-numbers-crosssdk chicken-egg-miscmacros-crosssdk chicken-egg-moremacros-crosssdk"
DEPENDS = " chicken-egg-setup-helper chicken-egg-check-errors chicken-egg-vector-lib chicken-egg-srfi-63 chicken-egg-utf8 chicken-egg-numbers chicken-egg-miscmacros chicken-egg-moremacros chicken-egg-setup-helper-cross chicken-egg-check-errors-cross chicken-egg-vector-lib-cross chicken-egg-srfi-63-cross chicken-egg-utf8-cross chicken-egg-numbers-cross chicken-egg-miscmacros-cross chicken-egg-moremacros-cross chicken-egg-levenshtein-cross"
RDEPENDS_${PN} = " chicken-egg-setup-helper chicken-egg-check-errors chicken-egg-vector-lib chicken-egg-srfi-63 chicken-egg-utf8 chicken-egg-numbers chicken-egg-miscmacros chicken-egg-moremacros"

SRC_URI = "http://code.call-cc.org/egg-tarballs/4/levenshtein/levenshtein-${PV}.tar.gz"

SRC_URI[md5sum] = "d4bd08239f65ce0948cd2646b3375c8c"
SRC_URI[sha256sum] = "39a5d010296124451bc90d8af03f19ee6c1b59e85b284af9c9968d006d0476b8"

S = "${WORKDIR}/levenshtein-${PV}"

inherit chicken_install

BBCLASSEXTEND = "cross crosssdk nativesdk"

repository: OSSystems/meta-chicken

repo_name: OSSystems/meta-chicken


text:
# The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
  "/home/dnanexus/root/math/mathcore/inc/LinkDef.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/TComplex.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/TMath.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/TRandom.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/TRandom1.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/TRandom2.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/TRandom3.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/TKDTree.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/TKDTreeBinning.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/TStatistic.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/Error.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/IParamFunction.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/IFunction.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/ParamFunctor.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/Functor.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/Minimizer.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/MinimizerOptions.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/IntegratorOptions.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/IOptions.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/GenAlgoOptions.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/BasicMinimizer.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/MinimTransformFunction.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/MinimTransformVariable.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/Integrator.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/VirtualIntegrator.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/AllIntegrationTypes.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/AdaptiveIntegratorMultiDim.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/IntegratorMultiDim.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/Factory.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/FitMethodFunction.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/GaussIntegrator.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/GaussLegendreIntegrator.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/RootFinder.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/IRootFinderMethod.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/RichardsonDerivator.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/BrentMethods.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/BrentMinimizer1D.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/BrentRootFinder.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/DistSampler.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/DistSamplerOptions.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/GoFTest.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/SpecFuncMathCore.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/DistFuncMathCore.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/ChebyshevPol.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/KDTree.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/TDataPoint.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/TDataPointN.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/Delaunay2D.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/Random.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/TRandomEngine.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/RandomFunctions.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/StdEngine.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/MersenneTwisterEngine.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/MixMaxEngine.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/TRandomGen.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/LCGEngine.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Math/Types.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/BasicFCN.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/BinData.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/Chi2FCN.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/DataOptions.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/DataRange.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/FcnAdapter.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/FitConfig.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/FitData.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/FitExecutionPolicy.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/FitResult.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/FitUtil.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/Fitter.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/LogLikelihoodFCN.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/ParameterSettings.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/PoissonLikelihoodFCN.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/SparseData.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/root/math/mathcore/inc/Fit/UnBinData.h" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  )
set(CMAKE_CXX_COMPILER_ID "GNU")

# Preprocessor definitions for this target.
set(CMAKE_TARGET_DEFINITIONS_CXX
  "USE_ROOT_ERROR"
  )

# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
  "include"
  )

# Pairs of files generated by the same build rule.
set(CMAKE_MULTIPLE_OUTPUT_PAIRS
  "/home/dnanexus/lib/libMathCore.rootmap" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  "/home/dnanexus/lib/libMathCore_rdict.pcm" "/home/dnanexus/math/mathcore/G__MathCore.cxx"
  )

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  )

# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")

extension: cmake


text:
SUMMARY = "WPE Backend for freedesktop.org stack"
DESCRIPTION = "WPE's backend based on a freedesktop.org stack."
HOMEPAGE = "https://github.com/Igalia/WPEBackend-fdo"
SECTION = "wpe"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://COPYING;md5=1f62cef2e3645e3e74eb05fd389d7a66"

DEPENDS_append = " glib-2.0 libwpe libxkbcommon virtual/libgl wayland"

RECIPE_BRANCH ?= "master"
PV = "1.0.0+git${SRCPV}"
SRC_URI = "git://github.com/Igalia/WPEBackend-fdo.git;branch=${RECIPE_BRANCH};protocol=https"
SRCREV ?= "5a4b58c7d6a70068d13b8404a0c970b03a856119"
S = "${WORKDIR}/git"

inherit cmake

FILES_SOLIBSDEV = ""
FILES_${PN} += "${libdir}/libWPEBackend-fdo-0.1.so"

INSANE_SKIP_${PN} = "dev-so"

repository: WebPlatformForEmbedded/meta-wpe

repo_name: WebPlatformForEmbedded/meta-wpe

gha_language: BitBake


text:
package y21d9

import (
  "testing"
  "github.com/fdm1/advent_of_code_go/pkg/aoc_utils"
)

func TestPart1(t *testing.T) {
  aoc_utils.MockAdventOfCodeInput(2021, 9)
  result := Part1(false)
  expectedResult := "15"

  if result != expectedResult {
    t.Fatalf("actual result %v != expected result %v", result, expectedResult)
  }
}

func TestPart2(t *testing.T) {
  aoc_utils.MockAdventOfCodeInput(2021, 9)
  result := Part2(false)
  expectedResult := "1134"

  if result != expectedResult {
    t.Fatalf("actual result %v != expected result %v", result, expectedResult)
  }
}

func TestCalculateRisk(t *testing.T) {
  lowPoints := map[string]int{}
  lowPoints["foo"] = 1
  lowPoints["bar"] = 0
  lowPoints["baz"] = 5
  lowPoints["foobar"] = 5
  result := CalculateRisk(lowPoints)
  expectedResult := 15

  if result != expectedResult {
    t.Fatalf("actual result %v != expected result %v", result, expectedResult)
  }
}

func TestFindLowPointsForRow(t *testing.T) {
  row0 := []int{3, 2, 3, 6, 9, 8, 9, 8, 7, 6, 6, 7, 6, 7, 8, 9, 5, 4, 3, 9, 9, 7, 6, 3, 4, 6, 7, 8, 9, 4, 3, 4, 5, 9, 8, 6, 9, 8, 7, 7, 9, 9, 7, 6, 8, 9, 3, 6, 7, 8, 9, 9, 8, 5, 4, 3, 2, 3, 4, 5, 9, 8, 5, 4, 3, 4, 6, 9, 6, 5, 9, 3, 9, 8, 7, 6, 7, 8, 4, 5, 6, 9, 7, 8, 9, 8, 6, 7, 9, 9, 7, 9, 9, 8, 7, 6, 7, 5, 6, 7}
  row1 := []int{2, 1, 3, 5, 6, 7, 8, 9, 8, 7, 7, 9, 8, 9, 9, 4, 3, 1, 2, 4, 9, 8, 5, 4, 5, 6, 8, 9, 6, 4, 2, 3, 9, 9, 7, 5, 9, 8, 6, 6, 8, 5, 9, 7, 8, 9, 2, 4, 5, 6, 9, 9, 9, 7, 8, 7, 5, 4, 6, 6, 7, 9, 6, 5, 4, 5, 7, 8, 9, 9, 8, 4, 5, 9, 8, 9, 7, 6, 5, 6, 7, 9, 6, 7, 9, 8, 7, 8, 9, 5, 6, 9, 9, 9, 5, 4, 3, 4, 5, 8}
  row2 := []int{3, 4, 4, 6, 8, 8, 9, 3, 9, 8, 9, 1, 9, 8, 6, 5, 3, 2, 4, 9, 8, 7, 6, 5, 6, 7, 9, 6, 5, 3, 0, 9, 8, 7, 6, 4, 9, 7, 5, 4, 3, 4, 9, 8, 9, 0, 1, 3, 4, 5, 8, 9, 9, 8, 9, 7, 6, 5, 7, 7, 8, 9, 7, 6, 5, 7, 9, 9, 9, 8, 7, 5, 6, 7, 9, 9, 8, 9, 7, 7, 8, 9, 5, 4, 5, 9, 8, 9, 3, 4, 9, 8, 9, 8, 7, 4, 2, 4, 5, 5}
  intRows := [][]int{row0, row1, row2}
  result := FindLowPointsForRow(1, intRows)
  expectedResult := map[string]int{}
  expectedResult["1,1"] = 1
  expectedResult["1,17"] = 1

  if len(result) != len(expectedResult) {
    t.Fatalf("contents don't match (%v vs %v)", result, expectedResult)
  }

  for i := range result {
    if result[i] != expectedResult[i] {
      t.Fatalf("contents don't match (%v vs %v)", result, expectedResult)
    }
  }
}

func TestPointAboveOrBelowIsPartOfBasin(t *testing.T) {
  row1 := []int{3, 9, 8, 7, 8, 9, 4, 9, 2, 1}
  point := "0,6"
  val := 3
  result := PointAboveOrBelowIsPartOfBasin(point, val, row1)
  expectedResult := true

  if result != expectedResult {
    t.Fatalf("contents don't match (%v vs %v)", result, expectedResult)
  }
}


text:
SUMMARY = "Intel SGX Linux DDDriver"
DESCRIPTION = "Intel(R) Software Guard Extensions (Intel(R) SGX) \
is an Intel technology for application developers seeking to \
protect select code and data from disclosure or modification."
HOMEPAGE = "https://github.com/intel/linux-sgx-driver"

LICENSE = "GPL-2.0-only"
LIC_FILES_CHKSUM = "file://License.txt;md5=b54f8941f6087efb6be3deb0f1e617f7"

DEPENDS = "virtual/kernel"

PV = "2.1+git${SRCPV}"

SRC_URI = "\
    git://github.com/intel/linux-sgx-driver.git;branch=master;protocol=https \
"
SRCREV = "2a509c203533f9950fa3459fe91864051bc021a2"

S = "${WORKDIR}/git"

inherit module

EXTRA_OEMAKE += "KDIR='${STAGING_KERNEL_DIR}'"

MODULE_NAME = "isgx"

do_install () {
    dir="${D}/lib/modules/${KERNEL_VERSION}/kernel/${MODULE_NAME}"

    install -d "$dir"
    install -m 0644 "${MODULE_NAME}.ko" "$dir"
}

RPROVIDES:${PN} += "kernel-module-${MODULE_NAME}"


text:
package werewolf

import (
	"encoding/json"
	"fmt"

	"github.com/google/uuid"
)

// Witch 玩家
type Witch struct {
	*Human
	有毒藥 bool
	有解藥 bool
}

// NewWitch 建立新女巫
func NewWitch(遊戲 *Game, 位子 int) *Witch {
	human := NewHuman(遊戲, 位子)
	return &Witch{
		Human: human,
		有毒藥:   true,
		有解藥:   true,
	}
}

func (我 *Witch) 種族() GROUP {
	return 神職
}

func (我 *Witch) 職業() RULE {
	return 女巫
}

func (我 *Witch) 能力(i int) (_ Player) {

	有使用過藥了嗎 := false

	if 我.有解藥 {
		我.遊戲.旁白(傳輸資料{Sound: "他被殺了，你要救他嗎？"}, 1500)

		被狼殺玩家 := 我.遊戲.尋找淘汰者(狼殺)

		// 女巫是否救人
		if 被狼殺玩家 != nil && !我.出局了() {

			可以救 := !(我.遊戲.輪數 >= 2 && 被狼殺玩家.號碼() == 我.號碼())
			救的選項 := map[string]string{
				"不救😵": "no",
			}
			顯示文字 := fmt.Sprintf("你要救『%d號玩家』嗎？", 被狼殺玩家.號碼())
			if 可以救 {
				救的選項["救💊"] = "yes"
			} else {
				顯示文字 += "  (不能救自己唷哈哈哈笨蛋)"
			}

			uid := newUID()
			我.遊戲.旁白有話對單個玩家說(我, 傳輸資料{
				UID:     uid,
				Display: 顯示文字,
				Action:  等待回應,
				Data:    救的選項,
			}, 0)

			是否使用解藥, err := 我.等待動作(等待回應, uid)

			if err != nil || 是否使用解藥.Reply == "yes" {
				我.遊戲.救玩家(狼殺)
				我.有解藥 = false
				有使用過藥了嗎 = true
			}
		} else {
			我.遊戲.等一下(random(3) * 2500)
		}
	}

	我.遊戲.旁白(傳輸資料{Sound: "你要使用毒藥嗎？你要毒誰呢？"}, 1500)

	if !有使用過藥了嗎 && 我.有毒藥 && !我.出局了() {

		uid := uuid.New().String()
		我.遊戲.旁白有話對單個玩家說(我, 傳輸資料{
			UID:     uid,
			Display: "你要使用毒藥嗎？",
			Action:  等待回應,
			Data: map[string]interface{}{
				"要💉":  "yes",
				"不要😎": "no",
			},
		}, 0)

		//如果是第二晚之後被殺的是女巫，則不能使用解藥
		是否使用毒藥, err := 我.等待動作(等待回應, uid)
		if err != nil {
			return
		}

		if 是否使用毒藥.Reply == "yes" {

			我.有毒藥 = false
			可毒的玩家號碼 := []int{}
			目前存活玩家們 := 我.遊戲.存活玩家們()

			for i := range 目前存活玩家們 {
				玩家 := 目前存活玩家們[i]
				if 我.號碼() == 玩家.號碼() {
					continue
				}
				可毒的玩家號碼 = append(可毒的玩家號碼, 玩家.號碼())
			}

			uid := uuid.New().String()
			我.遊戲.旁白有話對單個玩家說(我, 傳輸資料{
				UID:     uid,
				Display: "你要毒誰呢？",
				Action:  選擇玩家,
				Data:    可毒的玩家號碼,
			}, 0)

			for {
				被女巫毒的人, err := 我.等待動作(選擇玩家, uid)
				if err != nil {
					return
				}

				玩家號碼 := 0
				err = json.Unmarshal([]byte(被女巫毒的人.Reply), &玩家號碼)
				if err != nil {
					continue
				}

				玩家, 存在 := 我.遊戲.玩家資料(玩家號碼)
				if 存在 {
					我.遊戲.殺玩家(毒殺, 玩家)
					return
				}
			}
		}
	} else {
		我.遊戲.等一下(random(3) * 2500)
	}

	return
}

func (我 *Witch) 需要夜晚行動() bool {
	return true
}

gha_language: JavaScript


text:
@article{mockus1978application,
  title={The application of Bayesian methods for seeking the extremum},
  author={Mockus, Jonas and Tiesis, Vytautas and Zilinskas, Antanas},
  journal={Towards global optimization},
  volume={2},
  number={117-129},
  pages={2},
  year={1978}
}

@article{HennigS2012,
  title =	 {Entropy Search for Information-Efficient Global Optimization},
  author =	 {Hennig, P. and Schuler, CJ.},
  month =	 jun,
  volume =	 13,
  pages =	 {1809-1837},
  abstract =	 {Contemporary global optimization algorithms are based on
                  local measures of utility, rather than a probability measure
                  over location and value of the optimum. They thus attempt to
                  collect low function values, not to learn about the
                  optimum. The reason for the absence of probabilistic global
                  optimizers is that the corresponding inference problem is
                  intractable in several ways. This paper develops desiderata
                  for probabilistic optimization algorithms, then presents a
                  concrete algorithm which addresses each of the computational
                  intractabilities with a sequence of approximations and
                  explicitly adresses the decision problem of maximizing
                  information gain from each evaluation. },
  journal =	 {Journal of Machine Learning Research},
  year =	 2012,
  file =
                  {http://jmlr.csail.mit.edu/papers/volume13/hennig12a/hennig12a.pdf},
  link =	 {http://jmlr.csail.mit.edu/papers/v13/hennig12a.html},
  code = {http://probabilistic-optimization.org/Global.html}
}

repository: christopheroates/probnum

repo_name: christopheroates/probnum

gha_language: Python

extension: bib


text:
// I did some updated in the code, based on the problem description

package main

import (
	"fmt"
	"math/rand"
	"time"
)

type Segment struct {
	Id   int
	Name string
}

type Campaign struct {
	Id       int
	Name     string
	Segments []Segment
}

func main() {
	rand.Seed(time.Now().UnixNano())

	// Generate a list of random campaigns
	campaigns := make([]Campaign, 0)

	// updated from 1000 to 10,000 campaigns
	for i := 1; i <= 10000; i++ {
		segments := make([]Segment, 0)
		// updated to 100 segments
		for j := 1; j <= 100; j++ {
			segment := Segment{
				Id:   rand.Intn(10000),
				Name: fmt.Sprintf("Segment %d", j),
			}
			segments = append(segments, segment)
		}

		campaign := Campaign{
			Id:       i,
			Name:     fmt.Sprintf("Campaign %d", i),
			Segments: segments,
		}

		campaigns = append(campaigns, campaign)
	}

	// Segment list to compare ( Random list )
	// updated to 1000 segments
	segmentsList := make([]Segment, 0)
	for i := 1; i <= 1000; i++ {
		segmentId := rand.Intn(10000)

		segment := Segment{
			Id:   segmentId,
			Name: fmt.Sprintf("Segment %d", segmentId),
		}

		segmentsList = append(segmentsList, segment)
	}

	// Get matching segments for each campaign
	for _, campaign := range campaigns {
		match := getMatchingSegments(campaign.Segments, segmentsList)
		if len(match) > 0 {
			// print match segments
			fmt.Println("Campaign ", campaign.Id, " - ", len(match), "Segment(s) matching", match)
		}
	}
}

func getMatchingSegments(campaignSegments []Segment, requestSegments []Segment) []int {
	result := make([]int, 0)

	for _, campaignSegment := range campaignSegments {
		for _, requestSegment := range requestSegments {
			if requestSegment.Id == campaignSegment.Id {
				result = append(result, requestSegment.Id)
			}
		}
	}

	return result
}

repository: ktaf/go-learn

repo_name: ktaf/go-learn


text:
import { Processors } from "./processors";
import { EventBus } from "../services/event-bus";
import { EventNames } from "../constants/event-names";
import { StatsRepository } from "../repository/stats-repository";
import { MatchRepository } from "../repository/match-repository";
import { MatchState } from "../constants/match-state";
import { TopicNames } from "../constants/topic-names";

export class QueuedItem {
    public matchId: string;
    public url: string;
    public map: string;
    public data: any;

    public constructor(matchId: string, url: string, map: string, data?: any) {
        this.matchId = matchId;
        this.url = url;
        this.map = map;
        this.data = data;
    }
}

export class TelemetryProcessor extends Processors {

    public static readonly IGNORE_MAP = 'Range_Main';

    private static readonly LISTENER_DELAY = 1000;

    private static readonly MAX_PROCESSING = 5;
    private static readonly MAX_DOWNLOADING = 5;

    static getRollup(): {} {
        return {
            shotCount: 0,
            hitCount: 0,
            knockCount: 0,
            killCount: 0,
            hitCountByLocation: {
                ArmShot: 0,
                HeadShot: 0,
                TorsoShot: 0,
                PelvisShot: 0,
                LegShot: 0,
                None: 0,
                NonSpecific: 0
            }
        };
    }

    private downloadQueue: Array<QueuedItem> = [];
    private processQueue: Array<QueuedItem> = [];

    private downloading: number = 0;
    private processing: number = 0;

    private downloadInGame: boolean = false;
    private downloadAsynchronous: boolean = false;

    private processInGame: boolean = false;
    private processThreaded: boolean = false;

    private inAGame: boolean = false;

    public constructor() {
        super();
        this.loadMatches();
    }

    public listen(): void {
        EventBus.instance.subscribe('telemetry-service', TopicNames.Data, EventNames.DataInGame, this.eventListener.bind(this));
    }

    public eventListener(topic: string, event: string, data: any): void {
        switch (event) {
            case EventNames.DataInGame:
                this.inAGame = data;
                break;
        }
    }

    private loadMatches() {
        for (let i in MatchRepository.instance.matches) {
            let matchData = MatchRepository.instance.matches[i];
            if (matchData.state != MatchState.COMPLETED) {
                this.addToDownloadQueue(matchData.matchId, matchData.url, matchData.map);
            }
        }
        this.downloadListener();
        this.processListener();
    }

    public getTelemetry(matchId: string, url: string, map: string): () => void {
        if (TelemetryProcessor.IGNORE_MAP == map) {
            return () => { };
        }

        let that = this;
        return () => {
            that.addToDownloadQueue(matchId, url, map);
        };
    }

    private addToDownloadQueue(matchId: string, url: string, map: string): void {
        EventBus.instance.publish(TopicNames.Match, EventNames.MatchDownloadQueued, matchId);
        this.downloadQueue.push(new QueuedItem(matchId, url, map));
    }

    private downloadListener(): void {
        let that = this;
        let listener = () => {
            // Don't allow downloads in game
            if (!this.downloadInGame && this.inAGame) {
                setTimeout(listener, TelemetryProcessor.LISTENER_DELAY);
                return;
            }

            // Are there any queued downloads?
            if (0 >= that.downloadQueue.length) {
                setTimeout(listener, TelemetryProcessor.LISTENER_DELAY);
                return;
            }

            let maxDownloads = this.downloadAsynchronous ? TelemetryProcessor.MAX_DOWNLOADING : 1;

            // Don't exceed maximum simultaneous downloads
            if (that.downloading >= maxDownloads) {
                setTimeout(listener, TelemetryProcessor.LISTENER_DELAY);
                return;
            }

            that.downloading++;
            that.download(that.downloadQueue.shift());
            listener();
        };

        listener();
    }

    private download(queuedItem?: QueuedItem): void {
        if (!queuedItem) {
            return;
        }

        EventBus.instance.publish(TopicNames.Match, EventNames.MatchDownloading, queuedItem.matchId);

        this.getRaw(
            queuedItem.url,
            this.addToProcessingQueue(queuedItem)
        );
    }

    private addToProcessingQueue(queuedItem: QueuedItem): (err: any, res: any, body: any) => void {
        let that = this;
        return (err: any, res: any, body: any) => {
            if (err || !body) {
                return;
            }
            that.downloading--;
            queuedItem.data = body;
            that.processQueue.push(queuedItem);
            EventBus.instance.publish(TopicNames.Match, EventNames.MatchDownloading, queuedItem.matchId);
        };
    }

    private processListener(): void {
        let that = this;
        let listener = () => {
            // Don't process data in game
            if (!this.processInGame && this.inAGame) {
                setTimeout(listener, TelemetryProcessor.LISTENER_DELAY);
                return;
            }

            // Are there any queued processes?
            if (0 >= that.processQueue.length) {
                setTimeout(listener, TelemetryProcessor.LISTENER_DELAY);
                return;
            }

            let maxThreads = this.processThreaded ? TelemetryProcessor.MAX_PROCESSING : 1;

            // Don't exceed maximum simultaneous threads
            if (that.processing >= maxThreads) {
                setTimeout(listener, TelemetryProcessor.LISTENER_DELAY);
                return;
            }

            that.processing++;
            that.process(that.processQueue.shift());
            listener();
        };

        listener();
    }

    private process(queuedItem?: QueuedItem): void {
        if (!queuedItem) {
            return;
        }

        EventBus.instance.publish(TopicNames.Match, EventNames.MatchProcessing, queuedItem.matchId);

        if (!StatsRepository.instance.stats.optimiser) {
            StatsRepository.instance.stats.optimiser = {};
        }

        if (TelemetryProcessor.IGNORE_MAP == queuedItem.map) {
            delete queuedItem.data;
            EventBus.instance.publish(TopicNames.Match, EventNames.MatchCompleted, queuedItem.matchId);
            this.processing--;
            return;
        }

        this.setMap(queuedItem.map);

        let character: string = StatsRepository.instance.stats.name;
        let itemsEquiped: any = [];
        let weaponAttachmentsEquiped: any = {};
        let dbno: any = {};
        let started = true;
        let currentPhase = -1;

        for (let i in queuedItem.data) {

            let event = queuedItem.data[i];
            let phase = 'phase_' + currentPhase;

            if ('LogGameStatePeriodic' == event._T) {
                let tmpPhase = (event.common.isGame < 1) ? "0" : event.common.isGame
                if (tmpPhase != currentPhase) {
                    currentPhase = tmpPhase;
                    phase = 'phase_' + currentPhase;
                    this.setPhase(queuedItem.map, phase);
                    for (let i in itemsEquiped) {
                        let weapon = itemsEquiped[i];
                        this.setWeapon(queuedItem.map, phase, weapon);
                        for (let j in weaponAttachmentsEquiped[weapon]) {
                            let attachment = weaponAttachmentsEquiped[weapon][j];
                            this.setAttachment(queuedItem.map, phase, weapon, attachment);
                        }
                    }
                }
            }

            if ('LogMatchStart' == event._T) {
                started = true;
            }

            if (!started) {
                continue;
            }

            if ('LogItemAttach' == event._T && character == event.character.name) {
                let weapon = event.parentItem.itemId;
                let attachment = event.childItem.itemId;
                this.setAttachment(queuedItem.map, phase, weapon, attachment);
                weaponAttachmentsEquiped[weapon].push(attachment);
            }

            if ('LogItemDetach' == event._T && character == event.character.name) {
                let weapon = event.parentItem.itemId;
                let attachment = event.childItem.itemId;
                weaponAttachmentsEquiped[weapon].splice(weaponAttachmentsEquiped[weapon].indexOf(attachment), 1);
            }

            if ('LogPlayerMakeGroggy' == event._T && event.attacker.name == character) {
                dbno['_' + event.dBNOId] = {
                    damageReason: event.damageReason,
                    damageTypeCategory: event.damageTypeCategory,
                    damageCauserName: event.damageCauserName,
                    damageCauserAdditionalInfo: event.damageCauserAdditionalInfo
                };
            }

            if ('LogPlayerKill' == event._T && event.killer.name == character) {

                let dbnoData: any;

                // Use the DBNO item if required

                if (event.dBNOId == -1 || !dbno['_' + event.dBNOId]) {
                    dbnoData = {
                        damageReason: event.damageReason,
                        damageTypeCategory: event.damageTypeCategory,
                        damageCauserName: event.damageCauserName,
                        damageCauserAdditionalInfo: event.damageCauserAdditionalInfo
                    };
                    // This also contains attachment info!
                } else {
                    dbnoData = dbno['_' + event.dBNOId];
                }

                let weapon = this.damageCauserToItem(dbnoData.damageCauserName);

                StatsRepository.instance.stats.optimiser.playerStats.killCount++;
                StatsRepository.instance.stats.optimiser.playerStatsByMap[queuedItem.map].killCount++;
                StatsRepository.instance.stats.optimiser.playerStatsByPhase[phase].killCount++;
                StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap[queuedItem.map][phase].killCount++;

                if (StatsRepository.instance.stats.optimiser.weaponStats[weapon]) {

                    StatsRepository.instance.stats.optimiser.weaponStats[weapon].killCount++;
                    StatsRepository.instance.stats.optimiser.weaponStatsByMap[queuedItem.map][weapon].killCount++;
                    StatsRepository.instance.stats.optimiser.weaponStatsByPhase[phase][weapon].killCount++;
                    StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap[queuedItem.map][phase][weapon].killCount++;

                    for (let i in weaponAttachmentsEquiped[weapon]) {
                        let attachment = weaponAttachmentsEquiped[weapon][i];

                        StatsRepository.instance.stats.optimiser.weaponByAttachmentStats[weapon][attachment].killCount++;
                        StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap[queuedItem.map][weapon][attachment].killCount++;
                        StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase[phase][weapon][attachment].killCount++;
                        StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[queuedItem.map][phase][weapon][attachment].killCount++;
                    }
                }
            }

            if ('LogPlayerTakeDamage' == event._T && event.attacker && event.attacker.name == character && event.victim.name != character && 'Damage_Gun' == event.damageTypeCategory) {
                let weapon = this.damageCauserToItem(event.damageCauserName);

                StatsRepository.instance.stats.optimiser.playerStats.hitCount++;
                StatsRepository.instance.stats.optimiser.playerStats.hitCountByLocation[event.damageReason]++;

                StatsRepository.instance.stats.optimiser.playerStatsByMap[queuedItem.map].hitCount++;
                StatsRepository.instance.stats.optimiser.playerStatsByMap[queuedItem.map].hitCountByLocation[event.damageReason]++;

                StatsRepository.instance.stats.optimiser.playerStatsByPhase[phase].hitCount++;
                StatsRepository.instance.stats.optimiser.playerStatsByPhase[phase].hitCountByLocation[event.damageReason]++;

                StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap[queuedItem.map][phase].hitCount++;
                StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap[queuedItem.map][phase].hitCountByLocation[event.damageReason]++;

                StatsRepository.instance.stats.optimiser.weaponStats[weapon].hitCount++;
                StatsRepository.instance.stats.optimiser.weaponStats[weapon].hitCountByLocation[event.damageReason]++;

                StatsRepository.instance.stats.optimiser.weaponStatsByMap[queuedItem.map][weapon].hitCount++;
                StatsRepository.instance.stats.optimiser.weaponStatsByMap[queuedItem.map][weapon].hitCountByLocation[event.damageReason]++;

                StatsRepository.instance.stats.optimiser.weaponStatsByPhase[phase][weapon].hitCount++;
                StatsRepository.instance.stats.optimiser.weaponStatsByPhase[phase][weapon].hitCountByLocation[event.damageReason]++;

                StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap[queuedItem.map][phase][weapon].hitCount++;
                StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap[queuedItem.map][phase][weapon].hitCountByLocation[event.damageReason]++;

                for (let i in weaponAttachmentsEquiped[weapon]) {
                    let attachment = weaponAttachmentsEquiped[weapon][i];

                    StatsRepository.instance.stats.optimiser.weaponByAttachmentStats[weapon][attachment].hitCount++;
                    StatsRepository.instance.stats.optimiser.weaponByAttachmentStats[weapon][attachment].hitCountByLocation[event.damageReason]++;

                    StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap[queuedItem.map][weapon][attachment].hitCount++;
                    StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap[queuedItem.map][weapon][attachment].hitCountByLocation[event.damageReason]++;

                    StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase[phase][weapon][attachment].hitCount++;
                    StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase[phase][weapon][attachment].hitCountByLocation[event.damageReason]++;

                    StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[queuedItem.map][phase][weapon][attachment].hitCount++;
                    StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[queuedItem.map][phase][weapon][attachment].hitCountByLocation[event.damageReason]++;
                }
            }

            if ('LogPlayerAttack' == event._T && event.attacker.name == character && event.weapon.category == 'Weapon') {
                let weapon = event.weapon.itemId;

                StatsRepository.instance.stats.optimiser.playerStats.shotCount++;
                StatsRepository.instance.stats.optimiser.playerStatsByMap[queuedItem.map].shotCount++;

                StatsRepository.instance.stats.optimiser.playerStatsByPhase[phase].shotCount++;
                StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap[queuedItem.map][phase].shotCount++;

                StatsRepository.instance.stats.optimiser.weaponStats[weapon].shotCount++;
                StatsRepository.instance.stats.optimiser.weaponStatsByMap[queuedItem.map][weapon].shotCount++;

                StatsRepository.instance.stats.optimiser.weaponStatsByPhase[phase][weapon].shotCount++;
                StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap[queuedItem.map][phase][weapon].shotCount++;

                for (let i in weaponAttachmentsEquiped[weapon]) {
                    let attachment = weaponAttachmentsEquiped[weapon][i];

                    StatsRepository.instance.stats.optimiser.weaponByAttachmentStats[weapon][attachment].shotCount++;
                    StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap[queuedItem.map][weapon][attachment].shotCount++;

                    StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase[phase][weapon][attachment].shotCount++;
                    StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[queuedItem.map][phase][weapon][attachment].shotCount++;
                }
            }

            if ('LogItemEquip' == event._T && character == event.character.name && 'Weapon' == event.item.category) {

                let weapon = event.item.itemId;
                itemsEquiped.push(weapon);

                this.setWeapon(queuedItem.map, phase, weapon);

                if (!weaponAttachmentsEquiped[weapon]) {
                    weaponAttachmentsEquiped[weapon] = [];
                }

                // Attach attachments
                if (event.item.attachedItems) {
                    for (let i = 0; i < event.item.attachedItems.length; i++) {
                        let attachment = event.item.attachedItems[i];
                        this.setAttachment(queuedItem.map, phase, weapon, attachment);
                        weaponAttachmentsEquiped[weapon].push(attachment);
                    }
                }
            }

            if ('LogItemUnequip' == event._T && character == event.character.name && 'Weapon' == event.item.category) {
                let weapon = event.item.itemId;
                itemsEquiped.splice(itemsEquiped.indexOf(weapon), 1);
            }
        }

        delete queuedItem.data;
        EventBus.instance.publish(TopicNames.Match, EventNames.MatchCompleted, queuedItem.matchId);
        this.processing--;
        EventBus.instance.publish(TopicNames.Match, EventNames.StatsSave, {});
    }

    private setMap(map: string): void {
        // Player Stats

        if (!StatsRepository.instance.stats.optimiser.playerStats) {
            StatsRepository.instance.stats.optimiser.playerStats = TelemetryProcessor.getRollup();
        }

        if (!StatsRepository.instance.stats.optimiser.playerStatsByMap) {
            StatsRepository.instance.stats.optimiser.playerStatsByMap = {};
        }

        if (!StatsRepository.instance.stats.optimiser.playerStatsByMap[map]) {
            StatsRepository.instance.stats.optimiser.playerStatsByMap[map] = TelemetryProcessor.getRollup();
        }

        // Weapon Stats

        if (!StatsRepository.instance.stats.optimiser.weaponStats) {
            StatsRepository.instance.stats.optimiser.weaponStats = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByMap) {
            StatsRepository.instance.stats.optimiser.weaponStatsByMap = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByMap[map]) {
            StatsRepository.instance.stats.optimiser.weaponStatsByMap[map] = {};
        }

        // Weapons Attachement

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStats) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStats = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap[map]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap[map] = {};
        }

        // Weapons Attachement Phase

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[map]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[map] = {};
        }

        // Player Stats Phase

        if (!StatsRepository.instance.stats.optimiser.playerStatsByPhase) {
            StatsRepository.instance.stats.optimiser.playerStatsByPhase = {};
        }

        if (!StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap) {
            StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap = {};
        }

        if (!StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap[map]) {
            StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap[map] = {};
        }

        // Weapon Stats Phase

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByPhase) {
            StatsRepository.instance.stats.optimiser.weaponStatsByPhase = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap) {
            StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap[map]) {
            StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap[map] = {};
        }

        // Player Stats

        if (!StatsRepository.instance.stats.optimiser.playerStats) {
            StatsRepository.instance.stats.optimiser.playerStats = TelemetryProcessor.getRollup();
        }

        if (!StatsRepository.instance.stats.optimiser.playerStatsByMap) {
            StatsRepository.instance.stats.optimiser.playerStatsByMap = {};
        }

        if (!StatsRepository.instance.stats.optimiser.playerStatsByMap[map]) {
            StatsRepository.instance.stats.optimiser.playerStatsByMap[map] = TelemetryProcessor.getRollup();
        }

        // Weapon Stats

        if (!StatsRepository.instance.stats.optimiser.weaponStats) {
            StatsRepository.instance.stats.optimiser.weaponStats = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByMap) {
            StatsRepository.instance.stats.optimiser.weaponStatsByMap = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByMap[map]) {
            StatsRepository.instance.stats.optimiser.weaponStatsByMap[map] = {};
        }

        // Weapons Attachement

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStats) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStats = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap[map]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap[map] = {};
        }

        // Weapons Attachement Phase

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[map]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[map] = {};
        }

        // Player Stats Phase

        if (!StatsRepository.instance.stats.optimiser.playerStatsByPhase) {
            StatsRepository.instance.stats.optimiser.playerStatsByPhase = {};
        }

        if (!StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap) {
            StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap = {};
        }

        if (!StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap[map]) {
            StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap[map] = {};
        }

        // Weapon Stats Phase

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByPhase) {
            StatsRepository.instance.stats.optimiser.weaponStatsByPhase = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap) {
            StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap[map]) {
            StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap[map] = {};
        }

    }

    private setPhase(map: string, phase: string): void {
        if (!StatsRepository.instance.stats.optimiser.playerStatsByPhase[phase]) {
            StatsRepository.instance.stats.optimiser.playerStatsByPhase[phase] = TelemetryProcessor.getRollup();
        }

        if (!StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap[map][phase]) {
            StatsRepository.instance.stats.optimiser.playerStatsByPhaseByMap[map][phase] = TelemetryProcessor.getRollup();
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByPhase[phase]) {
            StatsRepository.instance.stats.optimiser.weaponStatsByPhase[phase] = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap[map][phase]) {
            StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap[map][phase] = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase[phase]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase[phase] = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[map][phase]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[map][phase] = {};
        }

    }

    private setWeapon(map: string, phase: string, weapon: string): void {
        if (!StatsRepository.instance.stats.optimiser.weaponStats[weapon]) {
            StatsRepository.instance.stats.optimiser.weaponStats[weapon] = TelemetryProcessor.getRollup();
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByMap[map][weapon]) {
            StatsRepository.instance.stats.optimiser.weaponStatsByMap[map][weapon] = TelemetryProcessor.getRollup();
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByPhase[phase][weapon]) {
            StatsRepository.instance.stats.optimiser.weaponStatsByPhase[phase][weapon] = TelemetryProcessor.getRollup();
        }

        if (!StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap[map][phase][weapon]) {
            StatsRepository.instance.stats.optimiser.weaponStatsByPhaseByMap[map][phase][weapon] = TelemetryProcessor.getRollup();
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStats[weapon]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStats[weapon] = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap[map][weapon]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap[map][weapon] = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase[phase][weapon]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase[phase][weapon] = {};
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[map][phase][weapon]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[map][phase][weapon] = {};
        }
    }

    private setAttachment(map: string, phase: string, weapon: string, attachment: string): void {

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStats[weapon][attachment]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStats[weapon][attachment] = TelemetryProcessor.getRollup();
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap[map][weapon][attachment]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByMap[map][weapon][attachment] = TelemetryProcessor.getRollup();
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase[phase][weapon][attachment]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhase[phase][weapon][attachment] = TelemetryProcessor.getRollup();
        }

        if (!StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[map][phase][weapon][attachment]) {
            StatsRepository.instance.stats.optimiser.weaponByAttachmentStatsByPhaseByMap[map][phase][weapon][attachment] = TelemetryProcessor.getRollup();
        }
    }

    private damageCauserToItem(damageCauser: string): string {
        if ('WeapCrossbow_1_C' == damageCauser) {
            return 'Item_Weapon_Crossbow_C';
        } else if ('WeapWin94_C' == damageCauser) {
            return 'Item_Weapon_Win1894_C';
        }
        return damageCauser.replace('Weap', 'Item_Weapon_');
    }
}

repository: willitscale/overwolf-application-pubg

repo_name: willitscale/overwolf-application-pubg

gha_language: TypeScript

extension: ts


text:
package crypto

import (
	"encoding/hex"
	"fmt"
	"github.com/annchain/OG/common/math"
	"testing"
)

func TestFromECDSA(t *testing.T) {
	priv, err := GenerateKey()
	fmt.Println(err, priv)
	data := math.PaddedBigBytes(priv.D, priv.Params().BitSize/8)
	fmt.Println(hex.EncodeToString(data))
}

repository: hwlsniper/OG

repo_name: hwlsniper/OG