text:
// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// 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 cli

import (
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"

	"github.com/spf13/cobra"
	"github.com/toqueteos/webbrowser"
)

var (
	// portCmd represents the port command
	portCmd = &cobra.Command{
		Use:   "port",
		Short: "A brief description of your command",
		Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
		//		Run: func(cmd *cobra.Command, args []string) {
		//			// TODO: Work your own magic here
		//			fmt.Println("port called")
		//		},
		RunE: openPorts,
	}
)

func init() {
	RootCmd.AddCommand(portCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// portCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// portCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")

}

func openPorts(cmd *cobra.Command, args []string) error {
	// TODO: Work your own magic here
	//	fmt.Println("port called")
	if len(args) == 0 {
		return errors.New("missing port argument list")
	}

	portMappings_l := make([]string, 0, len(args)+2)
	for _, port_s := range args {
		srv := httptest.NewServer(http.HandlerFunc( //--"/",
			func(w http.ResponseWriter, r *http.Request) {
				fmt.Fprintf(os.Stderr, "%+v\n", *r)
				http.Error(w, "temp server", http.StatusNotImplemented)
			}))
		srvUrlLen := len(srv.URL)
		colonIdx := strings.LastIndex(srv.URL, ":")
		localPort_s := srv.URL[colonIdx+1 : srvUrlLen]
		portMappings_l = append(portMappings_l, localPort_s+":"+port_s)
		webbrowser.Open(srv.URL)
	}
	fmt.Printf("-p %s\n", strings.Join(portMappings_l, " -p "))
	return nil
}

repository: ContiGuy/conti-build

repo_name: ContiGuy/conti-build


text:
# the name of the target operating system
set(CMAKE_SYSTEM_NAME Linux)

# which architecure to compile for
set(MULTIARCH_TUPLE arm-linux-gnueabihf)

# which system root to use
set(CMAKE_PREFIX_PATH ${CMAKE_SOURCE_DIR}/usr/${MULTIARCH_TUPLE})

# which C and C++ compiler to use
set(CMAKE_C_COMPILER  /usr/bin/${MULTIARCH_TUPLE}-gcc)
set(CMAKE_CXX_COMPILER /usr/bin/${MULTIARCH_TUPLE}-g++)

# where the target environment is located
set(CMAKE_FIND_ROOT_PATH /usr/${MULTIARCH_TUPLE})

# search for programs in the build host directories
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)

# search for libraries and headers in the target directories
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH)
set(CMAKE_LIBRARY_PATH
        /usr/lib/${MULTIARCH_TUPLE}
        /usr/lib
)

license: Unlicense

license_type: permissive

branch_name: refs/heads/master

extension: cmake


text:
// Package cmd provides the command line functions of the crunchy CLI
package cmd

/*
 Copyright 2018 - 2020 Crunchy Data Solutions, Inc.
 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.
*/

