text:
package commands

import (
	"fmt"
	"strconv"

	jsonrpc "github.com/33cn/chain33/rpc/jsonclient"
	rpctypes "github.com/33cn/chain33/rpc/types"
	"github.com/33cn/chain33/types"
	pkt "github.com/33cn/plugin/plugin/dapp/issuance/types"
	"github.com/spf13/cobra"
)

// IssuanceCmd 斗牛游戏命令行
func IssuanceCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "issuance",
		Short: "Issuance command",
		Args:  cobra.MinimumNArgs(1),
	}

	cmd.AddCommand(
		IssuanceCreateRawTxCmd(),
		IssuanceDebtRawTxCmd(),
		IssuanceRepayRawTxCmd(),
		IssuancePriceFeedRawTxCmd(),
		IssuanceCloseRawTxCmd(),
		IssuanceManageRawTxCmd(),
		IssuanceQueryCmd(),
	)

	return cmd
}

// IssuanceCreateRawTxCmd 生成开始交易命令行
func IssuanceCreateRawTxCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "create",
		Short: "Create a issuance",
		Run:   IssuanceCreate,
	}
	addIssuanceCreateFlags(cmd)
	return cmd
}

func addIssuanceCreateFlags(cmd *cobra.Command) {
	cmd.Flags().Float64P("balance", "b", 0, "balance")
	cmd.MarkFlagRequired("balance")
	cmd.Flags().Float64P("debtCeiling", "d", 0, "debtCeiling")
	cmd.Flags().Float64P("liquidationRatio", "l", 0, "liquidationRatio")
	cmd.Flags().Uint64P("period", "p", 0, "period")
}

//IssuanceCreate ....
func IssuanceCreate(cmd *cobra.Command, args []string) {
	paraName, _ := cmd.Flags().GetString("paraName")

	rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
	balance, _ := cmd.Flags().GetFloat64("balance")
	debtCeiling, _ := cmd.Flags().GetFloat64("debtCeiling")
	liquidationRatio, _ := cmd.Flags().GetFloat64("liquidationRatio")
	period, _ := cmd.Flags().GetUint64("period")

	params := &rpctypes.CreateTxIn{
		Execer:     types.GetExecName(pkt.IssuanceX, paraName),
		ActionName: "IssuanceCreate",
		Payload: []byte(fmt.Sprintf("{\"totalBalance\":%f, \"debtCeiling\":%f, \"liquidationRatio\":%f, \"period\":%d}",
			balance, debtCeiling, liquidationRatio, period)),
	}

	var res string
	ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.CreateTransaction", params, &res)
	ctx.RunWithoutMarshal()
}

// IssuanceDebtRawTxCmd 生成开始交易命令行
func IssuanceDebtRawTxCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "debt",
		Short: "Debt a issuance",
		Run:   IssuanceDebt,
	}
	addIssuanceDebtFlags(cmd)
	return cmd
}

func addIssuanceDebtFlags(cmd *cobra.Command) {
	cmd.Flags().StringP("issuanceID", "g", "", "issuance ID")
	cmd.MarkFlagRequired("issuanceID")
	cmd.Flags().Float64P("value", "v", 0, "value")
	cmd.MarkFlagRequired("value")
}

//IssuanceDebt ...
func IssuanceDebt(cmd *cobra.Command, args []string) {
	paraName, _ := cmd.Flags().GetString("paraName")

	rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
	issuanceID, _ := cmd.Flags().GetString("issuanceID")
	value, _ := cmd.Flags().GetFloat64("value")

	params := &rpctypes.CreateTxIn{
		Execer:     types.GetExecName(pkt.IssuanceX, paraName),
		ActionName: "IssuanceDebt",
		Payload:    []byte(fmt.Sprintf("{\"issuanceID\":\"%s\",\"value\":%f}", issuanceID, value)),
	}

	var res string
	ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.CreateTransaction", params, &res)
	ctx.RunWithoutMarshal()
}

// IssuanceRepayRawTxCmd 生成开始交易命令行
func IssuanceRepayRawTxCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "repay",
		Short: "Repay a issuance",
		Run:   IssuanceRepay,
	}
	addIssuanceRepayFlags(cmd)
	return cmd
}

func addIssuanceRepayFlags(cmd *cobra.Command) {
	cmd.Flags().StringP("issuanceID", "g", "", "issuance ID")
	cmd.MarkFlagRequired("issuanceID")
	cmd.Flags().StringP("debtID", "d", "", "debt ID")
	cmd.MarkFlagRequired("debtID")
}

//IssuanceRepay ...
func IssuanceRepay(cmd *cobra.Command, args []string) {
	paraName, _ := cmd.Flags().GetString("paraName")

	rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
	issuanceID, _ := cmd.Flags().GetString("issuanceID")
	debtID, _ := cmd.Flags().GetString("debtID")

	params := &rpctypes.CreateTxIn{
		Execer:     types.GetExecName(pkt.IssuanceX, paraName),
		ActionName: "IssuanceRepay",
		Payload:    []byte(fmt.Sprintf("{\"issuanceID\":\"%s\", \"debtID\":\"%s\"}", issuanceID, debtID)),
	}

	var res string
	ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.CreateTransaction", params, &res)
	ctx.RunWithoutMarshal()
}

// IssuancePriceFeedRawTxCmd 生成开始交易命令行
func IssuancePriceFeedRawTxCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "feed",
		Short: "price feed",
		Run:   IssuancePriceFeed,
	}
	addIssuancePriceFeedFlags(cmd)
	return cmd
}

func addIssuancePriceFeedFlags(cmd *cobra.Command) {
	cmd.Flags().Float64P("price", "p", 0, "price")
	cmd.MarkFlagRequired("price")
	cmd.Flags().Uint64P("volume", "v", 0, "volume")
	cmd.MarkFlagRequired("volume")
}

//IssuancePriceFeed ...
func IssuancePriceFeed(cmd *cobra.Command, args []string) {
	paraName, _ := cmd.Flags().GetString("paraName")

	rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
	price, _ := cmd.Flags().GetFloat64("price")
	volume, _ := cmd.Flags().GetUint64("volume")

	params := &rpctypes.CreateTxIn{
		Execer:     types.GetExecName(pkt.IssuanceX, paraName),
		ActionName: "IssuancePriceFeed",
		Payload:    []byte(fmt.Sprintf("{\"price\":[ %f ], \"volume\":[ %d ]}", price, volume)),
	}

	var res string
	ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.CreateTransaction", params, &res)
	ctx.RunWithoutMarshal()
}

// IssuanceCloseRawTxCmd 生成开始交易命令行
func IssuanceCloseRawTxCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "close",
		Short: "close a issuance",
		Run:   IssuanceClose,
	}
	addIssuanceCloseFlags(cmd)
	return cmd
}

func addIssuanceCloseFlags(cmd *cobra.Command) {
	cmd.Flags().StringP("issuanceID", "g", "", "issuance ID")
	cmd.MarkFlagRequired("issuanceID")
}

//IssuanceClose ...
func IssuanceClose(cmd *cobra.Command, args []string) {
	paraName, _ := cmd.Flags().GetString("paraName")

	rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
	issuanceID, _ := cmd.Flags().GetString("issuanceID")

	params := &rpctypes.CreateTxIn{
		Execer:     types.GetExecName(pkt.IssuanceX, paraName),
		ActionName: "IssuanceClose",
		Payload:    []byte(fmt.Sprintf("{\"issuanceId\":\"%s\"}", issuanceID)),
	}

	var res string
	ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.CreateTransaction", params, &res)
	ctx.RunWithoutMarshal()
}

// IssuanceManageRawTxCmd 生成开始交易命令行
func IssuanceManageRawTxCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "manage",
		Short: "manage a issuance",
		Run:   IssuanceManage,
	}
	addIssuanceManageFlags(cmd)
	return cmd
}

func addIssuanceManageFlags(cmd *cobra.Command) {
	cmd.Flags().StringP("addr", "a", "", "addr")
	cmd.MarkFlagRequired("addr")
}

//IssuanceManage ...
func IssuanceManage(cmd *cobra.Command, args []string) {
	paraName, _ := cmd.Flags().GetString("paraName")

	rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
	addr, _ := cmd.Flags().GetString("addr")

	params := &rpctypes.CreateTxIn{
		Execer:     types.GetExecName(pkt.IssuanceX, paraName),
		ActionName: "IssuanceManage",
		Payload:    []byte(fmt.Sprintf("{\"addr\":[\"%s\"]}", addr)),
	}

	var res string
	ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.CreateTransaction", params, &res)
	ctx.RunWithoutMarshal()
}

//IssuacneQueryPriceCmd ...
func IssuacneQueryPriceCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "price",
		Short: "Query latest price",
		Run:   IssuanceQueryPrice,
	}
	return cmd
}

//IssuanceQueryPrice ...
func IssuanceQueryPrice(cmd *cobra.Command, args []string) {
	rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")

	var params rpctypes.Query4Jrpc
	params.Execer = pkt.IssuanceX

	params.FuncName = "IssuancePrice"
	var res pkt.RepIssuancePrice
	ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
	ctx.Run()
}

//IssuanceQueryUserBalanceCmd ...
func IssuanceQueryUserBalanceCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "balance",
		Short: "Query user balance",
		Run:   IssuanceQueryUserBalance,
	}
	addIssuanceQueryBalanceFlags(cmd)
	return cmd
}

func addIssuanceQueryBalanceFlags(cmd *cobra.Command) {
	cmd.Flags().StringP("address", "a", "", "address")
	cmd.MarkFlagRequired("address")
}

//IssuanceQueryUserBalance ...
func IssuanceQueryUserBalance(cmd *cobra.Command, args []string) {
	rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
	addr, _ := cmd.Flags().GetString("address")

	var params rpctypes.Query4Jrpc
	params.Execer = pkt.IssuanceX
	params.FuncName = "IssuanceUserBalance"
	req := &pkt.ReqIssuanceRecords{
		Addr: addr,
	}
	params.Payload = types.MustPBToJSON(req)

	var res pkt.RepIssuanceUserBalance
	ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
	ctx.Run()
}

// IssuanceQueryCmd 查询命令行
func IssuanceQueryCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "query",
		Short: "Query result",
		Run:   IssuanceQuery,
	}
	addIssuanceQueryFlags(cmd)
	cmd.AddCommand(
		IssuacneQueryPriceCmd(),
		IssuanceQueryUserBalanceCmd(),
	)
	return cmd
}

func addIssuanceQueryFlags(cmd *cobra.Command) {
	cmd.Flags().StringP("issuanceID", "g", "", "issuance ID")
	cmd.Flags().StringP("address", "a", "", "address")
	cmd.Flags().StringP("index", "i", "", "index")
	cmd.Flags().StringP("status", "s", "", "status")
	cmd.Flags().StringP("issuanceIDs", "e", "", "issuance IDs")
	cmd.Flags().StringP("debtID", "d", "", "debt ID")
}

