text:
#=========================== begin_copyright_notice ============================
#
# Copyright (C) 2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
#
#============================ end_copyright_notice =============================

# Handle spirv translator library.
# Main variable for SPIRV translator handling is:
#  IGC_OPTION__SPIRV_TRANSLATOR_MODE -- SPIRV translator usage model. Can be
#  Source, Prebuilds or empty. If it is empty, then sources are tried first,
#  then fallback to prebuilds is performed is no sources are available.
#
# Prebuilds mode is handled in IGC and uses SPIRVLLVMTranslator_ROOT variable
# to find prebuild package. Here only minimal processing is done to ensure that
# sources are not found or not needed.
#
# Source mode is handled in this file by registering llvm hook for adding external
# projects. If Source mode was selected or SPIRV sources were found during standard
# search procedure then project will be register and then handled by IGC-LLVM cmake.
# Source mode has suboption:
#  IGC_OPTION__SPIRV_TRANSLATOR_SOURCE_DIR -- path to spirv translator sources.

include_guard(DIRECTORY)

option(IGC_OPTION__LINK_KHRONOS_SPIRV_TRANSLATOR "Enable link against Khronos SPIRV-LLVM-Translator, instead of legacy versions" ON)

if(IGC_OPTION__LINK_KHRONOS_SPIRV_TRANSLATOR)

llvm_define_mode_variable(SPIRV IGC_OPTION__SPIRV_TRANSLATOR_MODE)

# Guess default spirv translator path.
include(llvm_spirv_source_path)

# Handle dependent options for Source mode.
if(IGC_OPTION__SPIRV_TRANSLATOR_MODE STREQUAL SOURCE_MODE_NAME)
  set(IGC_OPTION__SPIRV_TRANSLATOR_SOURCE_DIR "${DEFAULT_SPIRV_TRANSLATOR_SOURCE_DIR}" CACHE PATH "Path to SPIRV translator sources")
  # Tell the build that we are using sources.
  set(IGC_BUILD__SPIRV_TRANSLATOR_SOURCES ON)
endif()

# Handle dependent options for Prebuild mode.
if(IGC_OPTION__SPIRV_TRANSLATOR_MODE STREQUAL PREBUILDS_MODE_NAME)
  message(STATUS "[SPIRV] Will use SPIRV translator prebuilds")
  # Set spirv translator source dir, as it is needed when using prebuild translator later
  set(IGC_OPTION__SPIRV_TRANSLATOR_SOURCE_DIR "${DEFAULT_SPIRV_TRANSLATOR_SOURCE_DIR}" CACHE PATH "Path to SPIRV translator sources")
  return()
endif()

# No mode was specified, start searching.
if(NOT IGC_OPTION__SPIRV_TRANSLATOR_MODE)
  message(STATUS "[SPIRV] Using default procedure to determine SPIRV mode")
  # OpenCL Clang and Vector Compiler share the library Spirv Translator, so we cannot build Spriv Translator
  # if OpenCL Clang is taken from the system.
  if(IGC_TRY_TO_TAKE_CLANG_FROM_SYSTEM)
    message(STATUS "[SPIRV] No mode was specified for SPIRV. Clang is trying to be taken from the system, so the SPIRV translator not will be built from the source")
    return()
  endif()
  if(EXISTS "${DEFAULT_SPIRV_TRANSLATOR_SOURCE_DIR}")
    set(IGC_BUILD__SPIRV_TRANSLATOR_SOURCES ON)
    set(IGC_OPTION__SPIRV_TRANSLATOR_SOURCE_DIR ${DEFAULT_SPIRV_TRANSLATOR_SOURCE_DIR})
  else()
    return()
  endif()
endif()

message(STATUS "[SPIRV] SPIRV translator will be built from sources")
message(STATUS "[SPIRV] Using SPIRV sources: ${IGC_OPTION__SPIRV_TRANSLATOR_SOURCE_DIR}")

# Only sources are left here. Other code paths executed return.
if(NOT EXISTS "${IGC_OPTION__SPIRV_TRANSLATOR_SOURCE_DIR}")
  message(FATAL_ERROR
    "[SPIRV] Cannot find SPIRV translator sources, please provide sources path by IGC_OPTION__SPIRV_TRANSLATOR_SOURCE_DIR flag")
endif()

register_llvm_external_project(spirv ${IGC_OPTION__SPIRV_TRANSLATOR_SOURCE_DIR})

endif()

extension: cmake


text:
// Code generated by go-swagger; DO NOT EDIT.

package tcp_lb

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"fmt"

	"github.com/go-openapi/runtime"
	"github.com/go-openapi/strfmt"
)

// New creates a new tcp lb API client.
func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService {
	return &Client{transport: transport, formats: formats}
}

/*
Client for tcp lb API
*/
type Client struct {
	transport runtime.ClientTransport
	formats   strfmt.Registry
}

// ClientOption is the option for Client methods
type ClientOption func(*runtime.ClientOperation)

// ClientService is the interface for Client methods
type ClientService interface {
	AddTCPLb(params *AddTCPLbParams, opts ...ClientOption) (*AddTCPLbNoContent, error)

	DescribeTCPLb(params *DescribeTCPLbParams, opts ...ClientOption) (*DescribeTCPLbOK, error)

	GetTCPLb(params *GetTCPLbParams, opts ...ClientOption) (*GetTCPLbOK, error)

	ListTCPLb(params *ListTCPLbParams, opts ...ClientOption) (*ListTCPLbOK, error)

	RemoveTCPLb(params *RemoveTCPLbParams, opts ...ClientOption) (*RemoveTCPLbNoContent, error)

	UpdateTCPLb(params *UpdateTCPLbParams, opts ...ClientOption) (*UpdateTCPLbNoContent, error)

	SetTransport(transport runtime.ClientTransport)
}

/*
AddTCPLb adds tcp lb
*/
func (a *Client) AddTCPLb(params *AddTCPLbParams, opts ...ClientOption) (*AddTCPLbNoContent, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewAddTCPLbParams()
	}
	op := &runtime.ClientOperation{
		ID:                 "addTcpLb",
		Method:             "POST",
		PathPattern:        "/tcp-lb",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http"},
		Params:             params,
		Reader:             &AddTCPLbReader{formats: a.formats},
		Context:            params.Context,
		Client:             params.HTTPClient,
	}
	for _, opt := range opts {
		opt(op)
	}

	result, err := a.transport.Submit(op)
	if err != nil {
		return nil, err
	}
	success, ok := result.(*AddTCPLbNoContent)
	if ok {
		return success, nil
	}
	// unexpected success response
	// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
	msg := fmt.Sprintf("unexpected success response for addTcpLb: API contract not enforced by server. Client expected to get an error, but got: %T", result)
	panic(msg)
}

/*
DescribeTCPLb gets detailed info of one tcp lb
*/
func (a *Client) DescribeTCPLb(params *DescribeTCPLbParams, opts ...ClientOption) (*DescribeTCPLbOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewDescribeTCPLbParams()
	}
	op := &runtime.ClientOperation{
		ID:                 "describeTcpLb",
		Method:             "GET",
		PathPattern:        "/tcp-lb/{tl}/detail",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http"},
		Params:             params,
		Reader:             &DescribeTCPLbReader{formats: a.formats},
		Context:            params.Context,
		Client:             params.HTTPClient,
	}
	for _, opt := range opts {
		opt(op)
	}

	result, err := a.transport.Submit(op)
	if err != nil {
		return nil, err
	}
	success, ok := result.(*DescribeTCPLbOK)
	if ok {
		return success, nil
	}
	// unexpected success response
	// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
	msg := fmt.Sprintf("unexpected success response for describeTcpLb: API contract not enforced by server. Client expected to get an error, but got: %T", result)
	panic(msg)
}

/*
GetTCPLb gets tcp lb
*/
func (a *Client) GetTCPLb(params *GetTCPLbParams, opts ...ClientOption) (*GetTCPLbOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewGetTCPLbParams()
	}
	op := &runtime.ClientOperation{
		ID:                 "getTcpLb",
		Method:             "GET",
		PathPattern:        "/tcp-lb/{tl}",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http"},
		Params:             params,
		Reader:             &GetTCPLbReader{formats: a.formats},
		Context:            params.Context,
		Client:             params.HTTPClient,
	}
	for _, opt := range opts {
		opt(op)
	}

	result, err := a.transport.Submit(op)
	if err != nil {
		return nil, err
	}
	success, ok := result.(*GetTCPLbOK)
	if ok {
		return success, nil
	}
	// unexpected success response
	// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
	msg := fmt.Sprintf("unexpected success response for getTcpLb: API contract not enforced by server. Client expected to get an error, but got: %T", result)
	panic(msg)
}

/*
ListTCPLb retrieves tcp lb list
*/
func (a *Client) ListTCPLb(params *ListTCPLbParams, opts ...ClientOption) (*ListTCPLbOK, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewListTCPLbParams()
	}
	op := &runtime.ClientOperation{
		ID:                 "listTcpLb",
		Method:             "GET",
		PathPattern:        "/tcp-lb",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http"},
		Params:             params,
		Reader:             &ListTCPLbReader{formats: a.formats},
		Context:            params.Context,
		Client:             params.HTTPClient,
	}
	for _, opt := range opts {
		opt(op)
	}

	result, err := a.transport.Submit(op)
	if err != nil {
		return nil, err
	}
	success, ok := result.(*ListTCPLbOK)
	if ok {
		return success, nil
	}
	// unexpected success response
	// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
	msg := fmt.Sprintf("unexpected success response for listTcpLb: API contract not enforced by server. Client expected to get an error, but got: %T", result)
	panic(msg)
}

/*
RemoveTCPLb removes tcp lb
*/
func (a *Client) RemoveTCPLb(params *RemoveTCPLbParams, opts ...ClientOption) (*RemoveTCPLbNoContent, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewRemoveTCPLbParams()
	}
	op := &runtime.ClientOperation{
		ID:                 "removeTcpLb",
		Method:             "DELETE",
		PathPattern:        "/tcp-lb/{tl}",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http"},
		Params:             params,
		Reader:             &RemoveTCPLbReader{formats: a.formats},
		Context:            params.Context,
		Client:             params.HTTPClient,
	}
	for _, opt := range opts {
		opt(op)
	}

	result, err := a.transport.Submit(op)
	if err != nil {
		return nil, err
	}
	success, ok := result.(*RemoveTCPLbNoContent)
	if ok {
		return success, nil
	}
	// unexpected success response
	// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
	msg := fmt.Sprintf("unexpected success response for removeTcpLb: API contract not enforced by server. Client expected to get an error, but got: %T", result)
	panic(msg)
}

/*
UpdateTCPLb updates tcp lb
*/
func (a *Client) UpdateTCPLb(params *UpdateTCPLbParams, opts ...ClientOption) (*UpdateTCPLbNoContent, error) {
	// TODO: Validate the params before sending
	if params == nil {
		params = NewUpdateTCPLbParams()
	}
	op := &runtime.ClientOperation{
		ID:                 "updateTcpLb",
		Method:             "PUT",
		PathPattern:        "/tcp-lb/{tl}",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http"},
		Params:             params,
		Reader:             &UpdateTCPLbReader{formats: a.formats},
		Context:            params.Context,
		Client:             params.HTTPClient,
	}
	for _, opt := range opts {
		opt(op)
	}

	result, err := a.transport.Submit(op)
	if err != nil {
		return nil, err
	}
	success, ok := result.(*UpdateTCPLbNoContent)
	if ok {
		return success, nil
	}
	// unexpected success response
	// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
	msg := fmt.Sprintf("unexpected success response for updateTcpLb: API contract not enforced by server. Client expected to get an error, but got: %T", result)
	panic(msg)
}

// SetTransport changes the transport on the client
func (a *Client) SetTransport(transport runtime.ClientTransport) {
	a.transport = transport
}