import (
	"fmt"
	"os"

	"github.com/crunchydata/postgres-operator/pgo/api"
	"github.com/crunchydata/postgres-operator/pgo/util"
	msgs "github.com/crunchydata/postgres-operator/pkg/apiservermsgs"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

var failoverCmd = &cobra.Command{
	Use:   "failover",
	Short: "Performs a manual failover",
	Long: `Performs a manual failover. For example:

	pgo failover mycluster`,
	Run: func(cmd *cobra.Command, args []string) {
		if Namespace == "" {
			Namespace = PGONamespace
		}
		log.Debug("failover called")
		if len(args) == 0 {
			fmt.Println(`Error: You must specify the cluster to failover.`)
		} else {
			if Query {
				queryFailover(args, Namespace)
			} else if util.AskForConfirmation(NoPrompt, "") {
				if Target == "" {
					fmt.Println(`Error: The --target flag is required for failover.`)
					return
				}
				createFailover(args, Namespace)
			} else {
				fmt.Println("Aborting...")
			}
		}

	},
}

func init() {
	RootCmd.AddCommand(failoverCmd)

	failoverCmd.Flags().BoolVarP(&Query, "query", "", false, "Prints the list of failover candidates.")
	failoverCmd.Flags().BoolVar(&NoPrompt, "no-prompt", false, "No command line confirmation.")
	failoverCmd.Flags().StringVarP(&Target, "target", "", "", "The replica target which the failover will occur on.")

}

// createFailover ....
func createFailover(args []string, ns string) {
	log.Debugf("createFailover called %v", args)

	request := new(msgs.CreateFailoverRequest)
	request.Namespace = ns
	request.ClusterName = args[0]
	request.Target = Target
	request.ClientVersion = msgs.PGO_VERSION

	response, err := api.CreateFailover(httpclient, &SessionCredentials, request)

	if err != nil {
		fmt.Println("Error: " + err.Error())
		os.Exit(2)
	}

	if response.Status.Code == msgs.Ok {
		for k := range response.Results {
			fmt.Println(response.Results[k])
		}
	} else {
		fmt.Println("Error: " + response.Status.Msg)
		os.Exit(2)
	}

}

// queryFailover is a helper function to return the user information about the
// replicas that can be failed over to for this cluster. This is called when the
// "--query" flag is specified
func queryFailover(args []string, ns string) {
	log.Debugf("queryFailover called %v", args)

	// call the API
	response, err := api.QueryFailover(httpclient, args[0], &SessionCredentials, ns)
	if err != nil {
		fmt.Println("Error: " + err.Error())
		os.Exit(2)
	}

	// indicate which cluster this is. Put a newline before to put some
	// separation between each line
	if !response.Standby {
		fmt.Printf("\nCluster: %s\n", args[0])
	} else {
		fmt.Printf("\nCluster (standby): %s\n", args[0])
	}

	// If there is a controlled error, output the message here and continue
	// to iterate through the list
	if response.Status.Code != msgs.Ok {
		fmt.Println("Error: " + response.Status.Msg)
		os.Exit(1)
	}

	// If there are no replicas found for this cluster, indicate so, and
	// continue to iterate through the list
	if len(response.Results) == 0 {
		fmt.Println("No replicas found.")
		return
	}

	// output the information about each instance
	fmt.Printf("%-20s\t%-10s\t%-10s\t%-20s\t%s\n", "REPLICA", "STATUS", "NODE", "REPLICATION LAG",
		"PENDING RESTART")

	for i := 0; i < len(response.Results); i++ {
		instance := response.Results[i]

		log.Debugf("postgresql instance: %v", instance)

		fmt.Printf("%-20s\t%-10s\t%-10s\t%12d %-7s\t%15t\n",
			instance.Name, instance.Status, instance.Node, instance.ReplicationLag, "MB",
			instance.PendingRestart)
	}
}

extension: go


text:
// Copyright 2016 Brent Rowland.
// Use of this source code is governed the Apache License, Version 2.0, as described in the LICENSE file.

package ltml

type Align int

const (
	AlignDefault = Align(iota)
	AlignLeft
	AlignRight
	AlignTop
	AlignBottom
)

var alignStrings = []string{"default", "left", "right", "top", "bottom"}

func (a Align) String() string {
	if int(a) < len(alignStrings) {
		return alignStrings[a]
	}
	return "unknown"
}

type HAlign int

const (
	HAlignLeft = HAlign(iota)
	HAlignCenter
	HAlignRight
	HAlignJustify
)

var hAlignStrings = []string{"left", "center", "right", "justify"}

func (ha HAlign) String() string {
	if int(ha) < len(hAlignStrings) {
		return hAlignStrings[ha]
	}
	return "unknown"
}

type VAlign int

const (
	VAlignTop = VAlign(iota)
	VAlignMiddle
	VAlignBottom
	VAlignBaseline
)

var vAlignStrings = []string{"top", "middle", "bottom", "baseline"}

func (va VAlign) String() string {
	if int(va) < len(vAlignStrings) {
		return vAlignStrings[va]
	}
	return "unknown"
}

repository: WHUTzju/leadtype

repo_name: WHUTzju/leadtype


text:
package api

import (
	"net/http"

	"github.com/journeymidnight/yig/helper"
	"github.com/journeymidnight/yig/meta/types"
	"github.com/journeymidnight/yig/signature"
)

const RequestContextKey = "RequestContext"

type RequestContext struct {
	RequestId      string
	BucketName     string
	ObjectName     string
	BucketInfo     *types.Bucket
	ObjectInfo     *types.Object
	AuthType       signature.AuthType
	IsBucketDomain bool
}

type Server struct {
	Server *http.Server
}

func (s *Server) Stop() {
	helper.Logger.Print(5, "Stopping API server...")
	helper.Logger.Println(5, "done")
}


text:
@inproceedings{Araujo:2016:EFA:2976796.2976868,
 author = {Araujo, Matheus Lima Diniz and Nascimento, Iuro and Rafael, Gustavo Caetano and de Melo-Minardi, Raquel and Benevenuto, Fabr\'{\i}cio},
 title = {Emotional Fingerprint from Authors in Classical Literature},
 booktitle = {Proceedings of the 22Nd Brazilian Symposium on Multimedia and the Web},
 series = {Webmedia '16},
 year = {2016},
 isbn = {978-1-4503-4512-5},
 location = {Teresina, Piau\&\#237; State, Brazil},
 pages = {263--270},
 numpages = {8},
 url = {http://doi.acm.org/10.1145/2976796.2976868},
 doi = {10.1145/2976796.2976868},
 acmid = {2976868},
 publisher = {ACM},
 address = {New York, NY, USA},
 keywords = {authorship identification, emotional analysis, recommendation systems, sentiment analysis},
}

license: MIT

repository: iurobpn/academic-kickstart

repo_name: iurobpn/academic-kickstart

extension: bib


text:
package gowrex

import (
	"bytes"
	"encoding/json"
	"io"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

// create body writer POST
func reqForm(r Request, params map[string]string, method string) (Request, error) {
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	defer writer.Close()
	req, err := http.NewRequest(method, r.URI, body)
	req.Header.Add("Content-Type", writer.FormDataContentType())
	if r.Headers != nil {
		for _, header := range r.Headers {
			req.Header.Add(header.Key, header.Value)
		}
	}
	if r.BasicAuth.Username != "" {
		r.Req.SetBasicAuth(r.BasicAuth.Username, r.BasicAuth.Password)
	}
	r.Req = req
	return r, err
}

func reqFormFileDisk(r Request, params map[string]string, paramName string, filePath string, method string) (Request, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return r, err
	}
	defer file.Close()
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(paramName, filepath.Base(filePath))
	if err != nil {
		return r, err
	}
	_, err = io.Copy(part, file)
	if err != nil {
		return r, err
	}
	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	err = writer.Close()
	if err != nil {
		return r, err
	}
	req, err := http.NewRequest(method, r.URI, body)
	req.Header.Add("Content-Type", writer.FormDataContentType())
	if r.Headers != nil {
		for _, header := range r.Headers {
			req.Header.Add(header.Key, header.Value)
		}
	}
	if r.BasicAuth.Username != "" {
		r.Req.SetBasicAuth(r.BasicAuth.Username, r.BasicAuth.Password)
	}
	r.Req = req
	return r, err
}

func reqFormFile(r Request, params map[string]string, paramName string, fileName string, fileBuffer *bytes.Buffer, method string) (Request, error) {
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(paramName, fileName)
	if err != nil {
		return r, err
	}
	_, err = io.Copy(part, fileBuffer)
	if err != nil {
		return r, err
	}
	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	err = writer.Close()
	if err != nil {
		return r, err
	}
	req, err := http.NewRequest(method, r.URI, body)
	req.Header.Add("Content-Type", writer.FormDataContentType())
	if r.Headers != nil {
		for _, header := range r.Headers {
			req.Header.Add(header.Key, header.Value)
		}
	}
	if r.BasicAuth.Username != "" {
		r.Req.SetBasicAuth(r.BasicAuth.Username, r.BasicAuth.Password)
	}
	r.Req = req
	return r, err
}

func reqJSON(r Request, body interface{}, method string) (Request, error) {
	var req *http.Request
	var err error
	if body == nil {
		req, err = http.NewRequest(method, r.URI, nil)
	} else {
		marshalled, err := json.Marshal(body)
		if err != nil {
			return r, err
		}
		jsonBuffer := bytes.NewBuffer(marshalled)
		req, err = http.NewRequest(method, r.URI, jsonBuffer)
	}
	req.Header.Add("Content-Type", "application/json")
	if r.Headers != nil {
		for _, header := range r.Headers {
			req.Header.Add(header.Key, header.Value)
		}
	}
	if r.BasicAuth.Username != "" {
		r.Req.SetBasicAuth(r.BasicAuth.Username, r.BasicAuth.Password)
	}
	r.Req = req
	return r, err
}

func get(r Request) (Request, error) {
	req, err := http.NewRequest("GET", r.URI, nil)
	r.Req = req
	return r, err
}

// Header - a header object
type Header struct {
	Key   string
	Value string
}

// BasicAuth - a basic auth object
type BasicAuth struct {
	Username string
	Password string
}

// Request - the request object
type Request struct {
	URI       string
	Req       *http.Request
	Timeout   time.Duration
	Headers   []Header
	BasicAuth BasicAuth
}

// Response - the response object
type Response struct {
	Res *http.Response
	URI string
}

// PostForm - POST request for a multipart form data
func (r Request) PostForm(params map[string]string) (Request, error) {
	return reqForm(r, params, "POST")
}

// PutForm - PUT request for a multipart form data
func (r Request) PutForm(params map[string]string) (Request, error) {
	return reqForm(r, params, "PUT")
}

// PostFormFileDisk - POST request for a multipart upload with file path with optional params
func (r Request) PostFormFileDisk(params map[string]string, paramName string, filePath string) (Request, error) {
	return reqFormFileDisk(r, params, paramName, filePath, "POST")
}

// PutFormFileDisk - PUT request for a multipart upload with file path with optional params
func (r Request) PutFormFileDisk(params map[string]string, paramName string, filePath string) (Request, error) {
	return reqFormFileDisk(r, params, paramName, filePath, "PUT")
}

// PostFormFile - POST request for a multipart upload with file buffer with optional params
func (r Request) PostFormFile(params map[string]string, paramName string, fileName string, fileBuffer *bytes.Buffer) (Request, error) {
	return reqFormFile(r, params, paramName, fileName, fileBuffer, "POST")
}

// PutFormFile - PUT request for a multipart upload with file buffer with optional params
func (r Request) PutFormFile(params map[string]string, paramName string, fileName string, fileBuffer *bytes.Buffer) (Request, error) {
	return reqFormFile(r, params, paramName, fileName, fileBuffer, "PUT")
}

// PostJSON - POST request to a JSON endpoint
func (r Request) PostJSON(body interface{}) (Request, error) {
	return reqJSON(r, body, "POST")
}

// PutJSON - PUT request to a JSON endpoint
func (r Request) PutJSON(body interface{}) (Request, error) {
	return reqJSON(r, body, "PUT")
}

// GetJSON - GET request to a JSON endpoint
func (r Request) GetJSON() (Request, error) {
	return reqJSON(r, nil, "GET")
}

// Get - GET request to any endpoint
func (r Request) Get() (Request, error) {
	return get(r)
}

// Do - process the request with timeout
func (r Request) Do() (Response, error) {
	client := &http.Client{}
	client.Timeout = r.Timeout
	res, err := client.Do(r.Req)
	return Response{res, r.URI}, err
}

// AddHeader - add a header on the request
func (r Request) AddHeader(key string, value string) Request {
	r.Headers = append(r.Headers, Header{Key: key, Value: value})
	return r
}

// AddBasicAuth - add basic auth on the request
func (r Request) AddBasicAuth(username string, password string) Request {
	r.BasicAuth.Password = password
	r.BasicAuth.Username = username
	return r
}

// JSON - decode JSON to interface
func (e Response) JSON(decoder interface{}) (*interface{}, error) {
	defer e.Res.Body.Close()
	resp := &decoder
	err := json.NewDecoder(e.Res.Body).Decode(resp)
	return resp, err
}

repository: alexesDev/gowrex

repo_name: alexesDev/gowrex


text:
package keyscan

import (
	log "github.com/sirupsen/logrus"
)

// Go runs the whole scan based on params.
func (ctx *ScanContext) Go() {
	ctx.GatherKeysToScanFromGlobs(ctx.Params.TargetGlobs)
	ctx.GatherForbiddenKeysFromFiles(ctx.Params.PermittedKeyFiles)
	ctx.GatherPermittedKeysFromFiles(ctx.Params.ForbiddenKeyFiles)
	ctx.ScanKeysForProblems()
	ctx.PrintProblemReport()
}

// ScanParams contains all the lists of things we need to check for while scanning for duplicate public keys.
type ScanParams struct {
	TargetGlobs       []string // List of files to parse and scan keys from.
	PermittedKeyFiles []string // List of files containing keys that are explicitly allowed to be owned by multiple users.
	ForbiddenKeyFiles []string // List of files containing keys that cannot be used by any user.
	IgnoredOwners     []string // Users whose keys are ignored in scans.
	LowerUIDBound     int      // Ignore system users, with UIDs below this. (e.g. root, nobody, cups)
	// IgnoredGroups []string // TODO Later?
}

// ScanContext is a container for all the data about a scan for keys.
type ScanContext struct {
	Params        ScanParams    // Configuration options.
	FoundKeys     []OwnedPubKey // All the keys that have been found from files and will be checked.
	PermittedKeys []OwnedPubKey // Keys that are explicitly allowed to be owned by multiple users.
	ForbiddenKeys []OwnedPubKey // Keys that are cannot be used by any user.
	Problems      ProblemSet    // Any problems found during the scan.
}

type PKProblemType uint

const (
	NoProblem PKProblemType = iota //
	KeyForbidden
	DuplicateKey
	// KeyTypeDeprecated // TODO Later?
)

// GetProblemTypeText gets a textual description from numeric problem class ID.
func GetProblemTypeText(pt PKProblemType) string {
	problemTypeTexts := []string{"No Problem", "Forbidden Key", "Duplicate Key"}
	return problemTypeTexts[uint(pt)]
}

// ProblemSet is contained by ScanContext to classify the problems we find.
type ProblemSet struct {
	ForbiddenKeys []PubKeyProblem
	DuplicateKeys []PubKeyProblem
}

// PubKeyProblem contains one problem found during a scan, along with the keys that were problematic.
type PubKeyProblem struct {
	ProblemType PKProblemType
	ProblemKey  OwnedPubKey
	RelatedKeys []OwnedPubKey
}

func appendEachKey(a []OwnedPubKey, b []OwnedPubKey) []OwnedPubKey {
	for _, k := range b {
		a = append(a, k)
	}
	return a
}

func (ctx *ScanContext) GatherKeysToScanFromGlobs(globs []string) {
	filenames, err := GetPathsByGlob(ctx.Params.TargetGlobs)
	if err != nil {
		log.Error(err)
	}
	ctx.GatherKeysToScanFromFiles(filenames)
}

func (ctx *ScanContext) GatherKeysToScanFromFiles(filenames []string) {
	opks := GatherKeysFromFiles(filenames)
	ctx.FoundKeys = appendEachKey(ctx.FoundKeys, opks)
}

func (ctx *ScanContext) GatherForbiddenKeysFromFiles(filenames []string) {
	opks := GatherKeysFromFiles(filenames)
	ctx.ForbiddenKeys = appendEachKey(ctx.ForbiddenKeys, opks)
}

func (ctx *ScanContext) GatherPermittedKeysFromFiles(filenames []string) {
	opks := GatherKeysFromFiles(filenames)
	ctx.PermittedKeys = appendEachKey(ctx.PermittedKeys, opks)
}

// GatherKeysFromFiles takes a slice of filenames and returns all the public keys it finds in them with metadata attached.
func GatherKeysFromFiles(filenames []string) []OwnedPubKey {
	opks := make([]OwnedPubKey, 0)
	for _, name := range filenames {
		numKeys := 0
		log.WithFields(log.Fields{"file": name}).Debug("Getting keys from new file")
		keys, err := GetOwnedPubKeysFromFile(name)
		if err != nil {
			log.Error(err)
		}
		numKeys += len(keys)
		for _, key := range keys {
			log.WithFields(log.Fields{"owner": key.Owner, "source": key.SourceFile}).Debug("Adding found key")
			opks = append(opks, key)
		}
		log.WithFields(log.Fields{"new_keys": numKeys, "file": name}).Debug("Key gathering from file complete")
	}
	return opks
}

// ScanKeysForProblems scans all a context's found keys for problems, and return true if any were found, false otherwise.
func (ctx *ScanContext) ScanKeysForProblems() bool {
	log.Debug("Context starting scan for problems")
	anyProblems := false
	for _, v := range ctx.FoundKeys {
		log.WithFields(log.Fields{"owner": v.Owner, "source": v.SourceFile}).Debug("Checking key")
		isProblem, keyProblem := ctx.IsKeyAProblem(v)
		if isProblem {
			anyProblems = true
			log.WithFields(log.Fields{"class": keyProblem.ProblemType}).Debug("Problem detected")
			if keyProblem.ProblemType == KeyForbidden {
				ctx.Problems.ForbiddenKeys = append(ctx.Problems.ForbiddenKeys, keyProblem)
			}
			if keyProblem.ProblemType == DuplicateKey {
				ctx.Problems.DuplicateKeys = append(ctx.Problems.DuplicateKeys, keyProblem)
			}
		}
	}
	log.WithFields(log.Fields{"duplicate_keys": len(ctx.Problems.DuplicateKeys), "forbidden_keys": len(ctx.Problems.ForbiddenKeys)}).Info("Problem scan complete")
	return anyProblems
}

func (ctx *ScanContext) IsKeyAProblem(k OwnedPubKey) (bool, PubKeyProblem) {
	if ctx.IsKeyPermitted(k) {
		return false, PubKeyProblem{}
	}
	if ctx.ShouldIgnoreOwner(k.Owner) {
		return false, PubKeyProblem{}
	}
	if ctx.IsKeyForbidden(k) {
		forbidding := ctx.FindKeysForbidding(k)
		p := PubKeyProblem{ProblemType: KeyForbidden, ProblemKey: k, RelatedKeys: forbidding}
		return true, p
	}
	if dups := ctx.GetDuplicatesOf(k); len(dups) != 0 {
		p := PubKeyProblem{ProblemType: DuplicateKey, ProblemKey: k, RelatedKeys: append(dups, k)}
		return true, p
	}
	return false, PubKeyProblem{}
}

// IsKeyPermitted returns whether the public key in k is one allowed to be anywhere.
func (ctx *ScanContext) IsKeyPermitted(k OwnedPubKey) bool {
	return IsKeyInSlice(k, ctx.PermittedKeys)
}

// IsKeyForbidden returns whether the public key in k is one forbidden from use by anyone.
func (ctx *ScanContext) IsKeyForbidden(k OwnedPubKey) bool {
	return IsKeyInSlice(k, ctx.ForbiddenKeys)
}

// FindKeysForbidding returns the actual entries in forbiddenkeys that will cause a key to be marked as forbidden.
// There's almost certainly some further abstraction that would remove redundancy around this file but I'm real tired.
func (ctx *ScanContext) FindKeysForbidding(k OwnedPubKey) []OwnedPubKey {
	results := make([]OwnedPubKey, 0)
	for _, opk := range ctx.ForbiddenKeys {
		if k.HasSameKeyAs(opk) {
			results = append(results, opk)
		}
	}
	return results
}

// GetDuplicatesOf finds and returns duplicates of an OwnedPubKey k in the ScanContext's FoundKeys.
func (ctx *ScanContext) GetDuplicatesOf(k OwnedPubKey) []OwnedPubKey {
	results := make([]OwnedPubKey, 0)
	for _, opk := range ctx.FoundKeys {
		if k.HasSameKeyAs(opk) {
			// Skip any opk that comes from the same source.
			if k.SourceFile != opk.SourceFile {
				results = append(results, opk)
			}
		}
	}
	return results
}

// ShouldIgnoreOwner returns true if the ScanContext's Params are set to ignore the user passed.
func (ctx *ScanContext) ShouldIgnoreOwner(s string) bool {
	return ctx.Params.ShouldIgnoreOwner(s)
}

// ShouldIgnoreOwner returns true if the ScanParams are set to ignore the user passed.
func (sp *ScanParams) ShouldIgnoreOwner(s string) bool {
	if stringInStringSlice(s, sp.IgnoredOwners) {
		return true
	}
	if UIDForUserIsBelow(sp.LowerUIDBound, s) {
		return true
	}
	return false
}

func UIDForUserIsBelow(lb int, username string) bool {
	uid, err := getUIDForUser(username)
	if err != nil {
		log.Error(err)
		return false // There's not much we can do in the case of error, so... return false? HACK
	}
	if uid < lb {
		return true
	}
	return false
}

// Returns true if the exact string is an element in the string slice.
func stringInStringSlice(s string, slice []string) bool {
	for _, v := range slice {
		if v == s {
			return true
		}
	}
	return false
}

repository: UCL-RITS/keyscan

repo_name: UCL-RITS/keyscan

branch_name: refs/heads/main


text:
@online{BrewersFriend,
author = "Unkown",
title = "Beer Styles-Alcohol by Volume Bar Graph",
url =
"https://www.brewersfriend.com/2009/01/04/beer-styles-alcohol-by-volume-bar-graph/"
}

@article{WSJ,
author = "AP Press",
title = "{Growth of New York state craft alcohol industry continues}",
Date = "3-16-2018"
}

path: /Problem Sets/PS11/PS11_Yuhas.bib


text:
package core_test

import (
	"testing"

	"github.com/gizo-network/gizo/core"
	"github.com/stretchr/testify/assert"
)

func TestGenesis(t *testing.T) {
	assert.NotNil(t, core.GenesisBlock())
}

repository: tktaofik/gizo

repo_name: tktaofik/gizo


text:
package main

import (
	"flag"
	"io/ioutil"
	"log"
	"os"
	"os/user"
	"path/filepath"
	"strings"

	yaml "gopkg.in/yaml.v2"
)

var isTest bool

func init() {
	flag.BoolVar(&isTest, "test", false, "output example config file rather than updating official one")
}

func main() {
	usr, err := user.Current()
	if err != nil {
		log.Fatalf("Error getting current user: %v\n", err)
	}
	kbDir := filepath.Join(usr.HomeDir, "/.kube")
	dwnDir := filepath.Join(usr.HomeDir, "/Downloads")

	configFile, err := ioutil.ReadFile(filepath.Join(kbDir, "/config"))
	if err != nil {
		log.Fatalf("Error reading config file: %v\n", err)
	}

	config := &Config{}
	err = yaml.Unmarshal(configFile, config)
	if err != nil {
		log.Fatalf("Failed to unmarshal main config file: %v\n", err)
	}

	downloads, err := ioutil.ReadDir(dwnDir)
	if err != nil {
		log.Fatalf("Failed to read downloads directory: %v\n", err)
	}
	cfCount := 0

	for _, file := range downloads {
		if strings.Contains(file.Name(), "kube-config") && !file.IsDir() {
			cfCount++
			cfFile, err := ioutil.ReadFile(filepath.Join(dwnDir, file.Name()))
			if err != nil {
				log.Printf("Failed to read config file %s: %v\n", file.Name(), err)
				continue
			}

			cluster := strings.Replace(file.Name(), "kube-config-", "", 1)
			cf := &Config{}
			err = yaml.Unmarshal(cfFile, cf)
			if err != nil {
				log.Fatalf("Failed to unmarshal data from %s: %v\n", file.Name(), err)
			}

			for i, clstr := range config.Users {
				if strings.Contains(clstr.Name, cluster) {
					log.Printf("Updating token for %s\n", cluster)
					config.Users[i].User.AuthProvider.Config.IDToken = cf.Users[0].User.AuthProvider.Config.IDToken
					os.Remove(filepath.Join(dwnDir, file.Name()))
				}
			}
		}
	}

	if cfCount == 0 {
		log.Printf("No config files found in %s\n", dwnDir)
		return
	}

	newConfig, err := yaml.Marshal(&config)
	if err != nil {
		log.Fatalf("Error marshalling new config data: %v\n", err)
	}

	outPath := filepath.Join(kbDir, "/config")

	if isTest {
		outPath = "./test/config"
	}

	err = ioutil.WriteFile(outPath, newConfig, os.FileMode(0777))
	if err != nil {
		log.Fatalf("Error updating config file: %v\n", err)
	}
}

repository: maxgardner/token-up

repo_name: maxgardner/token-up

gha_license_id: MIT

gha_language: Go


text:
/*
Copyright (c) 2020 Red Hat, Inc.

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.
*/

// IMPORTANT: This file has been generated automatically, refrain from modifying it manually as all
// your changes will be lost when the file is generated again.

package v1 // github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1

// SubnetworkBuilder contains the data and logic needed to build 'subnetwork' objects.
//
// AWS subnetwork object to be used while installing a cluster
type SubnetworkBuilder struct {
	bitmap_          uint32
	availabilityZone string
	name             string
	subnetID         string
	public           bool
}

// NewSubnetwork creates a new builder of 'subnetwork' objects.
func NewSubnetwork() *SubnetworkBuilder {
	return &SubnetworkBuilder{}
}

// Empty returns true if the builder is empty, i.e. no attribute has a value.
func (b *SubnetworkBuilder) Empty() bool {
	return b == nil || b.bitmap_ == 0
}

// AvailabilityZone sets the value of the 'availability_zone' attribute to the given value.
func (b *SubnetworkBuilder) AvailabilityZone(value string) *SubnetworkBuilder {
	b.availabilityZone = value
	b.bitmap_ |= 1
	return b
}

// Name sets the value of the 'name' attribute to the given value.
func (b *SubnetworkBuilder) Name(value string) *SubnetworkBuilder {
	b.name = value
	b.bitmap_ |= 2
	return b
}

// Public sets the value of the 'public' attribute to the given value.
func (b *SubnetworkBuilder) Public(value bool) *SubnetworkBuilder {
	b.public = value
	b.bitmap_ |= 4
	return b
}

// SubnetID sets the value of the 'subnet_ID' attribute to the given value.
func (b *SubnetworkBuilder) SubnetID(value string) *SubnetworkBuilder {
	b.subnetID = value
	b.bitmap_ |= 8
	return b
}

// Copy copies the attributes of the given object into this builder, discarding any previous values.
func (b *SubnetworkBuilder) Copy(object *Subnetwork) *SubnetworkBuilder {
	if object == nil {
		return b
	}
	b.bitmap_ = object.bitmap_
	b.availabilityZone = object.availabilityZone
	b.name = object.name
	b.public = object.public
	b.subnetID = object.subnetID
	return b
}

// Build creates a 'subnetwork' object using the configuration stored in the builder.
func (b *SubnetworkBuilder) Build() (object *Subnetwork, err error) {
	object = new(Subnetwork)
	object.bitmap_ = b.bitmap_
	object.availabilityZone = b.availabilityZone
	object.name = b.name
	object.public = b.public
	object.subnetID = b.subnetID
	return
}

repository: openshift-online/ocm-sdk-go

repo_name: openshift-online/ocm-sdk-go


text:
@article{shi2019forward,
  title={Forward-selected panel data approach for program evaluation},
  author={Shi, Zhentao and Huang, Jingyi},
  journal={arXiv preprint arXiv:1908.05894},
  year={2021}
}

@Book{hastie2009bible,
  title     = {The elements of statistical learning: Data mining, inference, and prediction},
  publisher = {Springer-Verlag},
  year      = {2009},
  author    = {Hastie, Trevor and Tibshirani, Robert and Friedman, Jerome},
  pages     = {9--41},
}

@Article{hsiao2012panel,
  Title                    = {A panel data approach for program evaluation: measuring the benefits of political and economic integration of Hong Kong with mainland China},
  Author                   = {Hsiao, Cheng and Steve H Ching and Shui Ki Wan},
  Journal                  = {Journal of Applied Econometrics},
  Year                     = {2012},
  Number                   = {5},
  Pages                    = {705--740},
  Volume                   = {27},
  Publisher                = {Wiley Online Library}
}

repository: zhentaoshi/fsPDA

repo_name: zhentaoshi/fsPDA

gha_language: R


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/iothub_registrymanager_sample.dir/iothub_registrymanager_sample.c.o"
  "CMakeFiles/iothub_registrymanager_sample.dir/linux/main.c.o"
  "iothub_registrymanager_sample.pdb"
  "iothub_registrymanager_sample"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang C)
  INCLUDE(CMakeFiles/iothub_registrymanager_sample.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)

repository: abhishek-tm/xfusion-azure-sdk-python

repo_name: abhishek-tm/xfusion-azure-sdk-python