//IssuanceQuery ...
func IssuanceQuery(cmd *cobra.Command, args []string) {
	rpcLaddr, _ := cmd.Flags().GetString("rpc_laddr")
	issuanceID, _ := cmd.Flags().GetString("issuanceID")
	address, _ := cmd.Flags().GetString("address")
	statusStr, _ := cmd.Flags().GetString("status")
	issuanceIDs, _ := cmd.Flags().GetString("issuanceIDs")
	debtID, _ := cmd.Flags().GetString("debtID")

	var params rpctypes.Query4Jrpc
	params.Execer = pkt.IssuanceX

	var status int64
	var err error
	if statusStr != "" {
		status, err = strconv.ParseInt(statusStr, 10, 32)
		if err != nil {
			fmt.Println(err)
			cmd.Help()
			return
		}
	}

	if issuanceID != "" {
		if address != "" {
			params.FuncName = "IssuanceRecordsByAddr"

			req := &pkt.ReqIssuanceRecords{
				IssuanceId: issuanceID,
				Status:     int32(status),
				Addr:       address,
			}
			params.Payload = types.MustPBToJSON(req)
			var res pkt.RepIssuanceRecords
			ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
			ctx.Run()
		} else if statusStr != "" {
			params.FuncName = "IssuanceRecordsByStatus"

			req := &pkt.ReqIssuanceRecords{
				IssuanceId: issuanceID,
				Status:     int32(status),
			}
			params.Payload = types.MustPBToJSON(req)
			var res pkt.RepIssuanceRecords
			ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
			ctx.Run()
		} else if debtID != "" {
			params.FuncName = "IssuanceRecordByID"

			req := &pkt.ReqIssuanceRecords{
				IssuanceId: issuanceID,
				DebtId:     debtID,
			}
			params.Payload = types.MustPBToJSON(req)
			var res pkt.RepIssuanceDebtInfo
			ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
			ctx.Run()
		} else {
			params.FuncName = "IssuanceInfoByID"

			req := &pkt.ReqIssuanceInfo{
				IssuanceId: issuanceID,
			}
			params.Payload = types.MustPBToJSON(req)
			var res pkt.RepIssuanceCurrentInfo
			ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
			ctx.Run()
		}
	} else if statusStr != "" {
		params.FuncName = "IssuanceByStatus"

		req := &pkt.ReqIssuanceByStatus{Status: int32(status)}
		params.Payload = types.MustPBToJSON(req)
		var res pkt.RepIssuanceIDs
		ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
		ctx.Run()
	} else if issuanceIDs != "" {
		params.FuncName = "IssuanceInfoByIDs"

		var issuanceIDsS []string
		issuanceIDsS = append(issuanceIDsS, issuanceIDs)
		issuanceIDsS = append(issuanceIDsS, issuanceIDs)
		req := &pkt.ReqIssuanceInfos{IssuanceIds: issuanceIDsS}
		params.Payload = types.MustPBToJSON(req)
		fmt.Println(params.Payload)
		var res pkt.RepIssuanceCurrentInfos
		ctx := jsonrpc.NewRPCCtx(rpcLaddr, "Chain33.Query", params, &res)
		ctx.Run()
	} else {
		cmd.Help()
	}
}


text:
#
# Copyright (c) 2016 Rokas Kupstys.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
if (ANDROID)
    if (NOT EXISTS ${CMAKE_BINARY_DIR}/libs)
        file (MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/libs)
    endif ()
    if (NOT EXISTS ${CMAKE_BINARY_DIR}/Android)
        file (COPY ${CMAKE_SOURCE_DIR}/Android DESTINATION ${CMAKE_BINARY_DIR})
        execute_process (COMMAND android update project -p ${CMAKE_BINARY_DIR}/Android -t 1)
    endif ()
    if (NOT EXISTS ${CMAKE_BINARY_DIR}/Android/libs)
        execute_process (COMMAND ${CMAKE_COMMAND} -E create_symlink ${CMAKE_BINARY_DIR}/libs ${CMAKE_BINARY_DIR}/Android/libs)
    endif ()
endif ()