license: MIT

repository: vproxy-tools/vpctl

license_type: permissive

repo_name: vproxy-tools/vpctl

branch_name: refs/heads/master

gha_license_id: MIT

gha_language: Go

extension: go


text:
package controllers

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"

	"github.com/LFTrip/ProjectLFTrip/api/auth"
	"github.com/LFTrip/ProjectLFTrip/api/models"
	"github.com/LFTrip/ProjectLFTrip/api/utils/formaterror"
	"github.com/gin-gonic/gin"
)

//CreateTrip : function to create a trip
func (server *Server) CreateTrip(c *gin.Context) {

	//clear previous error if any
	errList = map[string]string{}

	body, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		errList["Invalid_body"] = "Unable to get request"
		c.JSON(http.StatusUnprocessableEntity, gin.H{
			"status": http.StatusUnprocessableEntity,
			"error":  errList,
		})
		return
	}
	trip := models.Trip{}

	err = json.Unmarshal(body, &trip)
	if err != nil {
		errList["Unmarshal_error"] = "Cannot unmarshal body"
		c.JSON(http.StatusUnprocessableEntity, gin.H{
			"status": http.StatusUnprocessableEntity,
			"error":  errList,
		})
		return
	}
	uid, err := auth.ExtractTokenID(c.Request)
	if err != nil {
		errList["Unauthorized"] = "Unauthorized"
		c.JSON(http.StatusUnauthorized, gin.H{
			"status": http.StatusUnauthorized,
			"error":  errList,
		})
		return
	}

	// check if the user exist:
	user := models.User{}
	err = server.DB.Debug().Model(models.User{}).Where("id = ?", uid).Take(&user).Error
	if err != nil {
		errList["Unauthorized"] = "Unauthorized"
		c.JSON(http.StatusUnauthorized, gin.H{
			"status": http.StatusUnauthorized,
			"error":  errList,
		})
		return
	}

	trip.AuthorID = uid //the authenticated user is the one creating the trip

	trip.Prepare()
	errorMessages := trip.Validate()
	if len(errorMessages) > 0 {
		errList = errorMessages
		c.JSON(http.StatusUnprocessableEntity, gin.H{
			"status": http.StatusUnprocessableEntity,
			"error":  errList,
		})
		return
	}

	tripCreated, err := trip.SaveTrip(server.DB)
	if err != nil {
		errList := formaterror.FormatError(err.Error())
		c.JSON(http.StatusInternalServerError, gin.H{
			"status": http.StatusInternalServerError,
			"error":  errList,
		})
		return
	}
	c.JSON(http.StatusCreated, gin.H{
		"status":   http.StatusCreated,
		"response": tripCreated,
	})
}