if (NOT EXISTS ${CMAKE_BINARY_DIR}/bin)
    file (MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
endif ()

set (CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/dep/Urho3D/CMake/Modules)
set (URHO3D_SAMPLES     0 CACHE BOOL "" FORCE)
set (URHO3D_C++11       1 CACHE BOOL "" FORCE)
set (URHO3D_USE_LIB_DEB 1 CACHE BOOL "" FORCE)
set (URHO3D_PCH         0 CACHE BOOL "" FORCE)
set (URHO3D_LUA	        0 CACHE BOOL "" FORCE)
if (ANDROID)
    set (URHO3D_LIB_TYPE STATIC CACHE STRING "" FORCE)
    set (URHO3D_TOOLS 0 CACHE BOOL "" FORCE)
else ()
    set (URHO3D_LIB_TYPE SHARED CACHE STRING "" FORCE)
    set (URHO3D_TOOLS 1 CACHE BOOL "" FORCE)
endif ()

add_subdirectory (dep/Urho3D)
find_package (Urho3D)

add_definitions (-DURHO3D_CXX11=1)

license: MIT

license_type: permissive

branch_name: refs/heads/master

extension: cmake


text:
@InProceedings{alhelbawy-gaizauskas:2014:P14-2,
  author    = {Alhelbawy, Ayman  and  Gaizauskas, Robert},
  title     = {Graph Ranking for Collective Named Entity Disambiguation},
  booktitle = {Proceedings of the 52nd Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers)},
  month     = {June},
  year      = {2014},
  address   = {Baltimore, Maryland},
  publisher = {Association for Computational Linguistics},
  pages     = {75--80},
  url       = {http://www.aclweb.org/anthology/P14-2013}
}

repository: chbrown/tex

repo_name: chbrown/tex

extension: bib


text:
@ARTICLE{2013A&A...558A..33A,
       author = {{Astropy Collaboration} and {Robitaille}, Thomas P. and
         {Tollerud}, Erik J. and {Greenfield}, Perry and {Droettboom}, Michael and
         {Bray}, Erik and {Aldcroft}, Tom and {Davis}, Matt and
         {Ginsburg}, Adam and {Price-Whelan}, Adrian M. and
         {Kerzendorf}, Wolfgang E. and {Conley}, Alexander and {Crighton}, Neil and
         {Barbary}, Kyle and {Muna}, Demitri and {Ferguson}, Henry and
         {Grollier}, Fr{\'e}d{\'e}ric and {Parikh}, Madhura M. and
         {Nair}, Prasanth H. and {Unther}, Hans M. and {Deil}, Christoph and
         {Woillez}, Julien and {Conseil}, Simon and {Kramer}, Roban and
         {Turner}, James E.~H. and {Singer}, Leo and {Fox}, Ryan and
         {Weaver}, Benjamin A. and {Zabalza}, Victor and {Edwards}, Zachary I. and
         {Azalee Bostroem}, K. and {Burke}, D.~J. and {Casey}, Andrew R. and
         {Crawford}, Steven M. and {Dencheva}, Nadia and {Ely}, Justin and
         {Jenness}, Tim and {Labrie}, Kathleen and {Lim}, Pey Lian and
         {Pierfederici}, Francesco and {Pontzen}, Andrew and {Ptak}, Andy and
         {Refsdal}, Brian and {Servillat}, Mathieu and {Streicher}, Ole},
        title = "{Astropy: A community Python package for astronomy}",
      journal = {\aap},
     keywords = {methods: data analysis, methods: miscellaneous, virtual observatory tools, Astrophysics - Instrumentation and Methods for Astrophysics},
         year = "2013",
        month = "Oct",
       volume = {558},
          eid = {A33},
        pages = {A33},
          doi = {10.1051/0004-6361/201322068},
archivePrefix = {arXiv},
       eprint = {1307.6212},
 primaryClass = {astro-ph.IM},
       adsurl = {https://ui.adsabs.harvard.edu/abs/2013A&A...558A..33A},
      adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}

@ARTICLE{1996A&AS..117..393B,
       author = {{Bertin}, E. and {Arnouts}, S.},
        title = "{SExtractor: Software for source extraction.}",
      journal = {\aaps},
     keywords = {METHODS: DATA ANALYSIS, TECHNIQUES: IMAGE PROCESSING, GALAXIES: PHOTOMETRY},
         year = "1996",
        month = "Jun",
       volume = {117},
        pages = {393-404},
          doi = {10.1051/aas:1996164},
       adsurl = {https://ui.adsabs.harvard.edu/abs/1996A&AS..117..393B},
      adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}

@ARTICLE{2018AJ....156...82C,
       author = {{Cloutier}, Ryan and {Doyon}, Ren{\'e} and {Bouchy}, Francois and
         {H{\'e}brard}, Guillaume},
        title = "{Quantifying the Observational Effort Required for the Radial Velocity Characterization of TESS Planets}",
      journal = {\aj},
     keywords = {methods: analytical, planets and satellites: detection, planets and satellites: fundamental parameters, techniques: radial velocities, Astrophysics - Earth and Planetary Astrophysics},
         year = "2018",
        month = "Aug",
       volume = {156},
       number = {2},
          eid = {82},
        pages = {82},
          doi = {10.3847/1538-3881/aacea9},
archivePrefix = {arXiv},
       eprint = {1807.01263},
 primaryClass = {astro-ph.EP},
       adsurl = {https://ui.adsabs.harvard.edu/abs/2018AJ....156...82C},
      adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}

@ARTICLE{2015ApJ...805...23C,
       author = {{Corrales}, Lia},
        title = "{X-Ray Scattering Echoes and Ghost Halos from the Intergalactic Medium: Relation to the Nature of AGN Variability}",
      journal = {\apj},
     keywords = {accretion, accretion disks, dust, extinction, quasars: general, intergalactic medium, X-rays: ISM, Astrophysics - High Energy Astrophysical Phenomena, Astrophysics - Astrophysics of Galaxies},
         year = "2015",
        month = "May",
       volume = {805},
       number = {1},
          eid = {23},
        pages = {23},
          doi = {10.1088/0004-637X/805/1/23},
archivePrefix = {arXiv},
       eprint = {1503.01475},
 primaryClass = {astro-ph.HE},
       adsurl = {https://ui.adsabs.harvard.edu/abs/2015ApJ...805...23C},
      adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}

@ARTICLE{2013RMxAA..49..137F,
       author = {{Ferland}, G.~J. and {Porter}, R.~L. and {van Hoof}, P.~A.~M. and
         {Williams}, R.~J.~R. and {Abel}, N.~P. and {Lykins}, M.~L. and
         {Shaw}, G. and {Henney}, W.~J. and {Stancil}, P.~C.},
        title = "{The 2013 Release of Cloudy}",
      journal = {\rmxaa},
     keywords = {atomic processes, galaxies: active, methods: numerical, molecular processes, radiation mechanisms: general, Astrophysics - Galaxy Astrophysics, Astrophysics - Cosmology and Extragalactic Astrophysics, Astrophysics - Instrumentation and Methods for Astrophysics},
         year = "2013",
        month = "Apr",
       volume = {49},
        pages = {137-163},
archivePrefix = {arXiv},
       eprint = {1302.4485},
 primaryClass = {astro-ph.GA},
       adsurl = {https://ui.adsabs.harvard.edu/abs/2013RMxAA..49..137F},
      adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}

@INPROCEEDINGS{1989BAAS...21..780H,
       author = {{Hanisch}, R.~J. and {Biemesderfer}, C.~D.},
        title = "{T$_{E}$X and LAT$_{E}$X Macro Definition Files for Astronomical Publications}",
    booktitle = {\baas},
         year = "1989",
        month = "Mar",
        pages = {780},
       adsurl = {https://ui.adsabs.harvard.edu/abs/1989BAAS...21..780H},
      adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}

@BOOK{lamport94,
       author = {{Lamport}, L.},
        title = "{LaTeX: A Document Preparation System}",
    publisher = {Addison-Wesley Professional},
	 year = "1994",
      edition = {2},
	 isbn = {0201529831}
}

@ARTICLE{2018ApJ...868L..33L,
       author = {{Li}, Leping and {Zhang}, Jun and {Peter}, Hardi and
         {Chitta}, Lakshmi Pradeep and {Su}, Jiangtao and {Song}, Hongqiang and
         {Xia}, Chun and {Hou}, Yijun},
        title = "{Quasi-periodic Fast Propagating Magnetoacoustic Waves during the Magnetic Reconnection Between Solar Coronal Loops}",
      journal = {\apj},
     keywords = {magnetic reconnection, plasmas, Sun: corona, Sun: UV radiation, waves, Astrophysics - Solar and Stellar Astrophysics},
         year = "2018",
        month = "Dec",
       volume = {868},
       number = {2},
          eid = {L33},
        pages = {L33},
          doi = {10.3847/2041-8213/aaf167},
archivePrefix = {arXiv},
       eprint = {1811.08553},
 primaryClass = {astro-ph.SR},
       adsurl = {https://ui.adsabs.harvard.edu/abs/2018ApJ...868L..33L},
      adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}

@ARTICLE{2016AJ....152...41P,
       author = {{Pr{\v{s}}a}, Andrej and {Harmanec}, Petr and {Torres}, Guillermo and
         {Mamajek}, Eric and {Asplund}, Martin and {Capitaine}, Nicole and
         {Christensen-Dalsgaard}, J{\o}rgen and {Depagne}, {\'E}ric and
         {Haberreiter}, Margit and {Hekker}, Saskia},
        title = "{Nominal Values for Selected Solar and Planetary Quantities: IAU 2015 Resolution B3}",
      journal = {\aj},
     keywords = {planets and satellites: fundamental parameters, standards, stars: fundamental parameters, stars: general, Sun: fundamental parameters, Astrophysics - Solar and Stellar Astrophysics, Astrophysics - Earth and Planetary Astrophysics, Astrophysics - Instrumentation and Methods for Astrophysics},
         year = "2016",
        month = "Aug",
       volume = {152},
       number = {2},
          eid = {41},
        pages = {41},
          doi = {10.3847/0004-6256/152/2/41},
archivePrefix = {arXiv},
       eprint = {1605.09788},
 primaryClass = {astro-ph.SR},
       adsurl = {https://ui.adsabs.harvard.edu/abs/2016AJ....152...41P},
      adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}

@ARTICLE{2011ApJS..197...31S,
       author = {{Schwarz}, Greg J. and {Ness}, Jan-Uwe and {Osborne}, J.~P. and
         {Page}, K.~L. and {Evans}, P.~A. and {Beardmore}, A.~P. and
         {Walter}, Frederick M. and {Helton}, L. Andrew and
         {Woodward}, Charles E. and {Bode}, Mike and {Starrfield}, Sumner and
         {Drake}, Jeremy J.},
        title = "{Swift X-Ray Observations of Classical Novae. II. The Super Soft Source Sample}",
      journal = {\apjs},
     keywords = {novae, cataclysmic variables, ultraviolet: stars, X-rays: stars, Astrophysics - Solar and Stellar Astrophysics, Astrophysics - High Energy Astrophysical Phenomena},
         year = "2011",
        month = "Dec",
       volume = {197},
       number = {2},
          eid = {31},
        pages = {31},
          doi = {10.1088/0067-0049/197/2/31},
archivePrefix = {arXiv},
       eprint = {1110.6224},
 primaryClass = {astro-ph.SR},
       adsurl = {https://ui.adsabs.harvard.edu/abs/2011ApJS..197...31S},
      adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}

@ARTICLE{2014ApJ...793..127V,
       author = {{Vogt}, Fr{\'e}d{\'e}ric P.~A. and {Dopita}, Michael A. and
         {Kewley}, Lisa J. and {Sutherland}, Ralph S. and
         {Scharw{\"a}chter}, Julia and {Basurah}, Hassan M. and {Ali}, Alaa and
         {Amer}, Morsi A.},
        title = "{Galaxy Emission Line Classification Using Three-dimensional Line Ratio Diagrams}",
      journal = {\apj},
     keywords = {galaxies: abundances, galaxies: general, galaxies: Seyfert, galaxies: starburst, H II regions, ISM: lines and bands, Astrophysics - Astrophysics of Galaxies},
         year = "2014",
        month = "Oct",
       volume = {793},
       number = {2},
          eid = {127},
        pages = {127},
          doi = {10.1088/0004-637X/793/2/127},
archivePrefix = {arXiv},
       eprint = {1406.5186},
 primaryClass = {astro-ph.GA},
       adsurl = {https://ui.adsabs.harvard.edu/abs/2014ApJ...793..127V},
      adsnote = {Provided by the SAO/NASA Astrophysics Data System}
}

gha_license_id: MIT

gha_language: Jupyter Notebook


text:
require u-boot.inc
PR ="r0"
DEFAULT_PREFERENCE = "-1"

SRC_URI = "http://www.powerdeveloper.org/asset/by-id/89;name=uboot-efikamx \
          "
SRC_URI[uboot-efikamx.md5sum] = "072fbd97b293ac96d3f166e261c56131"
SRC_URI[uboot-efikamx.sha256sum] = "ee813d15e0e699340e5099641e01ac2952d42329d168deb48692a22a66d48965"

S = "${WORKDIR}/uboot-efikamx-${PV}"

python do_fetch () {
        import os,shutil
        bb.build.exec_func("base_do_fetch", d)
        if os.access(bb.data.expand("${DL_DIR}/89", d), os.R_OK):
                shutil.copy(bb.data.expand("${DL_DIR}/89", d), bb.data.expand("${DL_DIR}/${PN}-${PV}.tar.lzma", d))
}

python do_unpack () {
        bb.build.exec_func('efikamx_uboot_do_unpack', d)
}

efikamx_uboot_do_unpack (){
       (cd ${WORKDIR}; tar xf ${DL_DIR}/${PN}-${PV}.tar.lzma)
}

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD

extension: bb


text:
@article{RN866,
 author = {Kearns, T. M. and Speare, R. and Cheng, A. C. and McCarthy, J. and Carapetis, J. R. and Holt, D. C. and Currie, B. J. and Page, W. and Shield, J. and Gundjirryirr, R. and Bundhala, L. and Mulholland, E. and Chatfield, M. and Andrews, R. M.},
 doi = {10.1371/journal.pntd.0004151},
 journal = {PLoS Neglected Tropical Diseases},
 number = {10},
 pages = {1-13},
 title = {Impact of an Ivermectin Mass Drug Administration on Scabies Prevalence in a Remote Australian Aboriginal Community},
 type = {Journal Article},
 url = {https://www.scopus.com/inward/record.uri?eid=2-s2.0-84946020800&doi=10.1371%2fjournal.pntd.0004151&partnerID=40&md5=21288f1ba8609d1b706bc4493c9c4702
http://journals.plos.org/plosntds/article/file?id=10.1371/journal.pntd.0004151&type=printable},
 volume = {9},
 year = {2015}
}


text:
#msvcpch.cmake
#声明一个宏，参数如下
#USE_MSVC_PCH        ：宏名字
#PCH_TARGET          ：项目名称
#PCH_HEADER_FILE     ：预编译头文件名称（stdafx.h）
#PCH_SOURCE_FILE     ：预编译源文件名称（stdafx.cpp）
macro(USE_MSVC_PCH PCH_TARGET PCH_HEADER_FILE PCH_SOURCE_FILE)
if(MSVC)
	# 获取预编译头文件的文件名，通常是stdafx
	GET_FILENAME_COMPONENT(PCH_NAME ${PCH_HEADER_FILE} NAME_WE)

	# 生成预编译文件的路径
	if(CMAKE_CONFIGURATION_TYPES)
        # 如果有配置选项（Debug/Release），路径添加以及配置选项
		SET(PCH_DIR "${CMAKE_CURRENT_BINARY_DIR}/PCH/${CMAKE_CFG_INTDIR}")
	ELSE(CMAKE_CONFIGURATION_TYPES)
		SET(PCH_DIR "${CMAKE_CURRENT_BINARY_DIR}/PCH")
	ENDIF(CMAKE_CONFIGURATION_TYPES)

	# 创建预编译文件的路径
	FILE(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/PCH)

	# 设置项目属性，使用预编译头文件
	SET_TARGET_PROPERTIES(${PCH_TARGET} PROPERTIES COMPILE_FLAGS
		"/Yu${PCH_HEADER_FILE} /FI${PCH_HEADER_FILE} /Fp${PCH_DIR}/${PCH_NAME}.pch")

	# 预编译源文件（stdafx.cpp）设置属性，创建预编译文件
	SET_SOURCE_FILES_PROPERTIES(${PCH_SOURCE_FILE} PROPERTIES COMPILE_FLAGS
		"/Yc${PCH_HEADER_FILE}")

	# 把预编译文件寄到清除列表
	SET_DIRECTORY_PROPERTIES(PROPERTIES
		ADDITIONAL_MAKE_CLEAN_FILES ${PCH_DIR}/${PCH_NAME}.pch)
endif(MSVC)
endmacro(USE_MSVC_PCH)

repository: sailzeng/zcelib

repo_name: sailzeng/zcelib


text:
/*
Copyright 2022 The Koordinator 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 statesinformer

import (
	"context"
	"reflect"
	"sync"
	"time"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	apiruntime "k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/watch"
	clientset "k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
	"k8s.io/klog/v2"

	apiext "github.com/koordinator-sh/koordinator/apis/extension"
	"github.com/koordinator-sh/koordinator/pkg/koordlet/metrics"
	"github.com/koordinator-sh/koordinator/pkg/util"
)

const (
	nodeInformerName pluginName = "nodeInformer"
)

type nodeInformer struct {
	nodeInformer cache.SharedIndexInformer
	nodeRWMutex  sync.RWMutex
	node         *corev1.Node
}

func NewNodeInformer() *nodeInformer {
	return &nodeInformer{}
}

func (s *nodeInformer) GetNode() *corev1.Node {
	s.nodeRWMutex.RLock()
	defer s.nodeRWMutex.RUnlock()
	if s.node == nil {
		return nil
	}
	return s.node.DeepCopy()
}

func (s *nodeInformer) Setup(ctx *pluginOption, state *pluginState) {
	s.nodeInformer = newNodeInformer(ctx.KubeClient, ctx.NodeName)
	s.nodeInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			node, ok := obj.(*corev1.Node)
			if ok {
				s.syncNode(node)
			} else {
				klog.Errorf("node informer add func parse Node failed, obj %T", obj)
			}
		},
		UpdateFunc: func(oldObj, newObj interface{}) {
			oldNode, oldOK := oldObj.(*corev1.Node)
			newNode, newOK := newObj.(*corev1.Node)
			if !oldOK || !newOK {
				klog.Errorf("unable to convert object to *corev1.Node, old %T, new %T", oldObj, newObj)
				return
			}
			if reflect.DeepEqual(oldNode, newNode) {
				klog.V(5).Infof("find node %s has not changed", newNode.Name)
				return
			}
			s.syncNode(newNode)
		},
	})
}

func (s *nodeInformer) Start(stopCh <-chan struct{}) {
	klog.V(2).Infof("starting node informer")
	go s.nodeInformer.Run(stopCh)
	klog.V(2).Infof("node informer started")
}

func (s *nodeInformer) HasSynced() bool {
	if s.nodeInformer == nil {
		return false
	}
	synced := s.nodeInformer.HasSynced()
	klog.V(5).Infof("node informer has synced %v", synced)
	return synced
}

func newNodeInformer(client clientset.Interface, nodeName string) cache.SharedIndexInformer {
	tweakListOptionsFunc := func(opt *metav1.ListOptions) {
		opt.FieldSelector = "metadata.name=" + nodeName
	}

	return cache.NewSharedIndexInformer(
		&cache.ListWatch{
			ListFunc: func(options metav1.ListOptions) (apiruntime.Object, error) {
				tweakListOptionsFunc(&options)
				return client.CoreV1().Nodes().List(context.TODO(), options)
			},
			WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
				tweakListOptionsFunc(&options)
				return client.CoreV1().Nodes().Watch(context.TODO(), options)
			},
		},
		&corev1.Node{},
		time.Hour*12,
		cache.Indexers{},
	)
}

func (s *nodeInformer) setupNodeInformer() {
	s.nodeInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			node, ok := obj.(*corev1.Node)
			if ok {
				s.syncNode(node)
			} else {
				klog.Errorf("node informer add func parse Node failed, obj %T", obj)
			}
		},
		UpdateFunc: func(oldObj, newObj interface{}) {
			oldNode, oldOK := oldObj.(*corev1.Node)
			newNode, newOK := newObj.(*corev1.Node)
			if !oldOK || !newOK {
				klog.Errorf("unable to convert object to *corev1.Node, old %T, new %T", oldObj, newObj)
				return
			}
			if reflect.DeepEqual(oldNode, newNode) {
				klog.V(5).Infof("find node %s has not changed", newNode.Name)
				return
			}
			s.syncNode(newNode)
		},
	})
}

func (s *nodeInformer) syncNode(newNode *corev1.Node) {
	klog.V(5).Infof("node update detail %v", newNode)
	s.nodeRWMutex.Lock()
	defer s.nodeRWMutex.Unlock()
	s.node = newNode.DeepCopy()

	// also register node for metrics
	recordNodeResourceMetrics(newNode)
}

func recordNodeResourceMetrics(node *corev1.Node) {
	// register node labels
	metrics.Register(node)
	// record node resource metrics
	recordNodeResources(node)

	klog.V(5).Info("record node prometheus metrics successfully")
}

func recordNodeResources(node *corev1.Node) {
	if node == nil || node.Status.Allocatable == nil {
		klog.V(4).Infof("failed to record node resources metrics, node is invalid: %v", node)
		return
	}

	// record node allocatable of BatchCPU & BatchMemory
	if q, ok := node.Status.Allocatable[apiext.BatchCPU]; ok {
		metrics.RecordNodeResourceAllocatable(string(apiext.BatchCPU), float64(util.QuantityPtr(q).Value()))
	} else {
		metrics.RecordNodeResourceAllocatable(string(apiext.BatchCPU), 0)
	}
	if q, ok := node.Status.Allocatable[apiext.BatchMemory]; ok {
		metrics.RecordNodeResourceAllocatable(string(apiext.BatchMemory), float64(util.QuantityPtr(q).Value()))
	} else {
		metrics.RecordNodeResourceAllocatable(string(apiext.BatchMemory), 0)
	}
}

repository: alldatacenter/alldata

repo_name: alldatacenter/alldata

extension: go


text:
package accumulator

import (
	"fmt"
)

// TODO(jeb): Investigate the usage of obj->json + jsonPatch
// deepMerge merges two objects together
func deepMerge(dstVal interface{}, srcVal interface{}) (interface{}, error) {
	switch srcVal.(type) {
	case nil:
		// preserving non nil dstVal
		return dstVal, nil
	case []interface{}:
		return castAndMergeSlice(dstVal, srcVal)
	case map[string]interface{}:
		return castAndMergeMap(dstVal, srcVal)
	default:
		// preserving non nil srcVal
		return srcVal, nil
	}
}

func castAndMergeSlice(dstVal interface{}, srcVal interface{}) (interface{}, error) {
	switch dstValType := dstVal.(type) {
	case []interface{}:
		dstSlice := dstVal.([]interface{})
		srcSlice := srcVal.([]interface{})
		mergedSlice, err := deepMergeSlice(dstSlice, srcSlice)
		if err != nil {
			return dstVal, err
		}
		return mergedSlice, nil
	case nil:
		// preserving non nil srcVal
		return srcVal, nil
	default:
		return dstVal, fmt.Errorf("Conflicting type. Unable to merge %T", dstValType)
	}
}

func deepMergeSlice(dstSlice []interface{}, srcSlice []interface{}) ([]interface{}, error) {
	if len(dstSlice) != len(srcSlice) {
		return dstSlice,
			fmt.Errorf("Conflicting arrays. Unable to merge array with conflicting length")
	}
	for id, dstVal := range srcSlice {
		mergedVal, err := deepMerge(dstVal, srcSlice[id])
		if err != nil {
			return dstSlice, err
		}
		dstSlice[id] = mergedVal
	}

	return dstSlice, nil
}

func castAndMergeMap(dstVal interface{}, srcVal interface{}) (interface{}, error) {
	switch dstValType := dstVal.(type) {
	case map[string]interface{}:
		dstMap := dstVal.(map[string]interface{})
		srcMap := srcVal.(map[string]interface{})
		mergedMap, err := deepMergeMap(dstMap, srcMap)
		if err != nil {
			return dstVal, err
		}
		return mergedMap, nil
	case nil:
		// preserving non nil srcVal
		return srcVal, nil
	default:
		return dstVal,
			fmt.Errorf("Conflicting type. Unable to merge %T", dstValType)

	}
}

func deepMergeMap(dstMap map[string]interface{}, srcMap map[string]interface{}) (map[string]interface{}, error) {
	for key, srcVal := range srcMap {
		if dstVal, ok := dstMap[key]; ok {
			mergedVal, err := deepMerge(dstVal, srcVal)
			if err != nil {
				return dstMap, err
			}
			dstMap[key] = mergedVal
		} else {
			dstMap[key] = srcVal
		}
	}
	return dstMap, nil
}

// TODO(jeb): Investigate the usage of obj->json->obj conversion
// to replace those functions.
// deepCopy copies slice and map. Returns original value otherwise
func deepCopy(srcVal interface{}) interface{} {
	switch thing := srcVal.(type) {
	case nil:
		return srcVal
	case []interface{}:
		return deepCopySlice(thing)
	case map[string]interface{}:
		return deepCopyMap(thing)
	default:
		return srcVal
	}
}

func deepCopySlice(srcSlice []interface{}) []interface{} {
	dstSlice := make([]interface{}, len(srcSlice))
	for id, srcVal := range srcSlice {
		dstSlice[id] = deepCopy(srcVal)
	}
	return dstSlice
}

func deepCopyMap(srcMap map[string]interface{}) map[string]interface{} {
	dstMap := make(map[string]interface{})
	for key, srcVal := range srcMap {
		dstMap[key] = deepCopy(srcVal)
	}
	return dstMap
}

repository: puzzle/kustomize

repo_name: puzzle/kustomize

branch_name: refs/heads/allinone


text:
package models

import (
	"time"

	"github.com/jinzhu/gorm"
)

type UserSession struct {
	ID                   uint
	Turn                 uint
	Hit                  uint
	ExpiredAt            time.Time
	Answer               string
	AnswerCharacterNames string
	ResultSummary        string
}

func FindSession(db *gorm.DB, sessionId int) *UserSession {
	var session UserSession
	recordNotFound := db.Table("user_session").
		Where("id = ?", sessionId).Where("expired_at >= ?", time.Now()).
		First(&session).RecordNotFound()
	if recordNotFound {
		session = UserSession{
			Turn:      0,
			Hit:       0,
			ExpiredAt: time.Now().Add(time.Duration(1) * time.Hour),
		}
		db.Table("user_session").Create(&session)
	}
	return &session
}

func UpdateSession(db *gorm.DB, session *UserSession) {
	session.ExpiredAt = time.Now().Add(time.Duration(1) * time.Hour)
	db.Table("user_session").Save(session)
}

gha_language: Go


text:
package lb

type Lbvservercsvserverbinding struct {
	Cachetype     string `json:"cachetype,omitempty"`
	Cachevserver  string `json:"cachevserver,omitempty"`
	Hits          int    `json:"hits,omitempty"`
	Name          string `json:"name,omitempty"`
	Pipolicyhits  int    `json:"pipolicyhits,omitempty"`
	Policyname    string `json:"policyname,omitempty"`
	Policysubtype int    `json:"policysubtype,omitempty"`
	Priority      int    `json:"priority,omitempty"`
}

repository: chiradeep/go-nitro

repo_name: chiradeep/go-nitro


text:
// The code in this file were adapted from the following original source to sign YAML files.
// The original source: https://github.com/sigstore/cosign/blob/main/cmd/cosign/cli/sign.go

package cli

import (
	"context"
	_ "crypto/sha256" // for `crypto.SHA256`
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	gyaml "github.com/ghodss/yaml"
	"github.com/peterbourgon/ff/v3/ffcli"
	"github.com/pkg/errors"
	"gopkg.in/yaml.v2"

	"github.com/IBM/integrity-enforcer/cmd/pkg/yamlsign"
	"github.com/sigstore/cosign/cmd/cosign/cli"
	"github.com/sigstore/cosign/pkg/cosign"
	"github.com/sigstore/cosign/pkg/cosign/fulcio"
	"github.com/sigstore/rekor/pkg/generated/models"

	"github.com/sigstore/cosign/pkg/cosign/pivkey"
	"github.com/sigstore/sigstore/pkg/kms"
	"github.com/sigstore/sigstore/pkg/signature"
)

// VerifyCommand verifies a signature on a supplied container image
type SignYamlCommand struct {
	KeyRef      string
	Sk          bool
	PayloadPath string
	Pf          cosign.PassFunc
}

func SignYaml() *ffcli.Command {

	cmd := SignYamlCommand{}
	cmd.Pf = cli.GetPass
	flagset := flag.NewFlagSet("ishieldctl sign", flag.ExitOnError)

	flagset.StringVar(&cmd.KeyRef, "key", "", "path to the public key file, URL, or KMS URI")
	flagset.BoolVar(&cmd.Sk, "sk", false, "whether to use a hardware security key")
	flagset.StringVar(&cmd.PayloadPath, "payload", "", "path to the yaml file")

	return &ffcli.Command{
		Name:       "sign",
		ShortUsage: "ishieldctl sign -key <key path>|<kms uri> [-payload <path>]",
		ShortHelp:  `Sign the supplied yaml file.`,
		LongHelp: `Sign the supplied yaml file.

EXAMPLES
  # sign a yaml file with Google sign-in
  ishieldctl sign -payload <yaml file>

  # sign a yaml file with a local key pair file
  ishieldctl sign -key key.pub -payload <yaml file>

  # sign a yaml file with a key pair stored in Google Cloud KMS
  ishieldctl sign -key gcpkms://projects/<PROJECT>/locations/global/keyRings/<KEYRING>/cryptoKeys/<KEY> -payload <yaml file>

  # sign a yaml file will create <FILE>.signed in same directory (e.g. ishieldctl sign -payload test.yaml => test.yaml.signed)
  `,
		FlagSet: flagset,
		Exec:    cmd.Exec,
	}

}

func (c *SignYamlCommand) Exec(ctx context.Context, args []string) error {
	if c.PayloadPath == "" {
		return errors.New("no payloadpath found in arguments")
	}
	// prepare yaml payload as json ([] byte]
	payloadPath := c.PayloadPath

	// fetch yaml after removing annotations such as signature, certificate, message, and bundle (if exist)
	mPayload, _ := yamlsign.FetchYamlContent(payloadPath)
	cleanPayloadYaml, err := yaml.Marshal(mPayload)
	var payloadJson []byte
	payloadJson, err = gyaml.YAMLToJSON(cleanPayloadYaml)
	if err != nil {
		return errors.Wrap(err, "Failed to convert payload to json")
	}

	// sign payload and upload to tlog
	sig, cert, entry, err := c.SignPayload(ctx, payloadJson)
	if err != nil {
		return errors.Wrap(err, "Failed to sign payload")
	}

	// prepare bundle as json ([]byte)
	bundleJson, err := prepareBundleJson(entry)
	if err != nil {
		return errors.Wrap(err, "Failed to prepare bundle json")
	}

	// create yaml file with annotations such as signature, [certificate], message, and bundle
	if c.KeyRef != "" {
		err = yamlsign.WriteYamlContent(sig, nil, bundleJson, mPayload, payloadPath)
	} else {
		err = yamlsign.WriteYamlContent(sig, cert, bundleJson, mPayload, payloadPath)
	}
	if err != nil {
		return errors.Wrap(err, "Failed to create signed yaml file")
	}

	return nil
}

func (c *SignYamlCommand) SignPayload(ctx context.Context, payloadJson []byte) ([]byte, []byte, *models.LogEntryAnon, error) {

	var signer signature.Signer

	var cert string

	switch {
	case c.Sk:
		sk, err := pivkey.NewSignerVerifier()
		if err != nil {
			return nil, nil, nil, err
		}
		signer = sk

	case c.KeyRef != "":
		k, err := loadSignerFromKeyRef(ctx, c.KeyRef, c.Pf)
		if err != nil {
			return nil, nil, nil, errors.Wrap(err, "reading key")
		}
		signer = k
	default: // Keyless!
		fmt.Fprintln(os.Stderr, "Generating ephemeral keys...")
		k, err := fulcio.NewSigner(ctx)
		if err != nil {
			return nil, nil, nil, errors.Wrap(err, "Getting key from Fulcio")
		}
		signer = k
		cert, _ = k.Cert, k.Chain

	}

	sig, _, err := signer.Sign(ctx, payloadJson)
	if err != nil {
		return nil, nil, nil, errors.Wrap(err, "Error in signing")
	}

	// Upload the cert or the public key, depending on what we have
	var rekorBytes []byte
	if cert != "" {
		rekorBytes = []byte(cert)
	} else {
		pemBytes, err := cosign.PublicKeyPem(ctx, signer)
		if err != nil {
			return nil, nil, nil, errors.Wrap(err, "Error in loading certificate")
		}
		rekorBytes = pemBytes
	}

	entry, err := cosign.UploadTLog(sig, payloadJson, rekorBytes)
	if err != nil {
		return nil, nil, nil, errors.Wrap(err, "failed to upload to tlog")
	}

	fmt.Println("tlog entry created with index: ", *entry.LogIndex)

	return sig, rekorBytes, entry, nil
}

func prepareBundleJson(entry *models.LogEntryAnon) ([]byte, error) {
	if entry.Verification == nil {
		return nil, nil
	}
	bundle := &cosign.Bundle{
		SignedEntryTimestamp: entry.Verification.SignedEntryTimestamp,
		Body:                 entry.Body,
		IntegratedTime:       entry.IntegratedTime,
		LogIndex:             entry.LogIndex,
	}

	bundleJson, err := json.Marshal(bundle)

	if err != nil {
		return nil, err
	}

	return bundleJson, nil

}

func loadSignerFromKeyRef(ctx context.Context, keyRef string, pf cosign.PassFunc) (signature.Signer, error) {

	for prefix := range kms.ProvidersMux().Providers() {
		if strings.HasPrefix(keyRef, prefix) {
			return kms.Get(ctx, keyRef)
		}
	}

	kb, err := ioutil.ReadFile(filepath.Clean(keyRef))
	if err != nil {
		return signature.ECDSASignerVerifier{}, err
	}
	pass, err := pf(false)
	if err != nil {
		return signature.ECDSASignerVerifier{}, err
	}
	return cosign.LoadECDSAPrivateKey(kb, pass)
}

repository: katmutua/integrity-enforcer

repo_name: katmutua/integrity-enforcer


text:
// updatePagePairHandler.go handles updating a page pair

package site

import (
	"encoding/json"
	"fmt"
	"net/http"

	"zanaduu3/src/core"
	"zanaduu3/src/database"
	"zanaduu3/src/pages"
	"zanaduu3/src/sessions"
)

// updatePagePairData contains the data we get in the request.
type updatePagePairData struct {
	ID       string
	Level    int
	IsStrong bool
}

var updatePagePairHandler = siteHandler{
	URI:         "/updatePagePair/",
	HandlerFunc: updatePagePairHandlerFunc,
	Options: pages.PageOptions{
		RequireLogin: true,
	},
}

// updatePagePairHandlerFunc handles requests for adding a update tag.
func updatePagePairHandlerFunc(params *pages.HandlerParams) *pages.Result {
	decoder := json.NewDecoder(params.R.Body)
	var data updatePagePairData
	err := decoder.Decode(&data)
	if err != nil {
		return pages.Fail("Couldn't decode json", err).Status(http.StatusBadRequest)
	}

	return updatePagePairHandlerInternal(params.DB, params.U, &data)
}

func updatePagePairHandlerInternal(db *database.DB, u *core.CurrentUser, data *updatePagePairData) *pages.Result {
	returnData := core.NewHandlerData(u)
	var err error

	// Load the existing page pair
	var pagePair *core.PagePair
	queryPart := database.NewQuery(`WHERE pp.id=?`, data.ID)
	err = core.LoadPagePairs(db, queryPart, func(db *database.DB, pp *core.PagePair) error {
		pagePair = pp
		return nil
	})
	if err != nil {
		return pages.Fail("Failed to check for existing page pair: %v", err)
	} else if pagePair == nil {
		return pages.Fail("Couldn't find the page pair", nil).Status(http.StatusBadRequest)
	}

	// Load pages
	pagePair = &core.PagePair{
		ParentID: pagePair.ParentID,
		ChildID:  pagePair.ChildID,
		Type:     pagePair.Type,
	}
	parent, child, err := core.LoadFullEditsForPagePair(db, pagePair, u, returnData.DomainMap)
	if err != nil {
		return pages.Fail("Error loading pagePair pages", err)
	}

	// Check edit permissions
	permissionError, err := core.CanAffectRelationship(db.C, parent, child, pagePair.Type)
	if err != nil {
		return pages.Fail("Error verifying permissions", err)
	} else if permissionError != "" {
		return pages.Fail(permissionError, nil).Status(http.StatusForbidden)
	}

	// Do it!
	var pagePairID int64
	err2 := db.Transaction(func(tx *database.Tx) sessions.Error {
		// Update page pair
		hashmap := make(database.InsertMap)
		hashmap["id"] = data.ID
		hashmap["level"] = data.Level
		hashmap["isStrong"] = data.IsStrong
		statement := tx.DB.NewInsertStatement("pagePairs", hashmap, "level", "isStrong").WithTx(tx)
		_, err := statement.Exec()
		if err != nil {
			return sessions.NewError("Couldn't insert pagePair", err)
		}
		return nil
	})
	if err2 != nil {
		return pages.FailWith(err2)
	}

	returnData.ResultMap["pagePair"], err = core.LoadPagePair(db, fmt.Sprintf("%d", pagePairID))
	if err != nil {
		return pages.Fail("Error loading the page pair", err)
	}
	return pages.Success(returnData)
}


text:
package main

import (
	"context"
	"testing"
)

func Test_runTask(t *testing.T) {
	type args struct {
		ctx   context.Context
		secTO int
		n     *int
	}
	tests := []struct {
		name string
		args args
	}{
		// TODO: Add test cases.
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			runTask(tt.args.ctx, tt.args.secTO, tt.args.n)
		})
	}
}


text:
@article{Ratelle-2018-Design,
    title = "Design of a human biomonitoring community-based project in the Northwest Territories Mackenzie Valley, Canada, to investigate the links between nutrition, contaminants and country foods",
    author = "Ratelle, Mylene  and
      Laird, Matthew  and
      Majowicz, Shannon  and
      Skinner, Kelly  and
      Swanson, Heidi  and
      Laird, Brian",
    journal = "International Journal of Circumpolar Health, Volume 77, Issue 1",
    volume = "77",
    number = "1",
    year = "2018",
    publisher = "Informa UK Limited",
    url = "https://aclanthology.org/G18-105001",
    doi = "10.1080/22423982.2018.1510714",
    pages = "1510714",
}

repository: gwf-uwaterloo/gwf-publications

repo_name: gwf-uwaterloo/gwf-publications

branch_name: refs/heads/main

gha_language: Python


text:
SUMMARY = "JSON manipulation library"
DESCRIPTION = "This library allows you to easily construct JSON objects in C, \
output them as JSON formatted strings and parse JSON formatted \
strings back into the C representation of JSON objects."
HOMEPAGE = "https://github.com/json-c/json-c/wiki"

LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://COPYING;md5=de54b60fbbc35123ba193fea8ee216f2"

inherit debian-package
require recipes-debian/sources/json-c.inc
DEBIAN_UNPACK_DIR = "${WORKDIR}/${BPN}-${REPACK_PV}"

inherit autotools

RPROVIDES_${PN} = "libjson"

BBCLASSEXTEND = "native nativesdk"

repository: meta-debian/meta-debian

repo_name: meta-debian/meta-debian

branch_name: refs/heads/warrior

gha_language: BitBake


text:
LINUX_VERSION = "4.1"

SRCREV = "186070d46805086fe9b46d95ac6d0e257203e5a4"

include linux-altera.inc


text:
package models

type Trick struct {
	bidSuit BidSuit
	opener  Player
	North   *Card
	East    *Card
	South   *Card
	West    *Card
}

repository: sonivre/GoCoinche

repo_name: sonivre/GoCoinche


text:
package mUDP

import (
	"fmt"
	"net"
	"time"
)

const maxBufferSize = 1024

type void struct{}
type Session string
type Node struct {
	addr     *net.UDPAddr
	session  Session
	deadline int64
}

func (n *Node) String() string {
	return string(n.session)
}

type Server struct {
	hub  map[Session]*Node
	conn *net.UDPConn

	IsConnected func(*Node)
	IsRead      func(*Node, []byte)
	IsDelete    func(*Node)
}

//Send Send to client
func (s *Server) Send(node *Node, message []byte) {
	_, err := s.conn.WriteToUDP(message, node.addr)
	if err != nil {
		return
	}
}

// Delete client
func (s *Server) Delete(node *Node) {
	s.IsDelete(node)
	delete(s.hub, node.session)
}

//Run server
func (s *Server) Run(port uint16, timeDeadLine time.Duration) (err error) {
	s.hub = make(map[Session]*Node)
	udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("0.0.0.0:%d", port))
	if err != nil {
		return err
	}
	s.conn, err = net.ListenUDP("udp", udpAddr)
	if err != nil {
		return err
	}
	defer s.conn.Close()
	ticker := time.NewTicker(timeDeadLine)
	go func() {
		for range ticker.C {
			s.clearDeadLine()
		}
	}()
	buffer := make([]byte, maxBufferSize)
	for {
		var node *Node
		n, addr, err := s.conn.ReadFromUDP(buffer)
		if err != nil {
			continue
		}
		session := Session(fmt.Sprintf("%s:%d|%s", addr.IP.String(), addr.Port, addr.Zone))
		if _, ok := s.hub[session]; ok == false {
			//new node
			node = &Node{}
			node.session = session
			node.addr = addr
			s.hub[session] = node
			s.IsConnected(node)
		} else {
			node = s.hub[session]
		}
		node.deadline = time.Now().Add(timeDeadLine).Unix()
		s.IsRead(node, buffer[0:n])
	}
}

func (s *Server) clearDeadLine() {
	now := time.Now().Unix()
	for _, n := range s.hub {
		if n.deadline < now {
			s.Delete(n)
		}
	}
}

repository: averole/mUDP

repo_name: averole/mUDP


text:
// Copyright (C) 2019 Ali Shanaakh, github@shanaakh.pro
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.

package env

import (
	"fmt"
	"os"
)

// MustGetEnv panics if environment variable does not exist, otherwise returns value.
func MustGet(name string) string {
	value, exist := os.LookupEnv(name)

	if !exist {
		panic(fmt.Sprintf("Environment variable %s does not set", name))
	}

	return value
}

// GetEnv returns environment variable with ability to specify default value.
func Get(key, fallback string) string {
	value, exists := os.LookupEnv(key)

	if !exists {
		value = fallback
	}

	return value
}


text:
inherit setuptools3
require python-asn1crypto.inc

RDEPENDS_${PN}_class-target += " \
    ${PYTHON_PN}-shell \
"

repository: astarche/meta-openembedded

repo_name: astarche/meta-openembedded

branch_name: refs/heads/nilrt/master/sumo


text:
package workerpools

import (
	"github.com/go-playground/validator/v10"
	"github.com/go-playground/validator/v10/non-standard/validators"
)

type IDynamicWorkerPool interface {
	GetWorkerType() string

	IWorkerPool
}

type DynamicWorkerPool struct {
	WorkerType string `json:"WorkerType"`

	workerPool
}

// NewDynamicWorkerPool creates and initializes a dynamic worker pool.
func NewDynamicWorkerPool(name string, workerType string) *DynamicWorkerPool {
	return &DynamicWorkerPool{
		WorkerType: workerType,
		workerPool: *newWorkerPool(name, WorkerPoolTypeDynamic),
	}
}

// GetWorkerType returns the worker type for this worker pool.
func (d *DynamicWorkerPool) GetWorkerType() string {
	return d.WorkerType
}

// Validate checks the state of the dynamic worker pool and returns an error if
// invalid.
func (d *DynamicWorkerPool) Validate() error {
	v := validator.New()
	err := v.RegisterValidation("notblank", validators.NotBlank)
	if err != nil {
		return err
	}
	return v.Struct(d)
}

var _ IDynamicWorkerPool = &DynamicWorkerPool{}

repository: OctopusDeploy/go-octopusdeploy

repo_name: OctopusDeploy/go-octopusdeploy

gha_license_id: NOASSERTION


text:
@book{C.Cripps2006,
author = {{C. Cripps}, Steve},
booktitle = {Zhurnal Eksperimental'noi i Teoreticheskoi Fiziki},
doi = {10.1002/1521-3773(20010316)40:6<9823::AID-ANIE9823>3.3.CO;2-C},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/C. Cripps - 2006 - RF Power Amplifiers for Wireless Communications.pdf:pdf},
isbn = {9781596930186},
issn = {14337851},
number = {6},
pages = {456},
title = {{RF Power Amplifiers for Wireless Communications}},
url = {http://scholar.google.com/scholar?hl=en{\&}btnG=Search{\&}q=intitle:No+Title{\#}0},
volume = {40},
year = {2006}
}
@article{Colantonio2001,
abstract = {Multiharmonic manipulation is presented as the most effective solution to improve power amplifier (PA) efficiency performances. Remarkable improvements in output power, power gain and power-added efficiency (PAE) are demonstrated, properly manipulating the input and output second and third harmonics, as compared to more classical design approaches. Experimental results at 5GHz confirm the feasibility, the validity and effectiveness of the proposed approach, increasing the maximum measured power-added efficiency from 39{\%} to 61{\%}   {\textcopyright} 2001 John Wiley {\&} Sons, Inc. Int J RF and Microwave CAE 11: 366-384, 2001},
annote = {o   Proper load pull should vary harmonic load together with fundamental one to find global optimum
{\S}  Eqn 17
o   Class FG – Terminate second and third harmonics at the same time vs just terminating odd harmonics in Class F},
author = {Colantonio, Paolo and Giannini, Franco and Leuzzi, Giorgio and Limiti, Ernesto},
doi = {10.1002/mmce.1045},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Colantonio et al. - 2001 - Multiharmonic manipulation for highly efficient microwave power amplifiers.pdf:pdf},
issn = {10964290},
journal = {International Journal of RF and Microwave Computer-Aided Engineering},
keywords = {High efficiency,High linearity,Low voltage,Multiharmonic manipulation,Power amplifiers},
number = {6},
pages = {366--384},
title = {{Multiharmonic manipulation for highly efficient microwave power amplifiers}},
volume = {11},
year = {2001}
}
@article{Colantonio2003,
author = {Colantonio, Paolo and Giannini, Franco and Leuzzi, Giorgio and Limiti, Ernesto},
doi = {10.1002/mmce.10106},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Colantonio et al. - 2003 - Theoretical Facet and Experimental Results of Harmonic Tuned PAs.pdf:pdf},
issn = {10964290},
journal = {International Journal of RF and Microwave Computer-Aided Engineering},
keywords = {High efficiency,Multi harmonic manipulation,Power amplifiers},
number = {6},
pages = {459--472},
title = {{Theoretical Facet and Experimental Results of Harmonic Tuned PAs}},
volume = {13},
year = {2003}
}
@article{Colantonio1998,
abstract = {Power-amplifier class-F operation is investigated and revised, evidencing the fundamental importance of the harmonic-generating mechanism and the limitations im- posed by the device input and output nonlinearities on the ideal class-F behavior. Closed- form expressions are derived for the major design quantities, together with the optimum fundamental and third-harmonic loading of the active device. A design procedure, making use of the derived expressions, is presented and the deviations from the ideal behavior are discussed. Sample designs, making use of a full nonlinear device model and commercial analysis software, are carried out to demonstrate the effectiveness of the analysis and the design procedure. It is shown, both analytically and using commercial nonlinear simula- tions, that blind application of commonly used, idealized class-F harmonic terminations can cause unexpected detrimental results.},
annote = {o   Class F definition: terminating the device [amplifier] output with open circuit terminations at odd harmonic frequencies of the fundamental component and short circuiting it at even harmonics
o   With large signal drive, the inputs are no longer purely sinusoidal and have harmonic content
{\S}  Generation of harmonics is due to clipping from the forward conduction of the gate to pinch off of conduction
{\S}  Harmonic termination – tuned load if every harmonic component is loaded by an ideal short circuit termination
{\textperiodcentered}        Values of harmonic terminations for odd components [2,17,18]
o   Snider [2] – optimally loaded and overdriven PA to derive the correct termination at haromincs
o   Output device capacitance will eventually short out high order harmonics
o   Alpha is the conduction angle of the amplifier
o   optimum operation of class-F amplifiers [7-9] and indicate some useful guidelines for optimum design [10-12]
o   Fifth harmonic peaking in [5,6]
o   3rd harmonic must be out of phase with fundamental in order for ideal square wave nature. If in phase, will result in non ideal waveform. Bias must be between B and AB (deep AB)
{\S}  Class B bias cannot be used for practical class F
{\S}  Open termination for odd harmonics is only a mathematical result and doesn't explain mechanism for generating the odd harmonics
{\S}  Closed form equations and all that jazz!},
author = {Colantonio, Paolo and Giannini, Franco and Leuzzi, Giorgio and Limiti, Ernesto and Elettronica, Ingegneria and Vergata, Tor},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Colantonio et al. - 1998 - On the Class-F Power Amplifier Design.pdf:pdf},
pages = {129--149},
title = {{On the Class-F Power Amplifier Design}},
year = {1998}
}
@article{Gao2006,
abstract = {This article provides a tutorial and review of recent developments in high-efficiency class F RF/ microwave PAs. The principles of class-F RF PAs are explained first. Recent progress in their theory and in design techniques is then presented. Different approaches of class-F PA designs are explained, and some examples of practical designs are illustrated. Finally, an attempt is made to discuss the future developments of class-F RF/microwave PAs.},
annote = {{\textperiodcentered}        Cds of transistor will short out higher order harmonics
o   Quantify?
o   Should take in account output Cds in matching network
{\textperiodcentered}        Non linear Cgs will distort signal
o   Shunt diode on gate to compensate [21]
{\S}  Jeon - Input harmonics control using non-linear capacitor in GaAs FET power amplifier
{\textperiodcentered}        Matching networks for the input of the transistor will affect performance!
{\textperiodcentered}        2 stage amplifier
o   First stage provides enough input power for second stage and shapes input voltage waveform to half sinusoid for second stage [23]
{\S}  Ingruber - High-efficiency harmonic-control amplifier
o   Could use first stage inverse F and second stage standard F
{\textperiodcentered}        Closed form equations for relating input harmonic terminations for generating in phase output harmonics [27]-[29]
o   Colantonio et al
{\textperiodcentered}        Quarter wavelength matching network with LC tank on output will result in open for odd and short for even harmonics
o   Raab – Introduction of Class F amplifiers},
author = {Gao, S.},
doi = {10.1109/MMW.2006.1614233},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Gao - 2006 - High-efficiency class-F RFmicrowave power amplifiers.pdf:pdf},
issn = {1527-3342},
journal = {IEEE Microwave Magazine},
number = {1},
pages = {40--48},
title = {{High-efficiency class-F RF/microwave power amplifiers}},
volume = {7},
year = {2006}
}
@article{Grebennikov2000,
author = {Grebennikov, Av},
doi = {10.1109/MWSYM.2000.863295},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Grebennikov - 2000 - Circuit design technique for high efficiency class F amplifiers.pdf:pdf},
isbn = {078035687X},
journal = {{\ldots} Symposium Digest. 2000 IEEE MTT-S {\ldots}},
pages = {2--5},
title = {{Circuit design technique for high efficiency class F amplifiers}},
url = {http://ieeexplore.ieee.org/xpls/abs{\_}all.jsp?arnumber=863295},
year = {2000}
}
@article{He2010,
author = {He, Tian and Balaji, Uma},
doi = {10.2529/PIERS090829215408},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/He, Balaji - 2010 - Design of a Class F Power Amplifier.pdf:pdf},
issn = {1931-7360},
journal = {PIERS Online},
number = {2},
pages = {141--144},
title = {{Design of a Class F Power Amplifier}},
volume = {6},
year = {2010}
}
@book{Hella,
author = {Hella, Mona and Ismail, Mohammed},
file = {:C$\backslash$:/Users/Tannis/Google Drive/Thesis/PA/Papers/RF Cmos Power Amplifier.pdf:pdf},
isbn = {0792376439},
title = {{RF CMOS Power Amplifiers: Theory, Design and Implementation}}
}
@article{Ingruber1998,
abstract = {A half-sinusoidally driven class-A harmonic-control amplifier (hHCA) combines the advantage of high gain of class A with the advantage of high drain efficiency of class F. Con- sequently, power-added efficiency is increased as compared with state-of-the-art high-efficiency amplification techniques. As this innovative amplifier concept consists of a pulse-forming class- B amplifier stage followed by a class-A power-amplifier stage, intermodulation distortion is low even in saturation. The real- ization of such a two-stage hHCA offers 71{\%} overall efficiency, 27.9-dBm output power, and 22.4-dB gain at 1.62 GHz. Two-tone measurements at 1-dB-gain compression, where the amplifier's single-carrier (SC) overall efficiency is still 64{\%}, has demon- strated third- and fifth-order intermodulation distortion of ?29 and ?21 dBc, respectively. Index},
author = {Ingruber, Bernhard and Member, Student and Pritzl, Werner and Smely, Dieter and Wachutka, Martin and Magerl, Gottfried},
doi = {10.1109/22.681213},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Ingruber et al. - 1998 - High-Efficiency Harmonic-Control Amplifier.pdf:pdf},
isbn = {0018-9480 VO  - 46},
issn = {00189480},
number = {6},
pages = {857--862},
title = {{High-Efficiency Harmonic-Control Amplifier}},
volume = {46},
year = {1998}
}
@article{Inoue2004,
author = {Inoue, Akira and Ohta, Akira and Goto, Seiki and Ishikawa, Takahide and Matsuda, Yoshio},
doi = {10.1109/MWSYM.2004.1338991},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Inoue et al. - 2004 - The efficiency of class-F and inverse class-F amplifiers.pdf:pdf},
isbn = {0780383311},
issn = {0149645X},
journal = {IEEE MTT-S International Microwave Symposium Digest},
keywords = {FETs,Heterojunction bipolar transistors,Power amplifiers,Waveform analysis},
pages = {1947--1950},
title = {{The efficiency of class-F and inverse class-F amplifiers}},
volume = {3},
year = {2004}
}
@article{Kee2003,
abstract = { A new family of switching amplifiers, each member having some of the features of both class E and inverse F, is introduced. These class-E/F amplifiers have class-E features such as incorporation of the transistor parasitic capacitance into the circuit, exact truly switching time-domain solutions, and allowance for zero-voltage-switching operation. Additionally, some number of harmonics may be tuned in the fashion of inverse class F in order to achieve more desirable voltage and current waveforms for improved performance. Operational waveforms for several implementations are presented, and efficiency estimates are compared to class-E.},
author = {Kee, Scott D. and Aoki, Ichiro and Hajimiri, Ali and Rutledge, David},
doi = {10.1109/TMTT.2003.812564},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Kee et al. - 2003 - The class-EF family of ZVS switching amplifiers.pdf:pdf},
isbn = {0018-9480},
issn = {00189480},
journal = {IEEE Transactions on Microwave Theory and Techniques},
keywords = {Class E,Class E/F,Class F,Harmonic tuning,High-efficiency amplifier,Switching power amplifier,Zero voltage switching (ZVS)},
number = {6},
pages = {1677--1690},
title = {{The class-E/F family of ZVS switching amplifiers}},
volume = {51},
year = {2003}
}
@article{Kim2010,
author = {Kim, Jangheon and Mkadem, Farouk and Boumaiza, Slim},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Kim, Mkadem, Boumaiza - 2010 - A High Efficiency and Multi-Band Multi-Mode Power Amplifier using a Distributed Second Harmonic Terminat.pdf:pdf},
isbn = {9782874870163},
journal = {Microwave Conference (EuMC), 2010 European},
number = {September},
pages = {1662--1665},
title = {{A High Efficiency and Multi-Band / Multi-Mode Power Amplifier using a Distributed Second Harmonic Termination}},
year = {2010}
}
@article{Kim2011,
abstract = {A saturated power amplifier (PA) optimized for efficiency is described. As a PA is driven into saturated operation, the current source of the device generates a large third harmonic current, which creates a quasi-rectangular current waveform. The large nonlinear output capacitor of the transistor generates a second harmonic voltage with a very small third harmonic component. The second harmonic voltage is in-phase with the fundamental voltage, making a half-sine wave voltage waveform with voltage peaking. These waveforms are similar to those of a class {\textless}formula formulatype="inline"{\textgreater}{\textless}tex Notation="TeX"{\textgreater}{\$}{\{}\backslashhbox{\{}F{\}}{\}}{\^{}}{\{}{\{}-{\}}1{\}}{\$}{\textless}/tex{\textgreater} {\textless}/formula{\textgreater}. The fundamental load at the intrinsic device is resistive with the output capacitance tuned out, which is identical to the class {\textless}formula formulatype="inline"{\textgreater}{\textless}tex Notation="TeX"{\textgreater}{\$}{\{}\backslashhbox{\{}F{\}}{\}}{\^{}}{\{}{\{}-{\}}1{\}}{\$}{\textless}/tex{\textgreater}{\textless}/formula{\textgreater} case. However, the required harmonic impedances are just larger than the impedance levels of the output capacitance for both the second and third harmonics. Therefore, the circuit topology is similar to that of a class E amplifier, which is very simple. The PA implemented using a GaN HEMT delivers the expected good performance using the simple circuit topology.},
author = {Kim, Jungjoon and Kim, Jangheon and Moon, Junghwan and Son, Jungwhan and Kim, Ildu and Jee, Seunghoon and Kim, Bumman},
doi = {10.1109/TMTT.2011.2155665},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Kim et al. - 2011 - Saturated power amplifier optimized for efficiency using self-generated harmonic current and voltage.pdf:pdf},
issn = {00189480},
journal = {IEEE Transactions on Microwave Theory and Techniques},
keywords = {Efficiency,load-pull simulation,nonlinear capacitance,power amplifier (PA),saturation},
number = {8},
pages = {2049--2058},
title = {{Saturated power amplifier optimized for efficiency using self-generated harmonic current and voltage}},
volume = {59},
year = {2011}
}
@article{Kye-Ik1997,
abstract = {We address the effect of gate signal distortion arising from capacitance non-linearity on the power added efficiencies of power amplifiers based on FETs. A novel method which can compensate the non-linearity of gate capacitance is proposed. The key idea is that a reversed diode is connected to the gate, where the gate and source part of a FET is simply modeled as a diode. We demonstrated this scheme with the load-pull and source-pull measurement of the circuit. A 7{\%} increase in power added efficiency is achieved},
author = {Kye-Ik, Jeon and Young-Se, Kwon and Song-Cheol, Hong},
doi = {10.1109/MWSYM.1997.602919},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Kye-Ik, Young-Se, Song-Cheol - 1997 - Input harmonics control using non-linear capacitor in GaAs FET power amplifier.pdf:pdf},
isbn = {0149-645X},
issn = {0149-645X},
journal = {Microwave Symposium Digest, 1997., IEEE MTT-S International},
keywords = {GaAs,GaAs FET power amplifier,III-V semiconductors,MMIC power amplifiers,capacitance nonlinearity,compensation,electric distortion,field effect MMIC,gallium arsenide,gate capacitance compensation,gate signal distortion,harmonics,input harmonics control,microwave power amplifiers,nonlinear capacitor,power added efficiencies,reversed diode},
pages = {817--820 vol.2},
title = {{Input harmonics control using non-linear capacitor in GaAs FET power amplifier}},
volume = {2},
year = {1997}
}
@article{Lucyszyn1997,
author = {Lucyszyn, S},
doi = {10.1080/002072197136110},
file = {:C$\backslash$:/Users/Tannis/Google Drive/Thesis/PA/Papers/pae errors with rf pa.PDF:PDF},
issn = {00207217},
journal = {International Journal of Electronics},
number = {3},
pages = {303--312},
title = {{Power-Added Efficiency Errors With RF Power Amplifiers}},
volume = {82 (3)},
year = {1997}
}
@article{Moon2012,
author = {Moon, Junghwan and Jee, Seunghoon and Kim, Jungjoon and Kim, Jangheon and Kim, Bumman},
doi = {10.1109/TMTT.2012.2190749},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Moon et al. - 2012 - Behaviors of class-F and Class-F -1 Amplifiers.pdf:pdf},
issn = {00189480},
journal = {IEEE Transactions on Microwave Theory and Techniques},
keywords = {Class-F -1,class-F,efficiency,nonlinear capacitor,power amplifier (PA),saturated PA},
number = {6 PART 2},
pages = {1937--1951},
title = {{Behaviors of class-F and Class-F -1 Amplifiers}},
volume = {60},
year = {2012}
}
@article{Nikandish2014,
abstract = {This paper presents a harmonic termination technique for single- and multi-band high-efficiency class-F monolithic microwave integrated circuit (MMIC) power amplifiers (PAs). The harmonic termination network (HTN), realized with the minimum possible number of elements, can be used to terminate an arbitrary number of harmonics in a single-band PA or harmonics of multiple frequencies in a concurrent multi-band PA. The drain and gate bias lines are embedded in the HTNs to obviate the need for RF chokes and reduce the chip area. A single- and a dual-band MMIC PA are designed using the proposed technique and implemented in a 0.25- $\mu$m AlGaAs-InGaAs pHEMT technology. The single-band 5.5-GHz PA provides 27.5 dBm of output power with 70{\%} power-added efficiency (PAE). This PAE level is achieved by terminating the first five harmonics at the output as well as the first three harmonics at the input of PA. The dual-band PA, operating at 5 and 12 GHz, delivers the output power of 28.0 and 26.7 dBm with PAE of 58{\%} and 51{\%}, at the two frequency bands, respectively.},
author = {Nikandish, Gholamreza and Babakrpur, Esmail and Medi, Ali},
doi = {10.1109/TMTT.2014.2315591},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Nikandish, Babakrpur, Medi - 2014 - A harmonic termination technique for single-and multi-band high-efficiency class-F MMIC power amplif.pdf:pdf},
issn = {00189480},
journal = {IEEE Transactions on Microwave Theory and Techniques},
keywords = {Class F,high-efficiency,monolithic microwave integrated circuit (MMIC),multi-band,power amplifier (PA)},
number = {5},
pages = {1212--1220},
title = {{A harmonic termination technique for single-and multi-band high-efficiency class-F MMIC power amplifiers}},
volume = {62},
year = {2014}
}
@article{Raab2003c,
abstract = {Linearization methods are niques are incorpo-the focus of Part 4 of$\backslash$nour rated into power series on power amplifiers, amplifiers and transmit-which$\backslash$ndescribes the basic ters for the dual purposes architecture and perfor-$\backslash$nof improving linearity mance capabilities of feed- and for allowing$\backslash$noperaback, feedforward and tion with less back-off predistortion$\backslash$ntechniques and therefore higher efficiency. This article provides$\backslash$na summary of the three main families of techniques have been developed:$\backslash$nFeedback, feedforward, and predistortion. 8a. FEEDBACK Feedback linearization$\backslash$ncan be applied either directly around the RF amplifier (RF},
author = {Raab, By Frederick H and Asbeck, Peter and Cripps, Steve and Kenington, Peter B and Popovich, Zoya B and Pothecary, Nick and Sevic, John F and Sokal, Nathan O},
file = {:C$\backslash$:/Users/Tannis/Google Drive/Thesis/PA/Papers/HFE1103{\_}RaabPart4.pdf:pdf},
journal = {High Frequency Electronics},
number = {November},
pages = {38--49},
title = {{RF and Microwave Power Amplifier and Transmitter Technologies - Part 4}},
year = {2003}
}
@article{Raab2001,
abstract = {A class-F power amplifier (PA) improves efficiency and$\backslash$npower-output capability (over that of class A) by using selected$\backslash$nharmonics to shape its drain-voltage and drain-current waveforms.$\backslash$nTypically, one waveform (e.g., voltage) approximates a square wave,$\backslash$nwhile the other (e.g., current) approximates a half sine wave. The$\backslash$noutput power and efficiency of an ideal class-F PA can be related to the$\backslash$nFourier coefficients of the waveforms, and Fourier coefficients for$\backslash$nmaximally flat waveforms have been determined. This paper extends that$\backslash$ntheory by determining the coefficients for the maximum power and$\backslash$nefficiency possible in a class-F PA with a given set of controlled$\backslash$nharmonics},
annote = {{\textperiodcentered}        To find maximum efficiency and power output capability for a set of harmonics},
author = {Raab, F.H.},
doi = {10.1109/22.925511},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Raab - 2001 - Maximum efficiency and output of class-F power amplifiers.pdf:pdf},
issn = {0018-9480},
journal = {IEEE Transactions on Microwave Theory and Techniques},
number = {6},
pages = {1162--1166},
title = {{Maximum efficiency and output of class-F power amplifiers}},
volume = {49},
year = {2001}
}
@article{Raab2003a,
annote = {Awesome summary!},
author = {Raab, F.H. and Asbeck, Peter and Cripps, Steve and Kenington, P.B. and Popovic, Z.B. and Pothecary, Nick and Sevic, J.F. and Sokal, N.O.},
file = {:C$\backslash$:/Users/Tannis/Google Drive/Thesis/PA/Papers/HFE0503{\_}RaabPart1.pdf:pdf},
journal = {High Frequency Electronics},
number = {5},
pages = {22--36},
title = {{RF and microwave power amplifier and transmitter technologies - Part 1}},
url = {http://www.feng.pucrs.br/{~}decastro/pdf/RF{\&}MicrowavePowerAmp{\&}XMTRs.pdf},
volume = {2},
year = {2003}
}
@article{Raab1997,
abstract = {Class-F power amplifiers (PA's) employ harmonic-frequency resonators to shape their drain or collector waveforms to improve efficiency. Generally, the output network must present the drain with either an open or short circuit at the harmonic frequencies. At VHF and higher frequencies, the drain capacitance, lead inductance, lead length, and dispersion make implementation of reasonably ideal tuned circuits difficult. However it is possible to control the impedances at a finite number of harmonics. This note first derives the basic relationships among the Fourier coefficients of the waveforms and the performance of the amplifier. Fourier coefficients for maximally flat waveforms are then derived for inclusion of up to the fifth harmonic. Amplifier performance is then tabulated as a function of which harmonics are included in the voltage and current waveforms. Efficiency increases from 50{\%} of class A toward 100{\%} as harmonics are added. Power-output capability increases by up to 27{\%}},
author = {Raab, Frederick H.},
doi = {10.1109/22.644215},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Raab - 1997 - Class-F Power Amplifiers with Maximally Flat Waveforms.pdf:pdf},
isbn = {0018-9480},
issn = {00189480},
journal = {IEEE Transactions on Microwave Theory and Techniques},
keywords = {Amplifier,Class-f,Power},
number = {11},
pages = {2007--2012},
title = {{Class-F Power Amplifiers with Maximally Flat Waveforms}},
volume = {45},
year = {1997}
}
@article{Raab2004,
author = {Raab, Frederick H. and Asbeck, Peter and Cripps, Steve and Kenington, Peter B. and Popovic, Zoya B. and Pothecary, Nick and Sevic, John F. and Sokal, Nathan O.},
file = {:C$\backslash$:/Users/Tannis/Google Drive/Thesis/PA/Papers/HFE0104{\_}RaabPart5.pdf:pdf},
journal = {High Frequency Electronics},
number = {January},
pages = {46--54},
title = {{RF and Microwave Power Amplifier and Transmitter Technologies - Part 5}},
year = {2004}
}
@article{Raab2003b,
author = {Raab, Frederick H. and Asbeck, Peter and Cripps, Steve and Kenington, Peter B. and Popovic, Zoya B. and Pothecary, Nick and Sevic, John F. and Sokal, Nathan O.},
file = {:C$\backslash$:/Users/Tannis/Google Drive/Thesis/PA/Papers/HFE0903{\_}RaabPart3.pdf:pdf},
journal = {High Frequency Electronics},
number = {9},
pages = {34--48},
title = {{RF and Microwave Power Amplifier and Transmitter Technologies - Part 3}},
year = {2003}
}
@article{Raab2003,
annote = {Summary of amplifier classes},
author = {Raab, Frederick H. and Asbeck, Peter and Cripps, Steve and Kenington, Peter B. and Popovic, Zoya B. and Pothecary, Nick and Sevic, John F. and Sokal, Nathan O.},
file = {:C$\backslash$:/Users/Tannis/Google Drive/Thesis/PA/Papers/HFE0703{\_}RaabPart2.pdf:pdf},
journal = {High Frequency Electronics},
number = {5},
pages = {22--36},
title = {{RF and Microwave Power Amplifier and Transmitter Technologies - Part 2}},
year = {2003}
}
@article{Raab2002,
abstract = {The generation of RF/microwave power is required not only in$\backslash$nwireless communications, but also in applications such as jamming,$\backslash$nimaging, RF heating, and miniature dc/dc converters. Each application$\backslash$nhas its own unique requirements for frequency, bandwidth, load, power,$\backslash$nefficiency, linearity, and cost. RF power is generated by a wide variety$\backslash$nof techniques, implementations, and active devices. Power amplifiers are$\backslash$nincorporated into transmitters in a similarly wide variety of$\backslash$narchitectures, including linear, Kalm, envelope tracking, outphasing,$\backslash$nand Doherty. Linearity can be improved through techniques such as$\backslash$nfeedback, feedforward, and predistortion},
annote = {Great summary of classes},
author = {Raab, Frederick H. and Asbeck, Peter and Cripps, Steve and Kenington, Peter B. and Popovi{\'{c}}, Zoya B. and Pothecary, Nick and Sevic, John F. and Sokal, Nathan O.},
doi = {10.1109/22.989965},
file = {:C$\backslash$:/Users/Tannis/Google Drive/Thesis/PA/Papers/pa amp and tx for rf.pdf:pdf},
isbn = {0018-9480},
issn = {00189480},
journal = {IEEE Transactions on Microwave Theory and Techniques},
keywords = {Amplifier,Chireix,Class A,Class B,Class C,Class D,Class E,Class F,Doherty,Envelope tracking,Feedback,Feedforward,HF,Kahn,Microwave,Outphasing,Power,Predistortion,T ransmitter,UHF,VHF},
number = {3},
pages = {814--826},
title = {{Power amplifiers and transmitters for RF and microwave}},
volume = {50},
year = {2002}
}
@article{Rosu2001,
author = {Rosu, Iulian},
file = {:C$\backslash$:/Users/Tannis/Google Drive/Thesis/PA/Papers/RF{\_}Power{\_}Amplifiers HAM.pdf:pdf},
isbn = {0471350524},
pages = {1--20},
title = {{RF power amplifiers}},
url = {http://books.google.com/books?hl=en{\&}lr={\&}id=HrDXZctHzUQC{\&}oi=fnd{\&}pg=PP7{\&}dq=RF+Power+Amplifiers{\&}ots=YkyOJPqaUn{\&}sig=AN7hc{\_}1TyZqPjXNWeMpISOXDomg$\backslash$nhttp://books.google.com/books?hl=en{\&}lr={\&}id=HrDXZctHzUQC{\&}oi=fnd{\&}pg=PP7{\&}dq=RF+power+amplifiers{\&}ots=YkyOJPqaVs{\&}sig=Or},
year = {2001}
}
@book{Rudiakova2006,
author = {Rudiakova, Anna and Krizhanovski, V.},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Rudiakova, Krizhanovski - 2006 - Advanced Design Techniques for Rf Power Amplifiers.pdf:pdf},
isbn = {9781402046384},
title = {{Advanced Design Techniques for Rf Power Amplifiers}},
year = {2006}
}
@article{Tsang2010,
abstract = {Advanced Design System (ADS) from Agilent is used for design and simulation based on the ADS model of Cree's CGH40010 high electron mobility transistor (HEMT). A high efficiency power amplifier is fabricated on RT/duroid 5870 high frequency laminate board. In this design, the harmonics at the input are controlled as well as the harmonics at the output. An input wave-shaping network is designed to shape the waveforms at the gate. In this case, the PAE is boosted 30{\%} higher than the PA with only the output wave- shaping network. By terminating harmonics with proper impedances at the output, a square voltage waveform and a half-sine current waveform are obtained at the transistor drain terminal. The overlapping area between the voltage and current waveforms can be reduced as well as the active device power consumption. The final design operating at 1GHz produced a PAE of 89{\%} with 38.35dBm output power in simulation and PAE of 78{\%} with 38.7dBm output power as the result of the IEEE PA design contest. Conclusion},
author = {Tsang, Kai Shing},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Tsang - 2010 - Class-F Power Amplifier with Maximized PAE.pdf:pdf},
number = {August},
title = {{Class-F Power Amplifier with Maximized PAE}},
year = {2010}
}
@article{Woo2006,
abstract = { This paper presents analytic and experimental comparisons for high-efficiency class-F and inverse class-F amplifiers. The analytic formula of the efficiencies, output powers, dc power dissipations, and fundamental load impedances of both amplifiers are derived from the ideal current and voltage waveforms. Based on the formula, the performances are compared with a reasonable condition: fundamental output power levels of class-F and inverse class-F amplifiers are conditioned to be identical. The results show that the inverse class-F amplifier has better efficiency than that of class-F amplifiers as the on-resistance of the transistor increases. For experimental comparison, we have designed and implemented the class-F and inverse class-F amplifiers at I-GHz band using a GaAs MESFET and analyzed the measured performances. Experimental results shows 10{\%} higher power-added efficiency of the inverse class-F amplifier than that of the class-F amplifier, which verifies the waveform analysis.},
author = {Woo, Young Yun and Yang, Youngoo and Kim, Bumman},
doi = {10.1109/TMTT.2006.872805},
file = {:C$\backslash$:/Users/Tannis/AppData/Local/Mendeley Ltd./Mendeley Desktop/Downloaded/Woo, Yang, Kim - 2006 - Analysis and experiments for high-efficiency class-F and inverse class-F power amplifiers.pdf:pdf},
issn = {00189480},
journal = {IEEE Transactions on Microwave Theory and Techniques},
keywords = {Class-F amplifier,Harmonies control circuit,Highefficiency amplifier,Inverse class-F amplifier,Power amplifier},
number = {5},
pages = {1969--1973},
title = {{Analysis and experiments for high-efficiency class-F and inverse class-F power amplifiers}},
volume = {54},
year = {2006}
}

repository: skyshiro/thesis

repo_name: skyshiro/thesis


text:
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"time"

	"github.com/go-chi/chi"
	"github.com/go-chi/chi/middleware"
	"github.com/ironarachne/random"
	"github.com/ironarachne/towngen"
)

func getTown(w http.ResponseWriter, r *http.Request) {
	id := chi.URLParam(r, "id")

	var newTown towngen.Town

	random.SeedFromString(id)

	newTown = towngen.GenerateTown("random", "random")

	json.NewEncoder(w).Encode(newTown)
}

func getTownRandom(w http.ResponseWriter, r *http.Request) {
	var newTown towngen.Town

	rand.Seed(time.Now().UnixNano())

	newTown = towngen.GenerateTown("random", "random")

	json.NewEncoder(w).Encode(newTown)
}

func main() {
	r := chi.NewRouter()

	r.Use(middleware.RequestID)
	r.Use(middleware.RealIP)
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)
	r.Use(middleware.URLFormat)
	r.Use(middleware.SetHeader("Content-Type", "application/json"))

	r.Use(middleware.Timeout(60 * time.Second))

	r.Get("/", getTownRandom)
	r.Get("/{id}", getTown)

	fmt.Println("Town Generator API is online.")
	log.Fatal(http.ListenAndServe(":7979", r))
}

repository: pgotsis/towngen

repo_name: pgotsis/towngen


text:
.pane {
  max-width: 960px;
  width: 100%;
  margin: 0 auto;
}

.paneflex {
  composes: pane;
  display: flex;
  align-items: center;
}
.paneflex > * {
  flex: 0 0 auto;
}

repository: aarontbt/xenoweb-gatsby

repo_name: aarontbt/xenoweb-gatsby

gha_language: JavaScript

extension: css


text:
package migrations

import (
	"database/sql"

	"github.com/pkg/errors"
)

var Migrations = []string{
	CreateAdminsTable,
	CreateAuthTokensTable,
	CreateAdminSessionsTable,
	CreateUsersTable,
	CreateUserSessionsTable,
	CreateBrandsTable,
	CreateIXRulesTable,
	CreateTickersTable,
	CreateCorporationsTable,
	CreateEventsTable,
	AlterTickersCorporationsTable,
	CreateCorpMappingTable,
	AlterCorpsTableAddISINCUSIP,
	AlterBrandsTableAddPublished,
	AlterUserTableAddHash,
	AlterUserTableAddApiKey,
	AlterAdminTableAddApiKey,
	AlterUserTableMakeApiKeyUnique,
	AlterEventsAddAuthMethod,
	AlterAuthTokensAddSalt,
	CreateLocationsTable,
	AlterLocationsAddCheckedAt,
	CreateDatasetsAndCustomersTable,
	UserBelongsToCustomer,
	AlterEventsAddOnDataset,
	CreateBrandCategoryTable,
	AddCategoryIDToBrands,
	AlterEventsAddOnCustomer,
	AlterEventsAddOnCustomerOnDatasetIndices,
	AddSftpSessionsTable,
	AlterUserTableAddSftpCreds,
	AddDatasetRelationships,
	AddDatasetManageFlag,
	AddScopedConstraintsToCorps,
	AddDataFingerprinting,
	AddTimestampsToFingerprintCorps,
	DataFingerprintingUpdates,
	DatasetsConsistencyUpdates,
	CreateUserCustomerView,
	TagTypeAndTagNaturalKeys,
	FingerprintTagView,
	UserTableCleanups,
	AddAuditTrail,
	ManageableTypoFix,
	UsersDropSuspendedAt,
	CustomersDropUpdatedAt,
	UsersFixSFTPPubKey,
	UsersFixSFTPPubKeyEncoding,
	FingerprintCorps,
	FingerprintCorpsConstraints,
	FingerprintCorpsRemoveType,
	FingerprintCorpsNotNull,
	MigrateAdminsToUsers,
	DropAdminTables,
	TagJobsAndTasks,
	ChangeCorpsConstraint,
	DataFingerprintingHistory,
	DataFingerprintViewsWithUsers,
	TagJobAndTaskRemove,
	LocationsTableCleanups,
	AddGeonamesTable,
	FpLevelCorpMappings,
	LocationsDropUpdatedAt,
	FingerprintTagConfidence,
	AddGeonamesIDToLocations,
	RemoveGeonamesTables,
	AddGeoanmesPostalCodeSearch,
	DeleteCPGLocations,
	AddUpdatedAtToFingerprints,
	InitialTagAppCreation,
	FingerprintUpdateCascade,
	FingerprintSearchPerformanceUpdates,
	IndexSortBrandConsConfidence,
	DropOldFingerprintTables,
	ExtraFieldsOnTag,
	AddCorpMappings,
	AddCorpMappingConstraints,
	FixCorpMappingConstraints,
	CustomerUserLogin,
}

func Drop(db *sql.DB) error {
	rows, err := db.Query(`SELECT 'DROP TABLE IF EXISTS "' || tablename || '" CASCADE;' FROM pg_tables WHERE schemaname='public';`)
	if err != nil {
		return err
	}
	defer rows.Close()

	for rows.Next() {
		var query string
		err := rows.Scan(&query)
		if err != nil {
			return err
		}
		if _, err := db.Exec(query); err != nil {
			return err
		}
	}
	return nil
}

func Migrate(db *sql.DB) error {
	tx, err := db.Begin()
	if err != nil {
		return err
	}

	if _, err := tx.Exec("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;"); err != nil {
		tx.Rollback()
		return err
	}

	_, err = tx.Exec(`CREATE TABLE IF NOT EXISTS migrations(version INTEGER NOT NULL);`)
	if err != nil {
		panic(err)
	}

	var version int
	row := tx.QueryRow(`SELECT version FROM migrations LIMIT 1;`)
	if err := row.Scan(&version); err != nil {
		if errors.Cause(err) != sql.ErrNoRows {
			tx.Rollback()
			return err
		}

		if _, err := tx.Exec(`INSERT INTO migrations(version) VALUES(0);`); err != nil {
			tx.Rollback()
			return err
		}

		version = 0
	}

	for i := version; i < len(Migrations); i++ {
		if _, err := tx.Exec(Migrations[i]); err != nil {
			tx.Rollback()
			return err
		}

		if _, err = tx.Exec(`UPDATE migrations SET version=$1;`, i+1); err != nil {
			tx.Rollback()
			return err
		}
	}

	return tx.Commit()
}

repository: benkonrath/dataset-dashboard

repo_name: benkonrath/dataset-dashboard


text:
if(TARGET_PLATFORM MATCHES "^host-linux-.*")
  set(IS_CROSS_BUILD True)
  if(TARGET_PLATFORM STREQUAL host-linux-arm64)
    set(CMAKE_SYSTEM_PROCESSOR aarch64)
    set(TRIPLE "aarch64-linux-gnu" CACHE STRING "" FORCE)
  elseif(TARGET_PLATFORM STREQUAL host-linux-arm)
    set(CMAKE_SYSTEM_PROCESSOR armv7l)
    set(TRIPLE "arm-linux-gnueabihf" CACHE STRING "" FORCE)
  else()
    set(IS_CROSS_BUILD False)
    set(TRIPLE "" CACHE STRING "" FORCE)
    set(TOOLCHAIN_PREFIX "" CACHE STRING "" FORCE)
  endif()

  if(IS_CROSS_BUILD)
    set(CMAKE_SYSTEM_NAME Linux)
    set(CMAKE_CROSSCOMPILING True)

    set(TOOLCHAIN_PREFIX "${TRIPLE}-" CACHE STRING "" FORCE)

    set(CMAKE_C_COMPILER ${TRIPLE}-gcc)
    set(CMAKE_CXX_COMPILER ${TRIPLE}-g++)

    set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
    set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
    set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
  endif()
endif()