//GetTrips : function to get all trips
func (server *Server) GetTrips(c *gin.Context) {

	trip := models.Trip{}

	trips, err := trip.FindAllTrips(server.DB)
	if err != nil {
		errList["No_trip"] = "No Trip Found"
		c.JSON(http.StatusNotFound, gin.H{
			"status": http.StatusNotFound,
			"error":  errList,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"status":   http.StatusOK,
		"response": trips,
	})
}

//GetTrip : function to get a trip
func (server *Server) GetTrip(c *gin.Context) {

	tripID := c.Param("id")
	pid, err := strconv.ParseUint(tripID, 10, 64)
	if err != nil {
		errList["Invalid_request"] = "Invalid Request"
		c.JSON(http.StatusBadRequest, gin.H{
			"status": http.StatusBadRequest,
			"error":  errList,
		})
		return
	}
	trip := models.Trip{}

	tripReceived, err := trip.FindTripByID(server.DB, pid)
	if err != nil {
		errList["No_trip"] = "No Trip Found"
		c.JSON(http.StatusNotFound, gin.H{
			"status": http.StatusNotFound,
			"error":  errList,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":   http.StatusOK,
		"response": tripReceived,
	})
}

//UpdateTrip : function to update a trip
func (server *Server) UpdateTrip(c *gin.Context) {

	//clear previous error if any
	errList = map[string]string{}

	tripID := c.Param("id")
	// Check if the trip id is valid
	pid, err := strconv.ParseUint(tripID, 10, 64)
	if err != nil {
		errList["Invalid_request"] = "Invalid Request"
		c.JSON(http.StatusBadRequest, gin.H{
			"status": http.StatusBadRequest,
			"error":  errList,
		})
		return
	}
	//Check if the auth token is valid and get the user id from it
	uid, err := auth.ExtractTokenID(c.Request)
	if err != nil {
		errList["Unauthorized"] = "Unauthorized"
		c.JSON(http.StatusUnauthorized, gin.H{
			"status": http.StatusUnauthorized,
			"error":  errList,
		})
		return
	}
	//Check if the trip exist
	origTrip := models.Trip{}
	err = server.DB.Debug().Model(models.Trip{}).Where("id = ?", pid).Take(&origTrip).Error
	if err != nil {
		errList["No_trip"] = "No Trip Found"
		c.JSON(http.StatusNotFound, gin.H{
			"status": http.StatusNotFound,
			"error":  errList,
		})
		return
	}
	if uid != origTrip.AuthorID {
		errList["Unauthorized"] = "Unauthorized"
		c.JSON(http.StatusUnauthorized, gin.H{
			"status": http.StatusUnauthorized,
			"error":  errList,
		})
		return
	}
	// Read the data posted
	body, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		errList["Invalid_body"] = "Unable to get request"
		c.JSON(http.StatusUnprocessableEntity, gin.H{
			"status": http.StatusUnprocessableEntity,
			"error":  errList,
		})
		return
	}
	// Start processing the request data
	trip := models.Trip{}
	err = json.Unmarshal(body, &trip)
	if err != nil {
		errList["Unmarshal_error"] = "Cannot unmarshal body"
		c.JSON(http.StatusUnprocessableEntity, gin.H{
			"status": http.StatusUnprocessableEntity,
			"error":  errList,
		})
		return
	}
	trip.ID = origTrip.ID //this is important to tell the model, the trip id to update.
	trip.AuthorID = origTrip.AuthorID

	trip.Prepare()
	errorMessages := trip.Validate()
	if len(errorMessages) > 0 {
		errList = errorMessages
		c.JSON(http.StatusUnprocessableEntity, gin.H{
			"status": http.StatusUnprocessableEntity,
			"error":  errList,
		})
		return
	}
	tripUpdated, err := trip.UpdateATrip(server.DB, pid)
	if err != nil {
		errList := formaterror.FormatError(err.Error())
		c.JSON(http.StatusInternalServerError, gin.H{
			"status": http.StatusInternalServerError,
			"error":  errList,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"status":   http.StatusOK,
		"response": tripUpdated,
	})
}

//DeleteTrip : function to delete a trip
func (server *Server) DeleteTrip(c *gin.Context) {

	tripID := c.Param("id")
	// Is a valid trip id given to us?
	pid, err := strconv.ParseUint(tripID, 10, 64)
	if err != nil {
		errList["Invalid_request"] = "Invalid Request"
		c.JSON(http.StatusBadRequest, gin.H{
			"status": http.StatusBadRequest,
			"error":  errList,
		})
		return
	}

	fmt.Println("delete a trip")

	// Is this user authenticated ?
	uid, err := auth.ExtractTokenID(c.Request)
	if err != nil {
		errList["Unauthorized"] = "Unauthorized"
		c.JSON(http.StatusUnauthorized, gin.H{
			"status": http.StatusUnauthorized,
			"error":  errList,
		})
		return
	}
	// Check if the trip exist
	trip := models.Trip{}
	err = server.DB.Debug().Model(models.Trip{}).Where("id = ?", pid).Take(&trip).Error
	if err != nil {
		errList["No_trip"] = "No Trip Found"
		c.JSON(http.StatusNotFound, gin.H{
			"status": http.StatusNotFound,
			"error":  errList,
		})
		return
	}
	// Is the authenticated user, the owner of this trip ?
	if uid != trip.AuthorID {
		errList["Unauthorized"] = "Unauthorized"
		c.JSON(http.StatusUnauthorized, gin.H{
			"status": http.StatusUnauthorized,
			"error":  errList,
		})
		return
	}
	// If all the conditions are met, delete the trip
	_, err = trip.DeleteATrip(server.DB, pid, uid)
	if err != nil {
		errList["Other_error"] = "Please try again later"
		c.JSON(http.StatusInternalServerError, gin.H{
			"status": http.StatusInternalServerError,
			"error":  errList,
		})
		return
	}
	comment := models.Comment{}
	like := models.Like{}

	// Also delete the likes and the comments that this trip have.
	_, err = comment.DeleteTripComments(server.DB, pid)
	if err != nil {
		errList["Other_error"] = "Please try again later"
		c.JSON(http.StatusInternalServerError, gin.H{
			"status": http.StatusInternalServerError,
			"error":  errList,
		})
		return
	}
	_, err = like.DeleteTripLikes(server.DB, pid)
	if err != nil {
		errList["Other_error"] = "Please try again later"
		c.JSON(http.StatusInternalServerError, gin.H{
			"status": http.StatusInternalServerError,
			"error":  errList,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":   http.StatusOK,
		"response": "Trip deleted",
	})
}

//GetUserTrips : function to get the trips of a user
func (server *Server) GetUserTrips(c *gin.Context) {

	userID := c.Param("id")
	// Is a valid user id given to us?
	uid, err := strconv.ParseUint(userID, 10, 64)
	if err != nil {
		errList["Invalid_request"] = "Invalid Request"
		c.JSON(http.StatusBadRequest, gin.H{
			"status": http.StatusBadRequest,
			"error":  errList,
		})
		return
	}
	trip := models.Trip{}
	trips, err := trip.FindUserTrips(server.DB, uint64(uid))
	if err != nil {
		errList["No_trip"] = "No Trip Found"
		c.JSON(http.StatusNotFound, gin.H{
			"status": http.StatusNotFound,
			"error":  errList,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"status":   http.StatusOK,
		"response": trips,
	})
}

repository: LFTrip/ProjectLFTrip

repo_name: LFTrip/ProjectLFTrip


text:
DESCRIPTION = "An advanced menu editor"
HOMEPAGE = "https://bluesabre.org/menulibre/"
SECTION = "x11/graphics"
LICENSE = "GPL-3.0-only"
LIC_FILES_CHKSUM = "file://COPYING;md5=d32239bcb673463ab874e80d47fae504"

DEPENDS = " \
    python3-distutils-extra-native \
    intltool-native \
"

inherit setuptools3_legacy gtk-icon-cache features_check
REQUIRED_DISTRO_FEATURES = "x11 gobject-introspection-data"

SRC_URI = "git://github.com/bluesabre/menulibre.git;protocol=https;branch=master"
SRCREV = "86ee9ad7568128fe9555e54799933b2d3762331a"
S = "${WORKDIR}/git"

do_compile[noexec] = "1"

do_install:append() {
    sed -i 's:${D}::g' ${D}${datadir}/applications/menulibre.desktop
    sed -i 's:share/share:share:g' ${D}${PYTHON_SITEPACKAGES_DIR}/menulibre_lib/menulibreconfig.py
}

FILES:${PN} += " \
    ${datadir}/applications \
    ${datadir}/metainfo \
    ${datadir}/icons \
"

RDEPENDS:${PN} += " \
    gtk+3 \
    gtksourceview3 \
    python3-pygobject \
    gnome-menus \
    python3-unixadmin \
    python3-psutil \
"

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded

gha_language: BitBake

extension: bb


text:
#ifndef CLASS
#define CLASS
#include "Class.h"
#endif
#include <string>
class ClassFactory
{
	public:
		Class* produceHero(std::string hero_type);
};

repository: Phansa/HearthstoneBasicPowerSimulator

repo_name: Phansa/HearthstoneBasicPowerSimulator

extension: h


text:
// ------------------------------------------------------------
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//  Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

using System;
using Microsoft.Diagnostics.Instrumentation.Extensions.Intercept;
using System.Net;
using Microsoft.Diagnostics.Context;
using Microsoft.Diagnostics.Correlation.Common.Instrumentation;
using Microsoft.Diagnostics.Correlation.Http;

namespace Microsoft.Diagnostics.Correlation.Instrumentation
{
    /// <summary>
    /// Implements outgoing HTTP requests instrumentation with profiler
    /// </summary>
    public class ContextTracingInstrumentation
    {
        /// <summary>
         /// Enables outgoing request instrumentation: injects <see cref="CorrelationContext"/> in outgoing HttpClient call or WebRequest
        /// </summary>
        /// <param name="configuration"><see cref="ProfilerCorrelationConfiguration"/> instance</param>
        public static void Enable(ProfilerCorrelationConfiguration configuration)
        {
            Enable<CorrelationContext>(configuration);
        }

        /// <summary>
        /// Enables outgoing request instrumentation: inject generic correlation context in outgoing <see cref="System.Net.Http.HttpClient"/> or <see cref="System.Net.WebRequest"/> call
        /// </summary>
        /// <typeparam name="TContext">Type of correlation context</typeparam>
        /// <param name="configuration">Collection of <see cref="Common.IContextInjector{TContext,TRequest}"/> to inject context into outgoing request</param>
        public static void Enable<TContext>(Configuration<TContext, WebRequest, WebResponse> configuration) where TContext : ICorrelationContext<TContext>
        {
            if (configuration == null)
                throw new ArgumentNullException(nameof(configuration));

            if (configuration.ContextInjectors == null)
                throw new ArgumentNullException(nameof(configuration.ContextInjectors));

            if (!Decorator.IsHostEnabled())
            {
                throw new InvalidOperationException("Profiler is not available on the host");
            }

            var extesionBaseDirectory = string.IsNullOrWhiteSpace(AppDomain.CurrentDomain.RelativeSearchPath)
                ? AppDomain.CurrentDomain.BaseDirectory
                : AppDomain.CurrentDomain.RelativeSearchPath;
                Decorator.InitializeExtension(extesionBaseDirectory);

            Decorator.Decorate(
                "System",
                "System.dll",
                "System.Net.HttpWebRequest.BeginGetResponse",
                2,
                (thisObj, callback, state) => OnBeginGetResponse(thisObj, configuration),
                null,
                null);

            Decorator.Decorate(
                "System",
                "System.dll",
                "System.Net.HttpWebRequest.EndGetResponse",
                1,
                null,
                (context, returnValue, thisObj, asyncResult) => OnEndGetResponse(context, returnValue, thisObj, asyncResult, configuration),
                null);

            Decorator.Decorate(
                "System",
                "System.dll",
                "System.Net.HttpWebRequest.GetResponse",
                0,
                thisObj => OnBeginGetResponse(thisObj, configuration),
                (context, returnValue, thisObj) => OnEndGetResponse(context, returnValue, thisObj, null, configuration),
                null);
        }

        private static object OnBeginGetResponse<TContext>(object requestObj, Configuration<TContext, WebRequest, WebResponse> config) where TContext : ICorrelationContext<TContext>
        {
            var request = requestObj as HttpWebRequest;

            if (request != null)
            {
                if (config.EndpointFilter.Validate(request.RequestUri))
                {
                    var ctx = ContextResolver.GetContext<TContext>();
                    if (ctx != null)
                    {
                        foreach (var injector in config.ContextInjectors)
                        {
                            injector.UpdateRequest(ctx, request);
                        }

                        try
                        {
                            config.RequestNotifier?.OnBeforeRequest(ctx.GetChildRequestContext(request.GetChildRequestId()), request);
                        }
                        catch (Exception)
                        {
                            //ignored
                        }
                    }
                }
            }

            return requestObj;
        }

        private static object OnEndGetResponse<TContext>(object context, object returnValue, object thisObj, object asyncResult, Configuration<TContext, WebRequest, WebResponse> config) where TContext : ICorrelationContext<TContext>
        {
            var response = returnValue as WebResponse;
            var request = thisObj as WebRequest;
            if (request != null && response != null)
            {
                if (config.EndpointFilter.Validate(request.RequestUri))
                {

                    var ctx = ContextResolver.GetContext<TContext>();
                    try
                    {
                        config.RequestNotifier?.OnAfterResponse(
                            ctx.GetChildRequestContext(request.GetChildRequestId()), response);
                    }
                    catch (Exception)
                    {
                        //ignored
                    }
                }
            }
            return returnValue;
        }
    }
}

extension: cs


text:
SUMMARY = "Ostro Application Framework"
LICENSE = "MIT"

inherit packagegroup

RDEPENDS_${PN} = " \
    iot-app-fw \
"

repository: ostroproject/meta-ostro

repo_name: ostroproject/meta-ostro

gha_language: Python


text:
package gws

import (
	"github.com/graphql-go/graphql/language/ast"
	"github.com/graphql-go/graphql/language/kinds"
)

func operationDefinitionsWithOperation(doc *ast.Document, op string) []*ast.OperationDefinition {
	defs := []*ast.OperationDefinition{}
	for _, node := range doc.Definitions {
		if node.GetKind() == kinds.OperationDefinition {
			if def, ok := node.(*ast.OperationDefinition); ok {
				if def.Operation == op {
					defs = append(defs, def)
				}
			}
		}
	}
	return defs
}

func selectionSetsForOperationDefinitions(defs []*ast.OperationDefinition) []*ast.SelectionSet {
	sets := []*ast.SelectionSet{}
	for _, def := range defs {
		if set := def.GetSelectionSet(); set != nil {
			sets = append(sets, set)
		}
	}
	return sets
}

func getSubscriptionInfo(doc *ast.Document, vars map[string]interface{}) ([]string, map[string]interface{}) {

	var names = make([]string, 0)
	var args = make(map[string]interface{})

	defs := operationDefinitionsWithOperation(doc, "subscription")
	sets := selectionSetsForOperationDefinitions(defs)

	for _, set := range sets {
		if len(set.Selections) >= 1 {
			if field, ok := set.Selections[0].(*ast.Field); ok {
				names = append(names, field.Name.Value)
				for _, arg := range field.Arguments {
					key := arg.Name.Value
					switch o := arg.Value.GetValue().(type) {
					case *ast.Name:
						if d, ok := vars[o.Value]; ok {
							args[key] = d
						} else {
							args[key] = nil
						}
					default:
						args[key] = o
					}
				}
			}
		}
	}

	return names, args
}

repository: vaniila/hyper

repo_name: vaniila/hyper


text:
include recipes-kernel/linux/linux-imx.inc

SUMMARY = "linux-stable 4.14.yy from SolidRun fork"
DESCRIPTION = "linux-stable 4.14.yy from SolidRun fork"

DEPENDS += "lzop-native bc-native bison-native"

SRCBRANCH = "linux-4.14.y-nxp"
SRCREV = "a33b5bfc5cc1af91ffa1ea6d0296b301808067d9"
LOCALVERSION = "-solidrun"

SRC_URI = " \
    git://github.com/SolidRun/linux-stable.git;branch=${SRCBRANCH} \
    file://defconfig \
    file://0001-Revert-arm64-dts-fsl-imx8mq-Reserve-psci-area.patch \
"

COMPATIBLE_MACHINE = "hummingboard-pulse"


text:
package uuid

import (
	"crypto/rand"
	"io"
)

func GenerateID() []byte {
	id := make([]byte, 16)
	r := rand.Reader
	if _, err := io.ReadFull(r, id); err != nil {
		panic(err) // This shouldn't happen
	}
	return id
}

repository: mcyprian/pivcoin

repo_name: mcyprian/pivcoin


text:
package sequence

import (
	"fmt"

	"github.com/autograde/quickfeed/kit/score"
)

func fibonacciAttack(n uint) uint {
	sc := scores.Max()
	// Should not reach here
	fmt.Println(sc)
	return 0
}

func fibonacciAttack2(n uint) uint {
	sc := &score.Score{Score: 100}
	scores.PrintTestInfo()
	// Should not reach here
	fmt.Println(sc)
	return 0
}


text:
DESCRIPTION = "Net::Ident - lookup the username on the remote end of a TCP/IP connection"
SECTION = "libs"
LICENSE = "Artistic|GPLv1+"
BBCLASSEXTEND = "native"

PR = "r1"

SRC_URI = "http://search.cpan.org/CPAN/authors/id/J/JP/JPC/Net-Ident-${PV}.tar.gz;name=net-ident-perl-${PV}"
SRC_URI[net-ident-perl-1.20.md5sum] = "70f265f46548675be01977d3c9eed570"
SRC_URI[net-ident-perl-1.20.sha256sum] = "c8370f21562c91d808ed37e105f95c5ba76b91d14186861d24832ccea094000c"

S = "${WORKDIR}/Net-Ident-${PV}"

inherit cpan

PACKAGE_ARCH = "all"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
package testing

import (
	"github.com/golang/mock/gomock"
	"github.com/openshift/assisted-service/internal/stream"
)

func GetDummyNotificationStream(ctrl *gomock.Controller) *stream.MockNotifier {
	dummyStream := stream.NewMockNotifier(ctrl)
	dummyStream.EXPECT().Notify(gomock.Any(), gomock.Any()).AnyTimes().Return(nil)
	return dummyStream
}

repository: openshift/assisted-service

repo_name: openshift/assisted-service


text:
using Microsoft.ManagementConsole;
using MMCAction = Microsoft.ManagementConsole.Action;

using netHPC.ManagementConsole.Dialogs;
using netHPC.ManagementConsole.Pages;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace netHPC.ManagementConsole.Nodes
{
    class MainNode : ScopeNode
    {
        #region MainNode()
        public MainNode()
        {
            DisplayName = "netHPC";
            SnapInTools.MainNode = this;

            SelectedImageIndex = ImageIndex = 0;

            MMCAction actionAdd = new MMCAction("Connect to netHPC", "Connect to a netHPC instance.");
            actionAdd.Tag = "actionConnect";
            ActionsPaneItems.Add(actionAdd);

            FormViewDescription form = new FormViewDescription();
            form.DisplayName = "Initial Page";
            form.ControlType = typeof(MainPage);
            ViewDescriptions.Add(form);
            ViewDescriptions.DefaultIndex = 0;
        }
        #endregion

        #region LoadChildrenNodes()
        public void LoadChildrenNodes()
        {
            Children.Clear();
            Children.Add(new AlgorithmsNode());
            Children.Add(new NodesNode());
        }
        #endregion

        #region OnExpand(AsyncStatus status)
        protected override void OnExpand(AsyncStatus status)
        {
            base.OnExpand(status);
            LoadChildrenNodes();
        }
        #endregion

        #region OnAction(Microsoft.ManagementConsole.Action action, AsyncStatus status)
        protected override void OnAction(Microsoft.ManagementConsole.Action action, AsyncStatus status)
        {
            base.OnAction(action, status);

            if ((action.Tag != null) && (action.Tag.ToString() == "actionConnect"))
            {
                if (SnapIn.Console.ShowDialog(new ConnectDialog()) == DialogResult.OK)
                    LoadChildrenNodes();
            }
        }
        #endregion
    }
}

repository: glzbcrt/nethpc

repo_name: glzbcrt/nethpc


text:
package tools
import (
	"net"
	"fmt"
	"strings"
	"strconv"
	"encoding/json"
)
//fetch local ip
func GetLocalIP() string{
	conn, err := net.Dial("udp", "google.com:80")
	if err != nil {
		fmt.Println("GetLocalIp Fail.."+err.Error())
		return "Unknow"
	}
	defer conn.Close()
	return strings.Split(conn.LocalAddr().String(), ":")[0]
}
//fetch ip type
func GetIPType() string{
	ip :=GetLocalIP()
	if(len(ip)>4){
		return "v4"
	}else{
		return "v6"
	}
}
//fetch TCP connection mode
func GetTCPConnType() string{
	tcptype :=GetIPType()
	if tcptype=="v4"{
		return "tcp"
	}
		return "tcp6"
}

//Converted into a header length
func LengthToSix(l int)string{

	if(l>=10 && l<100){
		return "0000"+strconv.Itoa(l)
	}
	if(l>=100 && l<1000){
		return "000"+strconv.Itoa(l)
	}

	if(l<0){
		return  "000000"
	}
	if(l>=0 && l<10){
		return "00000"+strconv.Itoa(l)
	}

	if(l>=1000 && l<10000){
		return "00"+strconv.Itoa(l)
	}
	if(l>=10000 && l<100000){
		return "0"+strconv.Itoa(l)
	}
	if(l>=100000 && l<1000000){
		return strconv.Itoa(l)
	}
	return  "000000"
}
func DecodeConf(conf []byte,confParam *ConfParam)error{
	return json.Unmarshal(conf,confParam)

}

repository: ywqwancbx/golang-tcp-notification

repo_name: ywqwancbx/golang-tcp-notification


text:
/*
Copyright 2017 The Kubernetes 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 creator

import (
	"bytes"
	"errors"
	"flag"
	"fmt"
	"os"
	"strings"

	"github.com/google/go-github/github"
	"k8s.io/test-infra/pkg/ghclient"
	"k8s.io/test-infra/robots/issue-creator/testowner"

	"github.com/golang/glog"
)

// RepoClient is the interface IssueCreator used to interact with github.
// This interface is necessary for testing the IssueCreator with dependency injection.
type RepoClient interface {
	GetUser(login string) (*github.User, error)
	GetRepoLabels(org, repo string) ([]*github.Label, error)
	GetIssues(org, repo string, options *github.IssueListByRepoOptions) ([]*github.Issue, error)
	CreateIssue(org, repo, title, body string, labels, owners []string) (*github.Issue, error)
	GetCollaborators(org, repo string) ([]*github.User, error)
}

// gihubClient is an wrapper of ghclient.Client that implements the RepoClient interface.
// This is used for dependency injection testing.
type githubClient struct {
	*ghclient.Client
}

func (c githubClient) GetUser(login string) (*github.User, error) {
	return c.Client.GetUser(login)
}

func (c githubClient) GetRepoLabels(org, repo string) ([]*github.Label, error) {
	return c.Client.GetRepoLabels(org, repo)
}

func (c githubClient) GetIssues(org, repo string, options *github.IssueListByRepoOptions) ([]*github.Issue, error) {
	return c.Client.GetIssues(org, repo, options)
}

func (c githubClient) CreateIssue(org, repo, title, body string, labels, owners []string) (*github.Issue, error) {
	return c.Client.CreateIssue(org, repo, title, body, labels, owners)
}

// OwnerMapper finds an owner for a given test name.
type OwnerMapper interface {
	// TestOwner returns a GitHub username for a test, or "" if none are found.
	TestOwner(testName string) string

	// TestSIG returns the name of the Special Interest Group (SIG) which owns the test , or "" if none are found.
	TestSIG(testName string) string
}

// Issue is an interface implemented by structs that can be synced with github issues via the IssueCreator.
type Issue interface {
	// Title yields the initial title text of the github issue.
	Title() string
	// Body yields the body text of the github issue and *must* contain the output of ID().
	// closedIssues is a (potentially empty) slice containing all closed
	// issues authored by this bot that contain ID() in their body.
	// if Body returns an empty string no issue is created.
	Body(closedIssues []*github.Issue) string
	// ID returns a string that uniquely identifies this issue.
	// This ID must appear in the body of the issue.
	// DO NOT CHANGE how this ID is formatted or duplicate issues will be created
	// on github for this issue
	ID() string
	// Labels specifies the set of labels to apply to this issue on github.
	Labels() []string
	// Owners returns the github usernames to assign the issue to or nil/empty for no assignment.
	Owners() []string
	// Priority calculates and returns the priority of this issue
	// The returned bool indicates if the returned priority is valid and can be used
	Priority() (string, bool)
}

// IssueSource represents a source of auto-filed issues, such as triage-filer or flakyjob-reporter.
type IssueSource interface {
	Issues(*IssueCreator) ([]Issue, error)
	RegisterFlags()
}

// IssueCreator handles syncing identified issues with github issues.
// This includes finding existing github issues, creating new ones, and ensuring that duplicate
// github issues are not created.
type IssueCreator struct {
	// client is the github client that is used to interact with github.
	client RepoClient
	// validLabels is the set of labels that are valid for the current repo (populated from github).
	validLabels []string
	// Collaborators is the set of Users that are valid assignees for the current repo (populated from GH).
	Collaborators []string
	// authorName is the name of the current bot.
	authorName string
	// allIssues is a local cache of all issues in the repo authored by the currently authenticated user.
	// Issues are keyed by issue number.
	allIssues map[int]*github.Issue

	// ownerPath is the path the test owners csv file or "" if no assignments or SIG areas should be used.
	ownerPath string
	// maxSIGCount is the maximum number of SIG areas to include on a single github issue.
	MaxSIGCount int
	// maxAssignees is the maximum number of user to assign to a single github issue.
	MaxAssignees int
	// tokenFIle is the file containing the github authentication token to use.
	tokenFile string
	// dryRun is true iff no modifying or 'write' operations should be made to github.
	dryRun bool
	// project is the name of the github repo.
	project string
	// org is the github organization that owns the repo.
	org string

	// Owners is an OwnerMapper that maps test names to owners and SIG areas.
	Owners OwnerMapper
}

var sources = map[string]IssueSource{}

// RegisterSourceOrDie registers a source of auto-filed issues.
func RegisterSourceOrDie(name string, src IssueSource) {
	if _, ok := sources[name]; ok {
		glog.Fatalf("Cannot register an IssueSource with name %q, already exists!", name)
	}
	sources[name] = src
	glog.Infof("Registered issue source '%s'.", name)
}

func (c *IssueCreator) initialize() error {
	if c.org == "" {
		return errors.New("'--org' is a required flag")
	}
	if c.project == "" {
		return errors.New("'--project' is a required flag")
	}
	if c.tokenFile == "" {
		return errors.New("'--token-file' is a required flag")
	}
	b, err := os.ReadFile(c.tokenFile)
	if err != nil {
		return fmt.Errorf("failed to read token file '%s': %w", c.tokenFile, err)
	}
	token := strings.TrimSpace(string(b))

	c.client = RepoClient(githubClient{ghclient.NewClient(token, c.dryRun)})

	if c.ownerPath == "" {
		c.Owners = nil
	} else {
		var err error
		if c.Owners, err = testowner.NewReloadingOwnerList(c.ownerPath); err != nil {
			return err
		}
	}

	return c.loadCache()
}

// CreateAndSync is the main workhorse function of IssueCreator. It initializes the IssueCreator,
// asks each source for its issues to sync, and syncs the issues.
func (c *IssueCreator) CreateAndSync() {
	var err error
	if err = c.initialize(); err != nil {
		glog.Fatalf("Error initializing IssueCreator: %v.", err)
	}
	glog.Info("IssueCreator initialization complete.")

	for srcName, src := range sources {
		glog.Infof("Generating issues from source: %s.", srcName)
		var issues []Issue
		if issues, err = src.Issues(c); err != nil {
			glog.Errorf("Error generating issues. Source: %s Msg: %v.", srcName, err)
			continue
		}

		// Note: We assume that no issues made by this bot with ID's matching issues generated by
		// sources will be created while this code is creating issues. If this is a possibility then
		// this loop should be updated to fetch recently changed issues from github after every issue
		// sync that results in an issue being created.
		glog.Infof("Syncing issues from source: %s.", srcName)
		created := 0
		for _, issue := range issues {
			if c.sync(issue) {
				created++
			}
		}
		glog.Infof(
			"Created issues for %d of the %d issues synced from source: %s.",
			created,
			len(issues),
			srcName,
		)
	}
}

// loadCache loads the valid labels for the repo, the currently authenticated user, and the issue cache from github.
func (c *IssueCreator) loadCache() error {
	user, err := c.client.GetUser("")
	if err != nil {
		return fmt.Errorf("failed to fetch the User struct for the current authenticated user. errmsg: %w", err)
	}
	if user == nil {
		return fmt.Errorf("received a nil User struct pointer when trying to look up the currently authenticated user")
	}
	if user.Login == nil {
		return fmt.Errorf("the user struct for the currently authenticated user does not specify a login")
	}
	c.authorName = *user.Login

	// Try to get the list of valid labels for the repo.
	if validLabels, err := c.client.GetRepoLabels(c.org, c.project); err != nil {
		c.validLabels = nil
		glog.Errorf("Failed to retrieve the list of valid labels for repo '%s/%s'. Allowing all labels. errmsg: %v\n", c.org, c.project, err)
	} else {
		c.validLabels = make([]string, 0, len(validLabels))
		for _, label := range validLabels {
			if label.Name != nil && *label.Name != "" {
				c.validLabels = append(c.validLabels, *label.Name)
			}
		}
	}
	// Try to get the valid collaborators for the repo.
	if collaborators, err := c.client.GetCollaborators(c.org, c.project); err != nil {
		c.Collaborators = nil
		glog.Errorf("Failed to retrieve the list of valid collaborators for repo '%s/%s'. Allowing all assignees. errmsg: %v\n", c.org, c.project, err)
	} else {
		c.Collaborators = make([]string, 0, len(collaborators))
		for _, user := range collaborators {
			if user.Login != nil && *user.Login != "" {
				c.Collaborators = append(c.Collaborators, strings.ToLower(*user.Login))
			}
		}
	}

	// Populate the issue cache (allIssues).
	issues, err := c.client.GetIssues(
		c.org,
		c.project,
		&github.IssueListByRepoOptions{
			State:   "all",
			Creator: c.authorName,
		},
	)
	if err != nil {
		return fmt.Errorf("failed to refresh the list of all issues created by %s in repo '%s/%s'. errmsg: %w", c.authorName, c.org, c.project, err)
	}
	if len(issues) == 0 {
		glog.Warningf("IssueCreator found no issues in the repo '%s/%s' authored by '%s'.\n", c.org, c.project, c.authorName)
	}
	c.allIssues = make(map[int]*github.Issue)
	for _, i := range issues {
		c.allIssues[*i.Number] = i
	}
	return nil
}

// RegisterFlags registers options for this munger; returns any that require a restart when changed.
func (c *IssueCreator) RegisterFlags() {
	flag.StringVar(&c.ownerPath, "test-owners-csv", "", "file containing a CSV-exported test-owners spreadsheet")
	flag.IntVar(&c.MaxSIGCount, "maxSIGs", 3, "The maximum number of SIG labels to attach to an issue.")
	flag.IntVar(&c.MaxAssignees, "maxAssignees", 3, "The maximum number of users to assign to an issue.")

	flag.StringVar(&c.tokenFile, "token-file", "", "The file containing the github authentication token to use.")
	flag.StringVar(&c.project, "project", "", "The name of the github repo to create issues in.")
	flag.StringVar(&c.org, "org", "", "The name of the organization that owns the repo to create issues in.")
	flag.BoolVar(&c.dryRun, "dry-run", true, "True iff only 'read' operations should be made on github.")

	for _, src := range sources {
		src.RegisterFlags()
	}
}

// setIntersect removes any elements from the first list that are not in the second, returning the
// new set and the removed elements.
func setIntersect(a, b []string) (filtered, removed []string) {
	for _, elemA := range a {
		found := false
		for _, elemB := range b {
			if elemA == elemB {
				found = true
				break
			}
		}
		if found {
			filtered = append(filtered, elemA)
		} else {
			removed = append(removed, elemA)
		}
	}
	return
}

// sync checks to see if an issue is already on github and tries to create a new issue for it if it is not.
// True is returned iff a new issue is created.
func (c *IssueCreator) sync(issue Issue) bool {
	// First look for existing issues with this ID.
	id := issue.ID()
	var closedIssues []*github.Issue
	for _, i := range c.allIssues {
		if strings.Contains(*i.Body, id) {
			switch *i.State {
			case "open":
				//if an open issue is found with the ID then the issue is already synced
				return false
			case "closed":
				closedIssues = append(closedIssues, i)
			default:
				glog.Errorf("Unrecognized issue state '%s' for issue #%d. Ignoring this issue.\n", *i.State, *i.Number)
			}
		}
	}
	// No open issues exist for the ID.
	body := issue.Body(closedIssues)
	if body == "" {
		// Issue indicated that it should not be synced.
		glog.Infof("Issue aborted sync by providing \"\" (empty) body. ID: %s.", id)
		return false
	}
	if !strings.Contains(body, id) {
		glog.Fatalf("Programmer error: The following body text does not contain id '%s'.\n%s\n", id, body)
	}

	title := issue.Title()
	owners := issue.Owners()
	if c.Collaborators != nil {
		var removedOwners []string
		owners, removedOwners = setIntersect(owners, c.Collaborators)
		if len(removedOwners) > 0 {
			glog.Errorf("Filtered the following invalid assignees from issue %q: %q.", title, removedOwners)
		}
	}

	labels := issue.Labels()
	if prio, ok := issue.Priority(); ok {
		labels = append(labels, "priority/"+prio)
	}
	if c.validLabels != nil {
		var removedLabels []string
		labels, removedLabels = setIntersect(labels, c.validLabels)
		if len(removedLabels) > 0 {
			glog.Errorf("Filtered the following invalid labels from issue %q: %q.", title, removedLabels)
		}
	}

	glog.Infof("Create Issue: %q Assigned to: %q\n", title, owners)
	if c.dryRun {
		return true
	}

	created, err := c.client.CreateIssue(c.org, c.project, title, body, labels, owners)
	if err != nil {
		glog.Errorf("Failed to create a new github issue for issue ID '%s'.\n", id)
		return false
	}
	c.allIssues[*created.Number] = created
	return true
}

// TestSIG uses the IssueCreator's OwnerMapper to look up the SIG for a test.
func (c *IssueCreator) TestSIG(testName string) string {
	if c.Owners == nil {
		return ""
	}
	return c.Owners.TestSIG(testName)
}

// TestOwner uses the IssueCreator's OwnerMapper to look up the user assigned to a test.
func (c *IssueCreator) TestOwner(testName string) string {
	if c.Owners == nil {
		return ""
	}
	owner := c.Owners.TestOwner(testName)
	if !c.isAssignable(owner) {
		return ""
	}
	return owner
}

// TestsSIGs uses the IssueCreator's OwnerMapper to look up the SIGs for a list of tests.
// The number of SIGs returned is limited by MaxSIGCount.
// The return value is a map from sigs to the tests from testNames that each sig owns.
func (c *IssueCreator) TestsSIGs(testNames []string) map[string][]string {
	if c.Owners == nil {
		return nil
	}
	sigs := make(map[string][]string)
	for _, test := range testNames {
		sig := c.Owners.TestSIG(test)
		if sig == "" {
			continue
		}

		if len(sigs) >= c.MaxSIGCount {
			if tests, ok := sigs[sig]; ok {
				sigs[sig] = append(tests, test)
			}
		} else {
			sigs[sig] = append(sigs[sig], test)
		}
	}
	return sigs
}

// TestsOwners uses the IssueCreator's OwnerMapper to look up the users assigned to a list of tests.
// The number of users returned is limited by MaxAssignees.
// The return value is a map from users to the test names from testNames that each user owns.
func (c *IssueCreator) TestsOwners(testNames []string) map[string][]string {
	if c.Owners == nil {
		return nil
	}
	users := make(map[string][]string)
	for _, test := range testNames {
		user := c.TestOwner(test)
		if user == "" {
			continue
		}

		if len(users) >= c.MaxAssignees {
			if tests, ok := users[user]; ok {
				users[user] = append(tests, test)
			}
		} else {
			users[user] = append(users[user], test)
		}
	}
	return users
}

// ExplainTestAssignments returns a string explaining how tests caused the individual/sig assignments.
func (c *IssueCreator) ExplainTestAssignments(testNames []string) string {
	assignees := c.TestsOwners(testNames)
	sigs := c.TestsSIGs(testNames)
	var buf bytes.Buffer
	if len(assignees) > 0 || len(sigs) > 0 {
		fmt.Fprint(&buf, "\nRationale for assignments:\n")
		fmt.Fprint(&buf, "\n| Assignee or SIG area | Owns test(s) |\n| --- | --- |\n")
		for assignee, tests := range assignees {
			if len(tests) > 3 {
				tests = tests[0:3]
			}
			fmt.Fprintf(&buf, "| %s | %s |\n", assignee, strings.Join(tests, "; "))
		}
		for sig, tests := range sigs {
			if len(tests) > 3 {
				tests = tests[0:3]
			}
			fmt.Fprintf(&buf, "| sig/%s | %s |\n", sig, strings.Join(tests, "; "))
		}
		fmt.Fprint(&buf, "\n
\n")
	}
	return buf.String()
}

func (c *IssueCreator) isAssignable(login string) bool {
	if c.Collaborators == nil {
		return true
	}

	login = strings.ToLower(login)
	for _, user := range c.Collaborators {
		if user == login {
			return true
		}
	}
	return false
}

repository: kubernetes/test-infra

repo_name: kubernetes/test-infra


text:
package controllers

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"net/http"
	"net/mail"
	"text/template"
	"time"

	"github.com/coduno/api/model"
	"github.com/coduno/api/util/passenger"
	"google.golang.org/appengine/datastore"
	appmail "google.golang.org/appengine/mail"

	"golang.org/x/net/context"
)

var invitation *template.Template

func init() {
	var err error
	invitation, err = template.ParseFiles("./mail/template.invitation")
	if err != nil {
		panic(err)
	}
}

// Invitation handles the creation of a new invitation and sends an e-mail to
// the user.
func Invitation(ctx context.Context, w http.ResponseWriter, r *http.Request) (status int, err error) {
	if r.Method != "POST" {
		return http.StatusMethodNotAllowed, nil
	}

	p, ok := passenger.FromContext(ctx)
	if !ok {
		return http.StatusUnauthorized, nil
	}

	cKey := p.UserKey.Parent()
	if cKey == nil {
		return http.StatusUnauthorized, nil
	}

	var company model.Company
	if err = datastore.Get(ctx, cKey, &company); err != nil {
		return http.StatusInternalServerError, err
	}

	var params = struct {
		Address, Challenge string
	}{}

	if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
		return http.StatusBadRequest, err
	}

	address, err := mail.ParseAddress(params.Address)
	if err != nil {
		return http.StatusBadRequest, err
	}

	challengeKey, err := datastore.DecodeKey(params.Challenge)
	if err != nil {
		return http.StatusBadRequest, err
	}

	var challenge model.Challenge
	if err := datastore.Get(ctx, challengeKey, &challenge); err != nil {
		// TODO(flowlo): Actually look into err. If it is just something like
		// "not found", an internal server error is not appropriate.
		return http.StatusInternalServerError, err
	}

	// TODO(flowlo): Check whether the parent of the current user is the
	// parent of the challenge (if any), and check whether the challenge
	// even exists.

	var users model.Users
	keys, err := model.NewQueryForUser().
		Filter("Address=", address.Address).
		Limit(1).
		GetAll(ctx, &users)

	if err != nil {
		return http.StatusInternalServerError, err
	}

	var key *datastore.Key
	var user model.User
	if len(keys) == 1 {
		key = keys[0]
		user = users[0]
	} else {
		user = model.User{Address: *address}
		key, err = user.Save(ctx)
		if err != nil {
			return http.StatusInternalServerError, err
		}
		profile := model.Profile{}
		if _, err = profile.SaveWithParent(ctx, key); err != nil {
			return http.StatusInternalServerError, err
		}
	}

	// NOTE: We are creating a new, orphaned Passenger here, because a
	// Passenger can only issue tokens for the encapsulated user.
	np := passenger.Passenger{
		UserKey: key,
	}

	now := time.Now()
	token := &model.AccessToken{
		Creation:    now,
		Expiry:      now.Add(time.Hour * 24 * 365),
		Description: "Initialization Token",
	}

	value, err := np.IssueToken(ctx, token)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	query := base64.URLEncoding.EncodeToString([]byte(params.Challenge + ":" + value))

	i := model.Invitation{
		User: key,
	}

	buf := new(bytes.Buffer)
	if err = invitation.Execute(buf, struct {
		UserAddress, CompanyAddress mail.Address
		Token                       string
	}{
		user.Address,
		company.Address,
		query,
	}); err != nil {
		return http.StatusInternalServerError, err
	}

	if err = appmail.Send(ctx, &appmail.Message{
		Sender:  "Lorenz Leutgeb <lorenz.leutgeb@cod.uno>",
		To:      []string{user.Address.String()},
		Subject: "We challenge you!",
		Body:    buf.String(),
	}); err != nil {
		return http.StatusInternalServerError, err
	}

	key, err = i.SaveWithParent(ctx, cKey)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	json.NewEncoder(w).Encode(i.Key(key))
	return http.StatusOK, nil
}

repository: tudorgergely/api

repo_name: tudorgergely/api


text:
DESCRIPTION="A portable, efficient middleware for different kinds of mail access."
HOMEPAGE = "http://www.etpan.org"
SECTION = "libs"

LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://COPYRIGHT;md5=f18ebe7e452708c26f83954f81062ba7"

DEPENDS = "gnutls"

PR = "r2"

SRC_URI = "${SOURCEFORGE_MIRROR}/libetpan/libetpan-${PV}.tar.gz"
SRC_URI[md5sum] = "6fee60d08506e941642b8fa087e60b07"
SRC_URI[sha256sum] = "ce3ac567d0f07e5b2d1fdb0045042a8295ec477cd933de1a391fd48139c1f75e"

inherit autotools pkgconfig gettext binconfig

EXTRA_OECONF = "\
	--without-openssl \
    --with-gnutls \
    --disable-db \
    ${@base_contains('DISTRO_FEATURES', 'ipv6', '--enable-ipv6', '--disable-ipv6', d)} \
    "

FILES_${PN} = "${libdir}/lib*.so.*"
FILES_${PN}-dev = "${bindir} ${includedir} ${libdir}/lib*.so ${libdir}/*.la ${libdir}/pkgconfig"
FILES_${PN}-staticdev = "${libdir}/*.a"

repository: tworaz/oe-tworaz

repo_name: tworaz/oe-tworaz

gha_language: Shell


text:
package main

import (
	//"encoding/json"
	"doveclient/util"
	"fmt"
)

func main() {
	ts := `db = 1
user = "a"
arra_test=[["a","b"],["c","d"]]
[addr]
detail="abcd"
short="cfg"
[[mm.a]]
a=1
b=2
[[mm.a]]
a=11
b=22
[nodes.0]
master = "10.0.5.43:27301"
slave = "10.0.5.43:27301"

[nodes.1]
master = "10.0.5.43:27302"
slave = "10.0.5.43:27302"

[nodes.2]
master = "10.0.5.43:27303"
slave = "10.0.5.43:27303"

[nodes.3]
master = "10.0.5.43:27304"
slave = "10.0.5.43:27304"

[nodes.4]
master = "10.0.5.43:27305"
slave = "10.0.5.43:27305"

[nodes.5]
master = "10.0.60.26:27306"
slave = "10.0.60.26:27306"

[nodes.6]
master = "10.0.60.26:27307"
slave = "10.0.60.26:27307"

[nodes.7]
master = "10.0.60.26:27308"
slave = "10.0.60.26:27308"

[nodes.8]
master = "10.0.60.26:27309"
slave = "10.0.60.26:27309"

[nodes.9]
master = "10.0.60.26:27310"
slave = "10.0.60.26:27310"

[nodes.10]
master = "10.0.60.28:27311"
slave = "10.0.60.28:27311"

[nodes.11]
master = "10.0.60.28:27312"
slave = "10.0.60.28:27312"

[nodes.12]
master = "10.0.60.28:27313"
slave = "10.0.60.28:27313"

[nodes.13]
master = "10.0.60.28:27314"
slave = "10.0.60.28:27314"

[nodes.14]
master = "10.0.60.28:27315"
slave = "10.0.60.28:27315"

[ip.1.2]
a=1
b=2
[ip.2.3]
a=2
b=33

`
	ts2 := `[ab]
a1=23
a2=31
a3=["a","b"]
`

	mM, e := util.TomlToJson(ts)
	mM2, e := util.TomlConfigValueToJson(ts2)
	//jv, _ := json.MarshalIndent(mM, "", "    ")
	fmt.Printf("\n%s\n--------\n%s\n%s\n", mM, e, mM2)
}

repository: haolinbird/dove

repo_name: haolinbird/dove

branch_name: refs/heads/main


text:
parseGlobalSections(pre post PrePost)
testGlobalSection(post Postsec Key1=Value2)
testGlobalSection(pre Presec Key1=Value1 "Key2=Value with some spaces")
testGlobalSection(post Emptysec)
testGlobalSection(post ExtensibilityGlobals "SolutionGuid={00000000-0000-0000-0000-000000000000}")
testGlobalSection(post ExtensibilityAddIns)


text:
package benchmarks

import (
	"os/exec"
	"testing"
)

func BenchmarkSafeSQL(b *testing.B) {
	for n := 0; n < b.N; n++ {
		_ = exec.Command("safesql", "github.com/akwick/gotcha")
	}
}

func BenchmarkGas(b *testing.B) {
	for n := 0; n < b.N; n++ {
		_ = exec.Command("gas", "-include=G201,G202", "../../gotcha/...")
	}
}

func BenchmarkGotcha(b *testing.B) {
	for n := 0; n < b.N; n++ {
		_ = exec.Command("gotcha", "-src=../../gotcha/start.go", "-ssf=../sqlQuery.txt", "-pkgs=github.com/akwick/gotcha/lattice/taint,github.com/akwick/gotcha/worklist")
	}
}

repository: akwick/sqinco

repo_name: akwick/sqinco


text:
package core

import (
	"math"

	sdk "github.com/cosmos/cosmos-sdk/types"
	"github.com/emirpasic/gods/maps/treemap"
)

// Manager for the depth information of one side of the order book: sell or buy
type DepthManager struct {
	// ppMap keeps a depth map without any merging
	ppMap   *treemap.Map           // we can not use map[string]*PricePoint because iteration is needed
	Updated map[string]*PricePoint //it records all the changed PricePoint during last block
	Side    string
	//following members are used for depth merging
	Levels                 []string
	CachedMulDecsForLevels []sdk.Dec
	LevelDepth             LevelsPricePoint
}

func NewDepthManager(side string) *DepthManager {
	dm := &DepthManager{
		ppMap:                  treemap.NewWithStringComparator(),
		Updated:                make(map[string]*PricePoint),
		Side:                   side,
		Levels:                 make([]string, 0, 20),
		CachedMulDecsForLevels: make([]sdk.Dec, 0, 20),
		LevelDepth:             make(LevelsPricePoint, 20),
	}
	return dm
}

func (dm *DepthManager) AddLevel(levelStr string) error {
	for _, lvl := range dm.Levels {
		//Return if already added
		if lvl == levelStr {
			return nil
		}
	}
	if levelStr == "all" {
		dm.CachedMulDecsForLevels = append(dm.CachedMulDecsForLevels, sdk.OneDec())
	} else {
		p, err := sdk.NewDecFromStr(levelStr)
		if err != nil {
			return err
		}
		dm.CachedMulDecsForLevels = append(dm.CachedMulDecsForLevels, sdk.OneDec().QuoTruncate(p))
	}
	dm.Levels = append(dm.Levels, levelStr)
	dm.LevelDepth[levelStr] = make(map[string]*PricePoint)
	return nil
}

func (dm *DepthManager) Size() int {
	return dm.ppMap.Size()
}

// dump the PricePoints in ppMap for serialization
func (dm *DepthManager) DumpPricePoints() []*PricePoint {
	if dm == nil {
		return nil
	}
	size := dm.ppMap.Size()
	pps := make([]*PricePoint, size)
	iter := dm.ppMap.Iterator()
	iter.Begin()
	for i := 0; i < size; i++ {
		iter.Next()
		pps[i] = iter.Value().(*PricePoint)
	}
	return pps
}

// The orderbook's entry at 'price' is delta-changed by amount
// positive amount for increment, negative amount for decrement
func (dm *DepthManager) DeltaChange(price sdk.Dec, amount sdk.Int) {
	s := string(decToBigEndianBytes(price))
	ptr, ok := dm.ppMap.Get(s)
	var pp *PricePoint
	if !ok {
		pp = &PricePoint{Price: price, Amount: sdk.ZeroInt()}
	} else {
		pp = ptr.(*PricePoint)
	}
	pp.Amount = pp.Amount.Add(amount)
	if pp.Amount.IsZero() {
		dm.ppMap.Remove(s)
	} else {
		dm.ppMap.Put(s, pp)
	}
	// update the depth map without merging
	dm.Updated[s] = pp

	isBuy := true
	if dm.Side == "sell" {
		isBuy = false
	}
	for i, lev := range dm.Levels {
		// update the depth maps with merging
		updateAmount(dm.LevelDepth[lev],
			&PricePoint{Price: price, Amount: amount},
			dm.CachedMulDecsForLevels[i],
			isBuy,
		)
	}
}

// Returns the changed PricePoints of last block, without and with merging
// Clear dm.Updated and dm.LevelDepth for the next block
func (dm *DepthManager) EndBlock() (woMerging map[string]*PricePoint, wiMerging map[string]map[string]*PricePoint) {
	oldUpdated, oldLevelDepth := dm.Updated, dm.LevelDepth
	dm.Updated = make(map[string]*PricePoint)
	dm.LevelDepth = make(LevelsPricePoint, len(dm.Levels))
	for _, lev := range dm.Levels {
		dm.LevelDepth[lev] = make(map[string]*PricePoint)
	}
	return oldUpdated, oldLevelDepth
}

// Returns the highest n PricePoints
func (dm *DepthManager) GetHighest(n int) []*PricePoint {
	res := make([]*PricePoint, 0, n)
	iter := dm.ppMap.Iterator()
	iter.End()
	if n == 0 {
		n = math.MaxInt64
	}
	for i := 0; i < n; i++ {
		if ok := iter.Prev(); !ok {
			break
		}
		res = append(res, iter.Value().(*PricePoint))
	}
	return res
}

// Returns the lowest n PricePoints
func (dm *DepthManager) GetLowest(n int) []*PricePoint {
	res := make([]*PricePoint, 0, n)
	iter := dm.ppMap.Iterator()
	iter.Begin()
	if n == 0 {
		n = math.MaxInt64
	}
	for i := 0; i < n; i++ {
		if ok := iter.Next(); !ok {
			break
		}
		res = append(res, iter.Value().(*PricePoint))
	}
	return res
}

repository: coinsky/trade-server

repo_name: coinsky/trade-server


text:
require opie-securityplugin-blueping.inc

PV = "${OPIE_GIT_PV}"

SRC_URI = "${OPIE_GIT};protocol=git;subpath=noncore/securityplugins/blueping \
           ${OPIE_GIT};protocol=git;subpath=pics "


text:
//go:build windows
// +build windows

package ssh

import (
	"os"
	"time"

	oktetoLog "github.com/okteto/okteto/pkg/log"
	"golang.org/x/crypto/ssh"
	"golang.org/x/term"
)

func resizeWindow(session *ssh.Session) {
	go func() {
		prevW, prevH, err := term.GetSize(int(os.Stdout.Fd()))
		if err != nil {
			oktetoLog.Infof("request for terminal size failed: %s", err)
		}
		for {
			time.Sleep(time.Millisecond * 250)
			w, h, err := term.GetSize(int(os.Stdout.Fd()))
			if err != nil {
				oktetoLog.Infof("request for terminal size failed: %s", err)
			}
			if prevH != h || prevW != w {
				if err := session.WindowChange(h, w); err != nil {
					oktetoLog.Infof("request for terminal resize failed: %s", err)
				}
			}
			prevH = h
			prevW = w
		}
	}()
}

repository: okteto/okteto

repo_name: okteto/okteto


text:
package json

import (
	"encoding/json"
	"github.com/davyxu/cellnet"
	"github.com/davyxu/cellnet/codec"
	"net/url"
)

type jsonCodec struct {
}

func (self *jsonCodec) Name() string {
	return "wsjson"
}

func (self *jsonCodec) MimeType() string {
	return "application/json"
}

// 将结构体编码为JSON的字节数组
func (self *jsonCodec) Encode(msgObj interface{}, ctx cellnet.ContextSet) (data interface{}, err error) {

	raw, err := json.Marshal(msgObj)
	if err != nil {
		return nil, err
	}

	data = []byte(url.PathEscape(string(raw)))

	return
}

// 将JSON的字节数组解码为结构体
func (self *jsonCodec) Decode(data interface{}, msgObj interface{}) error {

	decodedStr, err := url.PathUnescape(string(data.([]byte)))
	if err != nil {
		return err
	}

	return json.Unmarshal([]byte(decodedStr), msgObj)
}

func init() {

	// 注册编码器
	codec.RegisterCodec(new(jsonCodec))
}


text:
// ATLAS: Adaptable Tool Library for Advanced Simulation
//
// Copyright 2015 University of Central Florida
//
//
// This library provides many fundamental capabilities used in creating
// virtual environment simulations.  It includes elements such as vectors,
// matrices, quaternions, containers, communication schemes (UDP, TCP, DIS,
// HLA, Bluetooth), and XML processing.  It also includes some extensions
// to allow similar code to work in Linux and in Windows.  Note that support
// for iOS and Android development is also included.
//
//
// 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.

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "atNotifier.h++"

// Define the "notify level" (we make this a class variable so that
// altering the level will affect all those calling notify())
int atNotifier::notify_level = AT_INFO;

// Define the "notify destination" (we make this a class variable so that
// altering the destination will affect all those calling notify())
FILE * atNotifier::output_file_ptr = stdout;

atNotifier::atNotifier()
{
   // Initialize the instance variables (an empty header and output to stdout)
   memset(header_name, 0, sizeof(header_name));
}

atNotifier::~atNotifier()
{
}

void atNotifier::setName(char * name)
{
   // Copy the name into the header (use strncpy to avoid writing over
   // the end of the array)
   strncpy(header_name, name, sizeof(header_name) - 1);

   // Guarantee a NULL character (covers the case when strncpy does copy
   // all "n" characters)
   header_name[sizeof(header_name) - 1] = '\0';
}

void atNotifier::setNotifyLevel(int desiredLevel)
{
   // Make sure the user chose a valid desired level
   if ( (desiredLevel == AT_INFO) || (desiredLevel == AT_WARN) ||
        (desiredLevel == AT_ERROR) || (desiredLevel == AT_FATAL_ERROR) ||
        (desiredLevel == AT_SILENT) )
   {
      // Set the level to the requested level
      notify_level = desiredLevel;
   }
   else
   {
      // Otherwise, output a warning about the illegal level
      notify(AT_WARN, "Attempt to set illegal notify level [%04x].\n",
             desiredLevel);
   }
}

void atNotifier::setNotifyDestination(FILE *output)
{
   // Set the output to the FILE given by the user (note that this class
   // does not open nor close the file)
   output_file_ptr = output;
}

void atNotifier::notify(int level, char *str, ...)
{
   va_list   args;

   // When in SILENT level, *never* notify
   if (notify_level & AT_SILENT)
      return;

   // Output if debug or no_header flag is set or if level is greater than
   // or equal to the current notify level
   if ( (level & AT_DEBUG) || (level & AT_FORCE) ||
        ((level & AT_LEVEL_MASK) >= notify_level) )
   {
      // If the "no header" bit is not set, output the header
      if (!(level & AT_NO_HEADER))
      {
         // Clear all modification flags
         level = level & AT_LEVEL_MASK;

         // Print the initial level as appropriate
         switch (level)
         {
            case AT_INFO:
               fprintf(output_file_ptr, "INFO: ");
               break;
            case AT_WARN:
               fprintf(output_file_ptr, "WARN: ");
               break;
            case AT_ERROR:
               fprintf(output_file_ptr, "ERROR: ");
               break;
            case AT_FATAL_ERROR:
               fprintf(output_file_ptr, "\n\nFATAL_ERROR: ");
               break;
            default:
               fprintf(output_file_ptr,"**** UNKNOWN ERROR LEVEL [%d] ****",
                       level);
               break;
         }

         // Then print the header name
         fprintf(output_file_ptr, header_name);
      }

      // Finally print the message itself with parameters (like printf)
      va_start(args, str);
      vfprintf(output_file_ptr, str, args);
      va_end(args);
      fflush(output_file_ptr);

      // If the user called this a fatal error, bail out harshly
      if ((level & AT_FATAL_ERROR) > 0)
      {
         // AT_FATAL_ERROR exits
         exit(AT_FATAL_ERROR);
      }
   }
}


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace SharpTrends.YearInSearch
{
    internal static class JSON
    {
        public class ListItem
        {
            [JsonProperty("title")]
            public string Title;

            [JsonProperty("exploreQuery")]
            public string ExploreQuery;
        }

        public class TopChart
        {
            [JsonProperty("listTitle")]
            public string ListTitle;

            [JsonProperty("listItems")]
            public List<ListItem> ListItems;

            [JsonProperty("id")]
            public string Id;

            [JsonProperty("type")]
            public string Type;

            [JsonProperty("title")]
            public string Title;

            [JsonProperty("template")]
            public string Template;

            [JsonProperty("embedTemplate")]
            public string EmbedTemplate;

            [JsonProperty("version")]
            public string Version;

            [JsonProperty("isLong")]
            public bool IsLong;

            [JsonProperty("isCurated")]
            public bool IsCurated;
        }

        public class Interactive
        {
            [JsonProperty("url")]
            public string Url;

            [JsonProperty("imgUrl")]
            public string ImgUrl;
        }

        public class Response
        {
            [JsonProperty("topCharts")]
            public List<TopChart> TopCharts;

            [JsonProperty("interactive")]
            public Interactive Interactive;
        }
    }
}

gha_language: C#


text:
package Consumer

import (
	_ "context"
	"encoding/json"
	"fmt"
	"github.com/Open-Twin/citymesh/complete_mesh/broker"
	"github.com/Open-Twin/citymesh/complete_mesh/dataFormat"
	"github.com/Open-Twin/citymesh/complete_mesh/sidecar"
	"github.com/Shopify/sarama"
	"github.com/gogo/protobuf/proto"
	"github.com/golang/protobuf/ptypes"
	"github.com/stretchr/testify/require"
	"github.com/tidwall/gjson"
	"gotest.tools/assert"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"sync"
	"testing"
	"time"
)

type Warning struct {
	Gkz       string `json:"GKZ"`
	Name      string `json:"Name"`
	Region    string `json:"Region"`
	Warnstufe string `json:"Warnstufe"`
}

var (
	addrs   = []string{"localhost:9092"}
	brokers = []string{"0.0.0.0:9092"}
	topic   = "topic_test"
)

const (
	kafkaConn = "localhost:9092"
)

/*func Test_consume(t *testing.T) {
	type args struct {
		topics []string
		master sarama.Consumer
	}
	tests := []struct {
		name  string
		args  args
		want  chan *sarama.ConsumerMessage
		want1 chan *sarama.ConsumerError
	}{
		// TODO: Add test cases.
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, got1 := main.consume(tt.args.topics, tt.args.master)
			if !reflect.DeepEqual(got, tt.want) {
				t.Errorf("consume() got = %v, want %v", got, tt.want)
			}
			if !reflect.DeepEqual(got1, tt.want1) {
				t.Errorf("consume() got1 = %v, want %v", got1, tt.want1)
			}
		})
	}
}*/

func TestConsume(t *testing.T) {
	config := sarama.NewConfig()
	config.Producer.Return.Successes = true
	producer, err := sarama.NewSyncProducer(addrs, config)
	require.NoError(t, err)

	partition, offset, err := producer.SendMessage(&sarama.ProducerMessage{
		Topic: topic,
		Value: sarama.ByteEncoder([]byte("foobar")),
	})
	require.NoError(t, err)
	t.Logf("Sent message to partition %d with offset %d", partition, offset)

	//ctx, cancel := context.WithCancel(context.Background())
	var wg sync.WaitGroup

	master, err := sarama.NewConsumer(brokers, config)

	topics, _ := master.Topics()

	consumer, errors := consume(topics, master)

	signals := make(chan os.Signal, 1)
	signal.Notify(signals, os.Interrupt)

	// Count how many message processed
	msgCount := 0

	// Get signnal for finish
	doneCh := make(chan struct{})
	go func() {
		for {
			select {
			case msg := <-consumer:
				msgCount++
				receivedMessage := &sidecar.CloudEvent{}
				err := proto.Unmarshal(msg.Value, receivedMessage)
				if err != nil {
					log.Fatalln("Failed to unmarshal message:", err)
				}

				//log.Printf("Message received: %s", receivedMessage.Data)
				//fmt.Println("Message received: ", receivedMessage.Data)
				fmt.Println("Message received: ", receivedMessage)
				//fmt.Println("Received messages", string(msg.Key), string(msg.Value))
			case consumerError := <-errors:
				msgCount++
				fmt.Println("Received consumerError ", string(consumerError.Topic), string(consumerError.Partition), consumerError.Err)
				doneCh <- struct{}{}
			case <-signals:
				fmt.Println("Interrupt is detected")
				doneCh <- struct{}{}
			}
		}
	}()

	log.Println("Sarama consumer up and running!")

	time.Sleep(1 * time.Second)

	wg.Wait()
	//close()
}

func TestConsumeTwice(t *testing.T) {
	config := sarama.NewConfig()
	config.Producer.Return.Successes = true
	producer, err := sarama.NewSyncProducer(addrs, config)
	require.NoError(t, err)

	data1, data2 := "foobar1", "foobar2"

	for _, data := range []string{data1, data2} {
		partition, offset, err := producer.SendMessage(&sarama.ProducerMessage{
			Topic: topic,
			Key:   sarama.StringEncoder("foobar"),
			Value: sarama.StringEncoder(data),
		})
		require.NoError(t, err)
		t.Logf("Sent message to partition %d with offset %d", partition, offset)
	}

	producertwo, err := initProducer()
	if err != nil {
		fmt.Println("Error producer: ", err.Error())
		os.Exit(1)
	}

	cloudmessage := Apiclient2()

	//fmt.Println(cloudmessage.Data)

	publish(cloudmessage, producertwo)

	//ctx, cancel := context.WithCancel(context.Background())
	var wg sync.WaitGroup

	master, err := sarama.NewConsumer(brokers, config)
	if err != nil {
		panic(err)
	}

	defer func() {
		if err := master.Close(); err != nil {
			panic(err)
		}
	}()

	topics, _ := master.Topics()

	consumer, errors := consume(topics, master)

	signals := make(chan os.Signal, 1)
	signal.Notify(signals, os.Interrupt)

	// Count how many message processed
	msgCount := 0

	doneCh := make(chan struct{})
	go func() {
		for {
			select {
			case msg := <-consumer:
				msgCount++
				receivedMessage := &sidecar.CloudEvent{}
				err := proto.Unmarshal(msg.Value, receivedMessage)
				if err != nil {
					log.Fatalln("Failed to unmarshal message:", err)
				}

				//log.Printf("Message received: %s", receivedMessage.Data)
				//fmt.Println("Message received: ", receivedMessage.Data)
				fmt.Println("Message received: ", receivedMessage)
				//fmt.Println("Received messages", string(msg.Key), string(msg.Value))
			case consumerError := <-errors:
				msgCount++
				fmt.Println("Received consumerError ", string(consumerError.Topic), string(consumerError.Partition), consumerError.Err)
				doneCh <- struct{}{}
			case <-signals:
				fmt.Println("Interrupt is detected")
				doneCh <- struct{}{}
			}
		}
	}()

	<-doneCh
	fmt.Println("Processed", msgCount, "messages")

	messageReceived := make(chan []byte)
	/*cons := &
	consumer := &Consumer{
		ready: make(chan bool),
		handle: func(data []byte) error {
			messageReceived <- data
			fmt.Printf("Received message: %s\n", data)
			return nil
		},
	}*/

	go func() {
		for {
			select {
			case msg := <-consumer:
				msgCount++
				receivedMessage := &sidecar.CloudEvent{}
				err := proto.Unmarshal(msg.Value, receivedMessage)
				if err != nil {
					log.Fatalln("Failed to unmarshal message:", err)
				}

				//log.Printf("Message received: %s", receivedMessage.Data)
				//fmt.Println("Message received: ", receivedMessage.Data)
				fmt.Println("Message received: ", receivedMessage)
				//fmt.Println("Received messages", string(msg.Key), string(msg.Value))
			case consumerError := <-errors:
				msgCount++
				fmt.Println("Received consumerError ", string(consumerError.Topic), string(consumerError.Partition), consumerError.Err)
				doneCh <- struct{}{}
			case <-signals:
				fmt.Println("Interrupt is detected")
				doneCh <- struct{}{}
			}
		}
	}()

	//close := main.consume(ctx, &wg, consumer)

	//<-consumer.ready
	log.Println("Sarama consumer up and running!")

	for i := 0; i < 2; i++ {
		data := <-messageReceived
		switch i {
		case 0:
			assert.Equal(t, data1, string(data))
		case 1:
			assert.Equal(t, data2, string(data))
		}
	}

	//cancel()
	wg.Wait()
	//close()
}

func initProducer() (sarama.SyncProducer, error) {
	// setup sarama log to stdout
	sarama.Logger = log.New(os.Stdout, "", log.Ltime)

	// producer config
	config := sarama.NewConfig()
	config.Producer.Retry.Max = 5
	config.Producer.RequiredAcks = sarama.WaitForAll
	config.Producer.Return.Successes = true
	config.Producer.MaxMessageBytes = 10000000

	// async producer
	//prd, err := sarama.NewAsyncProducer([]string{kafkaConn}, config)

	// sync producer
	prd, err := sarama.NewSyncProducer([]string{kafkaConn}, config)

	return prd, err
}

func consume(topics []string, master sarama.Consumer) (chan *sarama.ConsumerMessage, chan *sarama.ConsumerError) {
	consumers := make(chan *sarama.ConsumerMessage)
	errors := make(chan *sarama.ConsumerError)
	for _, topic := range topics {
		if strings.Contains(topic, "__consumer_offsets") {
			continue
		}
		partitions, _ := master.Partitions(topic)
		// this only consumes partition no 1, you would probably want to consume all partitions
		consumer, err := master.ConsumePartition(topic, partitions[0], sarama.OffsetOldest)
		if nil != err {
			fmt.Printf("Topic %v Partitions: %v", topic, partitions)
			panic(err)
		}
		fmt.Println(" Start consuming topic ", topic)
		go func(topic string, consumer sarama.PartitionConsumer) {
			for {
				select {
				case consumerError := <-consumer.Errors():
					errors <- consumerError
					fmt.Println("consumerError: ", consumerError.Err)

				case msg := <-consumer.Messages():
					consumers <- msg
					fmt.Println("Got message on topic ", topic, msg.Value)
				}
			}
		}(topic, consumer)
	}

	return consumers, errors
}

func publish(message broker.CloudEvent, producer sarama.SyncProducer) {
	// publish sync

	messageToSend := &message
	messageToSendBytes, err := proto.Marshal(messageToSend)

	//fmt.Println(messageToSendBytes)

	msg := &sarama.ProducerMessage{
		Topic: topic,
		Value: sarama.ByteEncoder(messageToSendBytes),
	}

	p, o, err := producer.SendMessage(msg)
	if err != nil {
		fmt.Println("Error publish: ", err.Error())
	}

	// publish async
	//producer.Input() <- &sarama.ProducerMessage{

	fmt.Println("Partition: ", p)
	fmt.Println("Offset: ", o)
}

func Apiclient() (cloudeventmessage broker.CloudEvent) {

	ampel, erro := http.Get("https://corona-ampel.gv.at/sites/corona-ampel.gv.at/files/assets/Warnstufen_Corona_Ampel_Gemeinden_aktuell.json")

	if erro != nil {
		fmt.Print(erro.Error())
		os.Exit(1)
	}
	body, err := ioutil.ReadAll(ampel.Body)
	ampelJson := string(body)

	value := gjson.Get(ampelJson, "#.Stand")
	println("Length: ", len(value.Array()))
	println(value.String())

	messages := make([]*dataFormat.Message, 0, 0)
	//0,0 checken

	datenres := gjson.Get(ampelJson, "#.Stand")
	datenres.ForEach(func(key, value gjson.Result) bool {
		stand := value.String()
		warnstufen := make([]*dataFormat.Warnstufen, 0, 0)

		path := "#(Stand==" + stand + ").Warnstufen"
		result := gjson.Get(ampelJson, path)
		result.ForEach(func(key, value gjson.Result) bool {
			var warning Warning
			if err := json.Unmarshal([]byte(value.Raw), &warning); err != nil {
				panic(err)
			}
			warnstufen = append(warnstufen,
				&dataFormat.Warnstufen{
					Region:    warning.Region,
					GKZ:       warning.Gkz,
					Name:      warning.Name,
					Warnstufe: warning.Warnstufe,
				})
			return true
		})
		messages = append(messages,
			&dataFormat.Message{Stand: stand,
				Warnstufen: warnstufen,
			})

		return true
	})

	marshalMessages, err := ptypes.MarshalAny(&dataFormat.Messages{Message: messages})
	if err != nil {
		panic(err)
	}

	data := broker.CloudEvent_ProtoData{ProtoData: marshalMessages}

	cloudeventmessage = broker.CloudEvent{
		IdService:   "",
		Source:      "corona-ampel",
		SpecVersion: "1.0",
		Type:        "json",
		Attributes:  nil,
		Data:        &data,
		IpService:   "192.168.0.10",
	}

	//fmt.Print(cloudeventmessage.Data)

	//fmt.Println(cloudeventmessage.Data)

	/*response, err := c.DataFromService(context.Background(), &cloudeventmessage)
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", response.GetMessage())*/

	return cloudeventmessage

}

func Apiclient2() (cloudeventmessage broker.CloudEvent) {

	ampel, erro := http.Get("https://corona-ampel.gv.at/sites/corona-ampel.gv.at/files/assets/Warnstufen_Corona_Ampel_Gemeinden_aktuell.json")

	if erro != nil {
		fmt.Print(erro.Error())
		os.Exit(1)
	}
	body, err := ioutil.ReadAll(ampel.Body)
	if err != nil {
		fmt.Print(err.Error())
		os.Exit(1)
	}
	ampelJson := string(body)

	value := gjson.Get(ampelJson, "#.Stand")
	println("Length: ", len(value.Array()))
	println(value.String())

	messages := make([]*dataFormat.Message, 0, 0)
	//0,0 checken

	datenres := gjson.Get(ampelJson, "#.Stand")
	datenres.ForEach(func(key, value gjson.Result) bool {
		stand := value.String()
		warnstufen := make([]*dataFormat.Warnstufen, 0, 0)

		path := "#(Stand==" + stand + ").Warnstufen"
		result := gjson.Get(ampelJson, path)
		result.ForEach(func(key, value gjson.Result) bool {
			var warning Warning
			if err := json.Unmarshal([]byte(value.Raw), &warning); err != nil {
				panic(err)
			}
			warnstufen = append(warnstufen,
				&dataFormat.Warnstufen{
					Region:    warning.Region,
					GKZ:       warning.Gkz,
					Name:      warning.Name,
					Warnstufe: warning.Warnstufe,
				})
			return true
		})
		messages = append(messages,
			&dataFormat.Message{Stand: stand,
				Warnstufen: warnstufen,
			})
		//jsonmessage,err := ProtobufToJSON(messages)

		return true
	})

	print("Message", messages)

	/*marshalMessages, err := ptypes.MarshalAny(&dataFormat.Messages{Message: messages})
	if err != nil {
		panic(err)
	}*/

	//data := sidecar.CloudEvent_ProtoData{ProtoData: marshalMessages}

	//jsondata,err := ProtobufToJSON(messages)

	text := ""
	for _, element := range messages {
		text = text + string(proto.MarshalTextString(element))
		//result, _ := ProtobufToJSON(element)
		//text = text + result

	}

	finishedMessage := broker.CloudEvent_TextData{TextData: text}

	cloudeventmessage = broker.CloudEvent{
		IdService:   "",
		Source:      "corona-ampel",
		SpecVersion: "1.0",
		Type:        "json",
		Attributes:  nil,
		Data:        &finishedMessage,
		IdSidecar:   "01",
		IpService:   "192.168.0.10",
		IpSidecar:   "192.168.0.11",
	}

	//fmt.Println(cloudeventmessage.Data)

	/*response, err := c.DataFromService(context.Background(), &cloudeventmessage)
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	log.Printf("Greeting: %s", response.GetMessage())*/

	return cloudeventmessage

}

repository: Open-Twin/citymesh

repo_name: Open-Twin/citymesh


text:
package togglr

import (
	"os"
	"reflect"
)

type envSource struct {
}

func (source envSource) GetConfig(name string, tag reflect.StructTag) (interface{}, bool) {
	var varName = tag.Get("env")
	if varName == "" {
		return nil, false
	}
	return os.Getenv(varName) == "1", true
}

var singltonEnvSource = envSource{}

repository: mouk/togglr

repo_name: mouk/togglr


text:
package main

import (
	"bytes"
	"fmt"
	"text/tabwriter"
	"time"
)

type item struct {
	Tick time.Time
	Mark string
}

const KeyTrace = "trace"

var Root = newTrace(0, "root")

type trace struct {
	parent   *trace
	children []*trace

	depth  int
	prefix string

	id    string
	items []item

	flag bool
}

func newTrace(depth int, id string) *trace {
	t := &trace{
		id:    id,
		depth: depth,
		items: []item{{Mark: "begin", Tick: time.Now()}},
	}
	return t
}

func NewTrace(parent *trace, id string) *trace {
	if parent == nil {
		parent = newTrace(0, "root")
	}

	if id == "" {
		id = parent.id
	}

	t := newTrace(parent.depth+1, id)
	parent.children = append(parent.children, t)
	return t

}

func (t *trace) Tick(mark string) {
	t.items = append(t.items, item{
		Mark: mark,
		Tick: time.Now(),
	})

}

func (t *trace) End() {
	if t.flag {
		return
	}

	t.flag = true
	t.items = append(t.items, item{Mark: "end", Tick: time.Now()})
}

const format = "%s\t%s\t%.2f\t"

func (t *trace) String() string {

	buf := &bytes.Buffer{}
	for i := 0; i < t.depth; i++ {
		buf.WriteString("  ") // 2 spaces
	}
	prefix := buf.String()

	buf.Truncate(0)

	w := tabwriter.NewWriter(buf, 0, 0, 2, ' ', 0)
	if len(t.items) > 0 {
		begin := t.items[0]
		end := t.items[len(t.items)-1]
		fmt.Fprintln(w, fmt.Sprintf(format, prefix, "* "+t.id, end.Tick.Sub(begin.Tick).Seconds()))
		//fmt.Fprintln(w, fmt.Sprintf(format, prefix, "· "+t.id, end.Tick.Sub(begin.Tick).Seconds()))

	}

	for i := 1; i < len(t.items)-1; i++ {
		fmt.Fprintln(w, fmt.Sprintf(format, prefix, t.items[i].Mark, t.items[i].Tick.Sub(t.items[i-1].Tick).Seconds()))
	}

	fmt.Fprintln(w, "")

	for i := 0; i < len(t.children); i++ {
		fmt.Fprint(w, t.children[i].String())
	}

	w.Flush()

	return buf.String()

}

func (t *trace) Output() {
	fmt.Println(t)

}

func main() {

	t := NewTrace(Root, "123")
	defer t.Output()
	defer t.End()
	t.Tick("1-1111111")
	time.Sleep(2e9)
	t.Tick("1-2222222")

	t2 := NewTrace(t, "456")
	defer t2.End()
	t2.Tick("2-1111111")
	time.Sleep(3e9)
	t2.Tick("2-2222222")

	t3 := NewTrace(t2, "789")
	defer t3.End()
	t3.Tick("3-1111111")
	time.Sleep(3e9)
	t3.Tick("3-2222222")

	t4 := NewTrace(t, "abc")
	defer t4.End()
	t4.Tick("4-1111111")
	time.Sleep(3e9)
	t4.Tick("4-2222222")

	t5 := NewTrace(t, "abc")
	defer t5.End()
	t5.Tick("5-1111111")
	time.Sleep(3e9)
	t5.Tick("5-2222222")
}

repository: lewgun/toolkits

repo_name: lewgun/toolkits


text:
@article{Al-Omari-2020-SemanticCloneBench:,
    title = "SemanticCloneBench: A Semantic Code Clone Benchmark using Crowd-Source Knowledge",
    author = "Al-Omari, Farouq  and
      Roy, Chanchal K.  and
      Chen, Tonghao",
    journal = "2020 IEEE 14th International Workshop on Software Clones (IWSC)",
    year = "2020",
    publisher = "IEEE",
    url = "https://aclanthology.org/G20-41001",
    doi = "10.1109/iwsc50091.2020.9047643",
    abstract = "Not only do newly proposed code clone detection techniques, but existing techniques and tools also need to be evaluated and compared. This evaluation process could be done by assessing the reported clones manually or by using benchmarks. The main limitations of available benchmarks include: they are restricted to one programming language; they have a limited number of clone pairs that are confined within the selected system(s); they require manual validation; they do not support all types of code clones. To overcome these limitations, we proposed a methodology to generate a wide range of semantic clone benchmark(s) for different programming languages with minimal human validation. Our technique is based on the knowledge provided by developers who participate in the crowd-sourced information website, Stack Overflow. We applied automatic filtering, selection and validation to the source code in Stack Overflow answers. Finally, we build a semantic code clone benchmark of 4000 clones pairs for the languages Java, C, C{\#} and Python.",
}

repository: gwf-uwaterloo/gwf-publications

repo_name: gwf-uwaterloo/gwf-publications

extension: bib