text:
package orchestrators

import (
	"fmt"
	"io/ioutil"
	"sort"
	"strings"
	"unicode/utf8"

	"golang.org/x/net/context"

	"github.com/camptocamp/conplicity/handler"
	"github.com/camptocamp/conplicity/util"
	"github.com/camptocamp/conplicity/volume"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/api/types/filters"

	log "github.com/Sirupsen/logrus"
)

// DockerOrchestrator implements a container orchestrator for Docker
type DockerOrchestrator struct {
	Handler *handler.Conplicity
}

// GetName returns the orchestrator name
func (*DockerOrchestrator) GetName() string {
	return "Docker"
}

// GetHandler returns the Orchestrator's handler
func (o *DockerOrchestrator) GetHandler() *handler.Conplicity {
	return o.Handler
}

// GetVolumes returns the Docker volumes, inspected and filtered
func (o *DockerOrchestrator) GetVolumes() (volumes []*volume.Volume, err error) {
	c := o.Handler
	vols, err := c.VolumeList(context.Background(), filters.NewArgs())
	if err != nil {
		err = fmt.Errorf("Failed to list Docker volumes: %v", err)
		return
	}
	for _, vol := range vols.Volumes {
		var voll types.Volume
		voll, err = c.VolumeInspect(context.Background(), vol.Name)
		if err != nil {
			err = fmt.Errorf("Failed to inspect volume %s: %v", vol.Name, err)
			return
		}
		v := volume.NewVolume(&voll, c.Config, c.Hostname)
		if b, r, s := o.blacklistedVolume(v); b {
			log.WithFields(log.Fields{
				"volume": vol.Name,
				"reason": r,
				"source": s,
			}).Info("Ignoring volume")
			continue
		}
		volumes = append(volumes, v)
	}
	return
}

// LaunchContainer starts a container using the Docker orchestrator
func (o *DockerOrchestrator) LaunchContainer(image string, env []string, cmd []string, binds []string) (state int, stdout string, err error) {
	err = util.PullImage(o.Handler.Client, image)
	if err != nil {
		err = fmt.Errorf("failed to pull image: %v", err)
		return
	}

	log.WithFields(log.Fields{
		"image":       image,
		"command":     strings.Join(cmd, " "),
		"environment": strings.Join(env, ", "),
		"binds":       strings.Join(binds, ", "),
	}).Debug("Creating container")

	container, err := o.Handler.ContainerCreate(
		context.Background(),
		&container.Config{
			Cmd:          cmd,
			Env:          env,
			Image:        image,
			OpenStdin:    true,
			StdinOnce:    true,
			AttachStdin:  true,
			AttachStdout: true,
			AttachStderr: true,
			Tty:          true,
		},
		&container.HostConfig{
			Binds: binds,
		}, nil, "",
	)
	if err != nil {
		err = fmt.Errorf("failed to create container: %v", err)
		return
	}
	defer util.RemoveContainer(o.Handler.Client, container.ID)

	log.Debugf("Launching with '%v'...", strings.Join(cmd, " "))
	err = o.Handler.ContainerStart(context.Background(), container.ID, types.ContainerStartOptions{})
	if err != nil {
		err = fmt.Errorf("failed to start container: %v", err)
	}

	var exited bool

	for !exited {
		var cont types.ContainerJSON
		cont, err = o.Handler.ContainerInspect(context.Background(), container.ID)
		if err != nil {
			err = fmt.Errorf("failed to inspect container: %v", err)
			return
		}

		if cont.State.Status == "exited" {
			exited = true
			state = cont.State.ExitCode
		}
	}

	body, err := o.Handler.ContainerLogs(context.Background(), container.ID, types.ContainerLogsOptions{
		ShowStdout: true,
		ShowStderr: true,
		Details:    true,
		Follow:     true,
	})
	if err != nil {
		err = fmt.Errorf("failed to retrieve logs: %v", err)
		return
	}

	defer body.Close()
	content, err := ioutil.ReadAll(body)
	if err != nil {
		err = fmt.Errorf("failed to read logs from response: %v", err)
		return
	}

	stdout = string(content)
	log.Debug(stdout)

	return
}

func (o *DockerOrchestrator) blacklistedVolume(vol *volume.Volume) (bool, string, string) {
	if utf8.RuneCountInString(vol.Name) == 64 || vol.Name == "duplicity_cache" || vol.Name == "lost+found" {
		return true, "unnamed", ""
	}

	list := o.Handler.Config.VolumesBlacklist
	i := sort.SearchStrings(list, vol.Name)
	if i < len(list) && list[i] == vol.Name {
		return true, "blacklisted", "blacklist config"
	}

	if vol.Config.Ignore {
		return true, "blacklisted", "volume config"
	}

	return false, "", ""
}

repository: robtimmer/conplicity

repo_name: robtimmer/conplicity


text:
require hal.inc

PR = "${INC_PR}.1"

SRC_URI += " file://hal-right-input-h.patch \
             file://fix-configure.diff \
             file://wifi-2.6.27.diff"

# The following code finds the right linux/input.h,
# which also works with external-toolchain/SDK
do_configure() {
	linux_input_h=`echo "#include <linux/input.h>" | ${CPP} - | \
		grep "linux\/input.h" | head -n 1 | awk -F '"' '{print $2}'`
	autotools_do_configure --with-linux-input-header=${linux_input_h}
}

SRC_URI[md5sum] = "750cf074e88b6fb7012f26d99cd39b9b"
SRC_URI[sha256sum] = "730a9f2340f789677eb0c3b0984bbaca3ede6c12d1e4b16bc7ea91f51d10ba90"

license: MIT

repository: overo/overo-oe-natty

license_type: permissive

repo_name: overo/overo-oe-natty

branch_name: HEAD

extension: bb


text:
package reportportal

import (
	"context"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"reflect"
	"testing"
)

const (
	baseURLPath = "/api/v1"
)

// setup sets up a test HTTP server along with a reportportal.Client that is
// configured to talk to that test server. Tests should register handlers on
// mux which provide mock responses for the API method being tested.
func setup() (client *Client, mux *http.ServeMux, serverURL string, teardown func()) {
	// mux is the HTTP request multiplexer used with the test server.
	mux = http.NewServeMux()

	// We want to ensure that tests catch mistakes where the endpoint URL is
	// specified as absolute rather than relative.
	apiHandler := http.NewServeMux()
	apiHandler.Handle(baseURLPath+"/", http.StripPrefix(baseURLPath, mux))
	apiHandler.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintln(os.Stderr, "FAIL: Client.BaseURL path prefix is not preserved in the request URL:")
		fmt.Fprintln(os.Stderr)
		fmt.Fprintln(os.Stderr, "\t"+req.URL.String())
		fmt.Fprintln(os.Stderr)
		fmt.Fprintln(os.Stderr, "\tDid you accidentally use an absolute endpoint URL rather than relative?")
		http.Error(w, "Client.BaseURL path prefix is not preserved in the request URL.", http.StatusInternalServerError)
	})

	// server is a test HTTP server used to provide mock API responses.
	server := httptest.NewServer(apiHandler)

	// client is the ReportPortal client being tested and is
	// configured to use test server.
	client = NewClient(nil)
	url, _ := url.Parse(server.URL + baseURLPath + "/")
	client.BaseURL = url

	return client, mux, server.URL, server.Close
}

func testMethod(t *testing.T, r *http.Request, want string) {
	t.Helper()
	if got := r.Method; got != want {
		t.Errorf("Request method: %v, want %v", got, want)
	}
}

func TestNewClient(t *testing.T) {
	c := NewClient(nil)

	if got, want := c.BaseURL.String(), BaseURL; got != want {
		t.Errorf("NewClient BaseURL is %v, want %v", got, want)
	}

	c2 := NewClient(nil)
	if c.httpClient == c2.httpClient {
		t.Error("NewClient returned same http.Clients, but they should differ")
	}
}

func TestNewRequest(t *testing.T) {
	type testInput struct {
		Name *string `json:"name"`
	}
	c := NewClient(nil)
	n := "test"
	inURL, outURL := "foo", BaseURL+"foo"
	inBody, outBody := &testInput{Name: &n}, `{"name":"test"}`+"\n"
	req, err := c.NewRequest("GET", inURL, inBody)
	if err != nil {
		t.Errorf("unexpected error when create new requests: %v", err)
	}
	// test that relative URL was expanded
	if got, want := req.URL.String(), outURL; got != want {
		t.Errorf("NewRequest(%q) URL is %v, want %v", inURL, got, want)
	}

	// test that body was JSON encoded
	body, _ := ioutil.ReadAll(req.Body)
	if got, want := string(body), outBody; got != want {
		t.Errorf("NewRequest(%v) Body is %v, want %v", inBody, got, want)
	}
}

func TestDo(t *testing.T) {
	client, mux, _, teardown := setup()
	defer teardown()

	type foo struct {
		A string
	}

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		testMethod(t, r, "GET")
		fmt.Fprint(w, `{"A":"a"}`)
	})

	req, _ := client.NewRequest("GET", ".", nil)
	body := new(foo)
	client.Do(context.Background(), req, body)

	want := &foo{"a"}
	if !reflect.DeepEqual(body, want) {
		t.Errorf("Response body = %v, want %v", body, want)
	}
}

branch_name: refs/heads/master

gha_language: Go

extension: go


text:
@article{Day-2020-Identifying,
    title = "Identifying Functional Impacts of Heat-Resistant Fungi on Boreal Forest Recovery After Wildfire",
    author = "Day, Nicola J.  and
      Cumming, Steven G.  and
      Dunfield, Kari E.  and
      Johnstone, Jill F.  and
      Mack, Michelle C.  and
      Reid, Kirsten A.  and
      Turetsky, Merritt R.  and
      Walker, Xanthe J.  and
      Baltzer, Jennifer L.",
    journal = "Frontiers in Forests and Global Change, Volume 3",
    volume = "3",
    year = "2020",
    publisher = "Frontiers Media SA",
    url = "https://aclanthology.org/G20-66001",
    doi = "10.3389/ffgc.2020.00068",
}
@article{Walker-2020-Patterns,
    title = "Patterns of Ecosystem Structure and Wildfire Carbon Combustion Across Six Ecoregions of the North American Boreal Forest",
    author = "Walker, Xanthe J.  and
      Baltzer, Jennifer L.  and
      Bourgeau-Chavez, Laura  and
      Day, Nicola J.  and
      Dieleman, Catherine M.  and
      Johnstone, Jill F.  and
      Kane, Evan S.  and
      Rogers, Brendan M.  and
      Turetsky, Merritt R.  and
      Veraverbeke, Sander  and
      Mack, Michelle C.",
    journal = "Frontiers in Forests and Global Change, Volume 3",
    volume = "3",
    year = "2020",
    publisher = "Frontiers Media SA",
    url = "https://aclanthology.org/G20-66002",
    doi = "10.3389/ffgc.2020.00087",
}

repository: gwf-uwaterloo/gwf-publications

repo_name: gwf-uwaterloo/gwf-publications

branch_name: refs/heads/main

gha_language: Python

extension: bib


text:
package config_test

import (
	"bytes"
	_ "embed"
	"strings"

	"context"
	"errors"
	"net/http"
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/fastly/cli/pkg/config"
	fsterr "github.com/fastly/cli/pkg/errors"
	"github.com/fastly/cli/pkg/testutil"
	toml "github.com/pelletier/go-toml"
)

type mockHTTPClient struct{}

func (c mockHTTPClient) Do(req *http.Request) (*http.Response, error) {
	return &http.Response{}, context.DeadlineExceeded
}

// TestConfigLoad validates that when a context.DeadlineExceeded error is
// returned from a http.Client.Do request, that an appropriate remediation
// error is returned to the user.
func TestConfigLoad(t *testing.T) {
	var (
		c mockHTTPClient
		d time.Duration
		f *config.File
	)
	if err := f.Load("foo", c, d, "/path/to/config.toml"); err != nil {
		if !errors.As(err, &fsterr.RemediationError{}) {
			t.Errorf("expected RemediationError got: %T", err)
		}
		if err.(fsterr.RemediationError).Remediation != fsterr.NetworkRemediation {
			t.Errorf("expected NetworkRemediation got: %s", err.(fsterr.RemediationError).Remediation)
		}
	} else {
		t.Error("expected an error, got nil")
	}
}

//go:embed testdata/static/config.toml
var staticConfig []byte

//go:embed testdata/static/config-invalid.toml
var staticConfigInvalid []byte

type testReadScenario struct {
	name                 string
	remediation          bool
	staticConfig         []byte
	userConfigFilename   string
	userResponseToPrompt string
	wantError            string
}

// TestConfigRead validates all logic flows within config.File.Read()
func TestConfigRead(t *testing.T) {
	scenarios := []testReadScenario{
		{
			name:         "static config should be used when there is no local user config",
			staticConfig: staticConfig,
		},
		{
			name:         "static config should return an error when invalid",
			staticConfig: staticConfigInvalid,
			wantError:    config.ErrInvalidConfig.Error(),
		},
		{
			name:                 "when user config is invalid (and the user accepts static config) but static config is also invalid, it should return an error",
			staticConfig:         staticConfigInvalid,
			userConfigFilename:   "config-invalid.toml",
			userResponseToPrompt: "yes",
			wantError:            config.ErrInvalidConfig.Error(),
		},
		{
			name:                 "when user config is invalid (and the user rejects static config), it should return a specific remediation error",
			remediation:          true,
			staticConfig:         staticConfig,
			userConfigFilename:   "config-invalid.toml",
			userResponseToPrompt: "no",
			wantError:            config.RemediationManualFix,
		},
		{
			name:                 "when user config is in the legacy format, it should return a specific error",
			staticConfig:         staticConfig,
			userConfigFilename:   "config-legacy.toml",
			userResponseToPrompt: "no",
			wantError:            config.ErrLegacyConfig.Error(),
		},
		{
			name:               "when user config is valid, it should return no error",
			staticConfig:       staticConfig,
			userConfigFilename: "config.toml",
		},
	}

	for _, testcase := range scenarios {
		t.Run(testcase.name, func(t *testing.T) {
			// We're going to chdir to an temp environment,
			// so save the PWD to return to, afterwards.
			pwd, err := os.Getwd()
			if err != nil {
				t.Fatal(err)
			}

			// Create test environment
			opts := testutil.EnvOpts{T: t}
			if testcase.userConfigFilename != "" {
				b, err := os.ReadFile(filepath.Join("testdata", testcase.userConfigFilename))
				if err != nil {
					t.Fatal(err)
				}
				opts.Write = []testutil.FileIO{
					{Src: string(b), Dst: "config.toml"},
				}
			}
			rootdir := testutil.NewEnv(opts)
			configPath := filepath.Join(rootdir, "config.toml")
			defer os.RemoveAll(rootdir)

			// Before running the test, chdir into the temp environment.
			// When we're done, chdir back to our original location.
			// This is so we can reliably assert file structure.
			if err := os.Chdir(rootdir); err != nil {
				t.Fatal(err)
			}
			defer os.Chdir(pwd)

			if testcase.userConfigFilename == "" {
				if fi, err := os.Stat(configPath); err == nil {
					t.Fatalf("expected the user config to NOT exist at this point: %+v", fi)
				}
			} else {
				if _, err := os.Stat(configPath); err != nil {
					t.Fatalf("expected the user config to exist at this point: %v", err)
				}
			}

			var f config.File
			f.SetStatic(testcase.staticConfig)

			var out bytes.Buffer
			in := strings.NewReader(testcase.userResponseToPrompt)

			err = f.Read(configPath, in, &out)

			if testcase.remediation {
				e, ok := err.(fsterr.RemediationError)
				if !ok {
					t.Fatalf("unexpected error asserting returned error (%T) to a RemediationError type", err)
				}
				if testcase.wantError != e.Remediation {
					t.Fatalf("want %v, have %v", testcase.wantError, e.Remediation)
				}
			} else {
				testutil.AssertErrorContains(t, err, testcase.wantError)
			}

			if testcase.wantError == "" {
				// If we're not expecting an error, then we're expecting the user
				// configuration file to exist...

				if _, err := os.Stat(configPath); err == nil {
					bs, err := os.ReadFile(configPath)
					if err != nil {
						t.Fatalf("unexpected err: %v", err)
					}

					err = toml.Unmarshal(bs, &f)
					if err != nil {
						t.Fatalf("unexpected err: %v", err)
					}

					if f.CLI.LastChecked == "" || f.CLI.Version == "" {
						t.Fatalf("expected LastChecked/Version to be set: %+v", f)
					}
				}
			}
		})
	}
}

type testUseStaticScenario struct {
	name               string
	userConfigFilename string
}

// TestUseStatic validates all logic flows within config.File.UseStatic()
func TestUseStatic(t *testing.T) {
	scenarios := []testUseStaticScenario{
		{
			name:               "legacy config should be safe to migrate to static",
			userConfigFilename: "config-legacy.toml",
		},
		// The following scenario is specifically validating that if a recent
		// config (which still had a 'Legacy' section) was identified as needing to
		// be migrated to the static config embedded in the CLI (because the
		// user config's CLI.Version field didn't align with the currently running
		// CLI binary version), then it should still be transitioned safely without
		// losing the user's token/email within the 'User' section.
		{
			name:               "config with 'legacy' section should be safe to migrate to static",
			userConfigFilename: "config-with-old-legacy-section.toml",
		},
	}

	for _, testcase := range scenarios {
		t.Run(testcase.name, func(t *testing.T) {
			// We're going to chdir to an temp environment,
			// so save the PWD to return to, afterwards.
			pwd, err := os.Getwd()
			if err != nil {
				t.Fatal(err)
			}

			// Create test environment
			b, err := os.ReadFile(filepath.Join("testdata", testcase.userConfigFilename))
			if err != nil {
				t.Fatal(err)
			}
			rootdir := testutil.NewEnv(testutil.EnvOpts{
				T: t,
				Write: []testutil.FileIO{
					{Src: string(b), Dst: "config.toml"},
				},
			})
			configPath := filepath.Join(rootdir, "config.toml")
			defer os.RemoveAll(rootdir)

			// Before running the test, chdir into the temp environment.
			// When we're done, chdir back to our original location.
			// This is so we can reliably assert file structure.
			if err := os.Chdir(rootdir); err != nil {
				t.Fatal(err)
			}
			defer os.Chdir(pwd)

			// Validate that invalid static configuration returns a specific error.
			f := config.File{}
			err = f.UseStatic(staticConfigInvalid, configPath)
			if err == nil {
				t.Fatal("expected an error, but got nil")
			} else {
				testutil.AssertErrorContains(t, err, config.ErrInvalidConfig.Error())
			}

			// Validate that legacy configuration can be migrated to the static one
			// embedded in the CLI binary.
			f = config.File{}
			var out bytes.Buffer
			f.Read(configPath, strings.NewReader(""), &out)
			f.UseStatic(staticConfig, configPath)
			if f.CLI.LastChecked == "" || f.CLI.Version == "" {
				t.Fatalf("expected LastChecked/Version to be set: %+v", f)
			}
			if f.User.Token != "foobar" {
				t.Fatalf("wanted token: %s, got: %s", "foobar", f.User.Token)
			}
			if f.User.Email != "testing@fastly.com" {
				t.Fatalf("wanted email: %s, got: %s", "testing@fastly.com", f.User.Email)
			}
		})
	}
}

// TestConfigWrite validates all logic flows within config.File.Write()
//
// Specifically we're interested in whether the f.Static field is written to
// disk (we don't we want it to be) and whether its value is reset (we do want).
func TestConfigWrite(t *testing.T) {
	// We're going to chdir to an temp environment,
	// so save the PWD to return to, afterwards.
	pwd, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}

	// Create test environment
	b, err := os.ReadFile(filepath.Join("testdata", "config.toml"))
	if err != nil {
		t.Fatal(err)
	}
	rootdir := testutil.NewEnv(testutil.EnvOpts{
		T: t,
		Write: []testutil.FileIO{
			{Src: string(b), Dst: "config.toml"},
		},
	})
	configPath := filepath.Join(rootdir, "config.toml")
	defer os.RemoveAll(rootdir)

	// Before running the test, chdir into the temp environment.
	// When we're done, chdir back to our original location.
	// This is so we can reliably assert file structure.
	if err := os.Chdir(rootdir); err != nil {
		t.Fatal(err)
	}
	defer os.Chdir(pwd)

	// Validate the f.Static field is reset and restored.
	var f config.File
	f.SetStatic(staticConfig)
	f.Write(configPath)
	if len(f.Static()) < 1 {
		t.Fatal("expected f.Static to be set")
	}

	// Validate the f.Static isn't written back to disk by reading from disk and
	// unmarshalling the data to check f.Static is now zero length.
	//
	// NOTE: We have to manually reset f.Static because toml.Unmarshal won't
	// reset any fields already with values (f.Static would still have a value
	// set as the field would have been reset at the end of the f.Write, which we
	// validated in the above test assertion).
	//
	// So although we manually reset f.Static, if the local toml file was
	// incorrectly marshalled with a static field, we'd expect the contents to be
	// set back into f.Static when we unmarshal the local toml file. It's that
	// behaviour of f.Write that we want to validate doesn't happen.
	f.SetStatic([]byte(""))
	bs, err := os.ReadFile(configPath)
	if err != nil {
		t.Fatalf("unexpected err: %v", err)
	}
	err = toml.Unmarshal(bs, &f)
	if err != nil {
		t.Fatalf("unexpected err: %v", err)
	}
	if len(f.Static()) > 0 {
		t.Fatalf("expected f.Static to be not set: %+v", f.Static())
	}
}

type testValidConfigScenario struct {
	testutil.TestScenario

	ok            bool
	staticConfig  []byte
	userConfig    string
	verboseOutput bool
}

// TestValidConfig validates all logic flows within config.File.ValidConfig()
func TestValidConfig(t *testing.T) {
	s1 := testValidConfigScenario{}
	s1.Name = "invalid config"
	s1.staticConfig = staticConfig
	s1.userConfig = "config-incompatible-config-version.toml"

	s2 := testValidConfigScenario{}
	s2.Name = "invalid config with verbose output"
	s2.staticConfig = staticConfig
	s2.userConfig = "config-incompatible-config-version.toml"
	s2.verboseOutput = true

	s3 := testValidConfigScenario{}
	s3.Name = "valid config"
	s3.ok = true
	s3.staticConfig = staticConfig
	s3.userConfig = "config.toml"

	scenarios := []testValidConfigScenario{s1, s2, s3}

	for _, testcase := range scenarios {
		t.Run(testcase.Name, func(t *testing.T) {
			// We're going to chdir to an temp environment,
			// so save the PWD to return to, afterwards.
			pwd, err := os.Getwd()
			if err != nil {
				t.Fatal(err)
			}

			// Create test environment
			rootdir := testutil.NewEnv(testutil.EnvOpts{
				T: t,
				Copy: []testutil.FileIO{
					{
						Src: filepath.Join("testdata", testcase.userConfig),
						Dst: filepath.Join("config.toml"),
					},
				},
			})
			configPath := filepath.Join(rootdir, "config.toml")
			defer os.RemoveAll(rootdir)

			// Before running the test, chdir into the temp environment.
			// When we're done, chdir back to our original location.
			// This is so we can reliably assert file structure.
			if err := os.Chdir(rootdir); err != nil {
				t.Fatal(err)
			}
			defer os.Chdir(pwd)

			var f config.File
			f.SetStatic(testcase.staticConfig)

			var stdout bytes.Buffer
			in := strings.NewReader("") // these tests won't trigger a user prompt

			err = f.Read(configPath, in, &stdout)
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}

			ok := f.ValidConfig(testcase.verboseOutput, &stdout)
			if ok != testcase.ok {
				t.Fatalf("want %t, have: %t", testcase.ok, ok)
			}

			output := strings.ReplaceAll(stdout.String(), "\n", " ")
			if !testcase.ok && testcase.verboseOutput {
				testutil.AssertStringContains(t, output, "incompatible with the current CLI version")
			}
		})
	}
}


text:
require libgnomeui.inc

PR = "r1"

SRC_URI[archive.md5sum] = "ceab6f4370581d1a03c09f15cc103099"
SRC_URI[archive.sha256sum] = "04c81f3bb5a337cdf3ed1230916f82d29857ee95eb884f58dd2f5c6860efe803"

branch_name: refs/heads/fido

gha_license_id: MIT

gha_language: BitBake


text:
@book{key,
  title={Gravity: An Introduction to Einstein's General Relativity},
  author={Hartle, J.B.},
  isbn={9780805386622},
  lccn={2002151118},
  url={https://books.google.com/books?id=ZHgpAQAAMAAJ},
  year={2003},
  publisher={Addison-Wesley}
}

repository: bhishanpdl/Programming

repo_name: bhishanpdl/Programming


text:
DESCRIPTION = "a collection of autoconf m4 macros"
HOMEPAGE = "http://cwautomacros.berlios.de/"
LICENSE = "GPLv2+"
PR = "0"

SRC_URI = "http://download.berlios.de/cwautomacros/cwautomacros-${PV}.tar.bz2"
SRC_URI[md5sum] = "352b295897ddb30c0d7d0acdd0b2313a"
SRC_URI[sha256sum] = "8f683713baa63e6b5c2ea72067f77cbacf0bee7d4efa907951c6bb5ac1ffd6b0"

do_compile () {
    :
}

do_install () {
    sed -i -e's,\$(INSTALLPREFIX)/share,${D}${datadir},g' \
           -e's,\$(INSTALLPREFIX),${D},g' \
           Makefile
    make install
    mv ${D}${datadir}/cwautomacros/m4 ${D}${datadir}/aclocal
}

NATIVE_INSTALL_WORKS = "1"
BBCLASSEXTEND += "native nativesdk"


text:
DESCRIPTION = "A sphinx extension which renders display math in HTML via JavaScript"
HOMEPAGE = "http://sphinx-doc.org/"
SECTION = "devel/python"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://LICENSE;md5=f0064c10bd544bcffccbc67a41c108d3"

SRC_URI[md5sum] = "e45179f0a3608b6766862e0f34c23b62"
SRC_URI[sha256sum] = "a9925e4a4587247ed2191a22df5f6970656cb8ca2bd6284309578f2153e0c4b8"

inherit setuptools3 pypi

repository: axilera/meta-cip-sr-common

repo_name: axilera/meta-cip-sr-common


text:
@article{gilbertMicrobiomewideAssociationStudies2016,
 abstract = {Rapid advances in DNA sequencing, metabolomics, proteomics and computational tools are dramatically increasing access to the microbiome and identification of its links with disease. In particular, time-series studies and multiple molecular perspectives are facilitating microbiome-wide association studies, which are analogous to genome-wide association studies. Early findings point to actionable outcomes of microbiome-wide association studies, although their clinical application has yet to be approved. An appreciation of the complexity of interactions among the microbiome and the host's diet, chemistry and health, as well as determining the frequency of observations that are needed to capture and integrate this dynamic interface, is paramount for developing precision diagnostics and therapies that are based on the microbiome.},
 author = {Gilbert, Jack A. and Quinn, Robert A. and Debelius, Justine and Xu, Zhenjiang Z. and Morton, James and Garg, Neha and Jansson, Janet K. and Dorrestein, Pieter C. and Knight, Rob},
 copyright = {© 2016 Nature Publishing Group, a division of Macmillan Publishers Limited. All Rights Reserved.},
 doi = {10.1038/nature18850},
 file = {/Users/zech/Zotero/storage/EPJ9HCWS/2016_Gilbert_et_al_Microbiome-wide_association_studies_link_dynamic_microbial_consortia_to_disease.pdf},
 issn = {0028-0836},
 journal = {Nature},
 langid = {english},
 month = {July},
 number = {7610},
 pages = {94--103},
 title = {Microbiome-Wide Association Studies Link Dynamic Microbial Consortia to Disease},
 urldate = {2016-07-09},
 volume = {535},
 year = {2016}
}

repository: zxlab/lab-web

repo_name: zxlab/lab-web

gha_language: TeX


text:
package pin

import (
	"bytes"
	"encoding/hex"
	"fmt"
	_ "log"
	"strconv"
)

type PinblockIso1 struct {
	PinBlocker
}

func (pinBlock *PinblockIso1) Encrypt(pan string, clearPin string, key []byte) (res []byte, err error) {

	if len(clearPin) > 12 {
		return nil, ErrInvalidPinLength
	}
	buf := bytes.NewBufferString(fmt.Sprintf("1%X%s", len(clearPin), clearPin))
	fillRandom(buf)

	pinBlockData, err := hex.DecodeString(buf.String())
	res, err = EncryptPinBlock(pinBlockData, key)
	return

}

func (pinBlock *PinblockIso1) GetPin(pan string, pinBlockData []byte, key []byte) (res string, err error) {

	clearPinBlock, err := DecryptPinBlock(pinBlockData, key)
	pinBlockStr := hex.EncodeToString(clearPinBlock)

	nPinDigits, _ := strconv.ParseInt(pinBlockStr[1:2], 16, 16)
	res = pinBlockStr[2:(2 + nPinDigits)]

	return

}

repository: eldologuzzo/libiso

repo_name: eldologuzzo/libiso


text:
package subtitles

import (
	"testing"

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

func TestFilterStyle(t *testing.T) {
	in := Subtitle{[]Caption{{
		1,
		makeTime(0, 0, 4, 630),
		makeTime(0, 0, 6, 18),
		[]string{"GO NINJA!", "{\\1c&H6FCCF9&}NINJA GO!"},
	}}}
	expected := Subtitle{[]Caption{{
		1,
		makeTime(0, 0, 4, 630),
		makeTime(0, 0, 6, 18),
		[]string{"GO NINJA!", "NINJA GO!"},
	}}}
	assert.Equal(t, &expected, in.filterStyle())
}

repository: chiflix/subtitles

repo_name: chiflix/subtitles


text:
package entity

import (
	"time"

	"github.com/dgrijalva/jwt-go"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type User struct {
	Student_number string               `json:”student_number”`
	School         string               `json:”school”`
	Email          string               `json:”email”`
	Info_list      []primitive.ObjectID `json:”info_list”`
}

type UserWithId struct {
	Student_number string               `json:”student_number”`
	School         string               `json:”school”`
	Email          string               `json:”email”`
	Info_list      []primitive.ObjectID `json:”info_list”`
	Id             primitive.ObjectID   `json:"id" bson:"_id,omitempty"`
}

type Info struct {
	Course_number string     `json:”course_number”`
	School        string     `json:”school”`
	Field_title   string     `json:”field_title"`
	Field_content string     `json:”field_content”`
	Origin        string     `json:”origin”`
	Time          *time.Time `json:”time”`
}

type Claims struct {
	Student_number string `json:"student_number"`
	School         string `json:"school"`
	Email          string `json:"email"`
	jwt.StandardClaims
}

repository: Chief-Noob/Peony-Backend

repo_name: Chief-Noob/Peony-Backend


text:
// Copyright 2022 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

package types

import (
	"reflect"
	"testing"
)

func fixKustomizationPostUnmarshallingCheck(k, e *Kustomization) bool {
	return k.Kind == e.Kind &&
		k.APIVersion == e.APIVersion &&
		len(k.Resources) == len(e.Resources) &&
		k.Resources[0] == e.Resources[0] &&
		k.Bases == nil
}

func TestKustomization_CheckDeprecatedFields(t *testing.T) {
	tests := []struct {
		name string
		k    Kustomization
		want *[]string
	}{
		{
			name: "using_bases",
			k: Kustomization{
				Bases: []string{"base"},
			},
			want: &[]string{deprecatedBaseWarningMessage},
		},
		{
			name: "using_ImageTags",
			k: Kustomization{
				ImageTags: []Image{},
			},
			want: &[]string{deprecatedImageTagsWarningMessage},
		},
		{
			name: "usingPatchesJson6902",
			k: Kustomization{
				PatchesJson6902: []Patch{},
			},
			want: &[]string{deprecatedPatchesJson6902Message},
		},
		{
			name: "usingPatchesStrategicMerge",
			k: Kustomization{
				PatchesStrategicMerge: []PatchStrategicMerge{},
			},
			want: &[]string{deprecatedPatchesStrategicMergeMessage},
		},
		{
			name: "usingVar",
			k: Kustomization{
				Vars: []Var{},
			},
			want: &[]string{deprecatedVarsMessage},
		},
		{
			name: "usingAll",
			k: Kustomization{
				Bases:                 []string{"base"},
				ImageTags:             []Image{},
				PatchesJson6902:       []Patch{},
				PatchesStrategicMerge: []PatchStrategicMerge{},
				Vars:                  []Var{},
			},
			want: &[]string{
				deprecatedBaseWarningMessage,
				deprecatedImageTagsWarningMessage,
				deprecatedPatchesJson6902Message,
				deprecatedPatchesStrategicMergeMessage,
				deprecatedVarsMessage,
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			k := tt.k
			if got := k.CheckDeprecatedFields(); !reflect.DeepEqual(got, tt.want) {
				t.Errorf("Kustomization.CheckDeprecatedFields() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestFixKustomizationPostUnmarshalling(t *testing.T) {
	var k Kustomization
	k.Bases = append(k.Bases, "foo")
	k.ConfigMapGenerator = []ConfigMapArgs{{GeneratorArgs{
		KvPairSources: KvPairSources{
			EnvSources: []string{"a", "b"},
			EnvSource:  "c",
		},
	}}}
	k.CommonLabels = map[string]string{
		"foo": "bar",
	}
	k.FixKustomization()

	expected := Kustomization{
		TypeMeta: TypeMeta{
			Kind:       KustomizationKind,
			APIVersion: KustomizationVersion,
		},
		Resources: []string{"foo"},
		ConfigMapGenerator: []ConfigMapArgs{{GeneratorArgs{
			KvPairSources: KvPairSources{
				EnvSources: []string{"a", "b", "c"},
			},
		}}},
		CommonLabels: map[string]string{
			"foo": "bar",
		},
	}
	if !reflect.DeepEqual(k, expected) {
		t.Fatalf("unexpected output: %v", k)
	}
	if !fixKustomizationPostUnmarshallingCheck(&k, &expected) {
		t.Fatalf("unexpected output: %v", k)
	}
}

func TestFixKustomizationPostUnmarshalling_2(t *testing.T) {
	k := Kustomization{
		TypeMeta: TypeMeta{
			Kind: ComponentKind,
		},
	}
	k.Bases = append(k.Bases, "foo")
	k.FixKustomization()

	expected := Kustomization{
		TypeMeta: TypeMeta{
			Kind:       ComponentKind,
			APIVersion: ComponentVersion,
		},
		Resources: []string{"foo"},
	}

	if !fixKustomizationPostUnmarshallingCheck(&k, &expected) {
		t.Fatalf("unexpected output: %v", k)
	}
}

func TestEnforceFields_InvalidKindAndVersion(t *testing.T) {
	k := Kustomization{
		TypeMeta: TypeMeta{
			Kind:       "foo",
			APIVersion: "bar",
		},
	}

	errs := k.EnforceFields()
	if len(errs) != 2 {
		t.Fatalf("number of errors should be 2 but got: %v", errs)
	}
}

func TestEnforceFields_InvalidKind(t *testing.T) {
	k := Kustomization{
		TypeMeta: TypeMeta{
			Kind:       "foo",
			APIVersion: KustomizationVersion,
		},
	}

	errs := k.EnforceFields()
	if len(errs) != 1 {
		t.Fatalf("number of errors should be 1 but got: %v", errs)
	}

	expected := "kind should be " + KustomizationKind + " or " + ComponentKind
	if errs[0] != expected {
		t.Fatalf("error should be %v but got: %v", expected, errs[0])
	}
}

func TestEnforceFields_InvalidVersion(t *testing.T) {
	k := Kustomization{
		TypeMeta: TypeMeta{
			Kind:       KustomizationKind,
			APIVersion: "bar",
		},
	}

	errs := k.EnforceFields()
	if len(errs) != 1 {
		t.Fatalf("number of errors should be 1 but got: %v", errs)
	}

	expected := "apiVersion for " + k.Kind + " should be " + KustomizationVersion
	if errs[0] != expected {
		t.Fatalf("error should be %v but got: %v", expected, errs[0])
	}
}

func TestEnforceFields_ComponentKind(t *testing.T) {
	k := Kustomization{
		TypeMeta: TypeMeta{
			Kind:       ComponentKind,
			APIVersion: "bar",
		},
	}

	errs := k.EnforceFields()
	if len(errs) != 1 {
		t.Fatalf("number of errors should be 1 but got: %v", errs)
	}

	expected := "apiVersion for " + k.Kind + " should be " + ComponentVersion
	if errs[0] != expected {
		t.Fatalf("error should be %v but got: %v", expected, errs[0])
	}
}

func TestEnforceFields(t *testing.T) {
	k := Kustomization{
		TypeMeta: TypeMeta{
			Kind:       KustomizationKind,
			APIVersion: KustomizationVersion,
		},
	}

	errs := k.EnforceFields()
	if len(errs) != 0 {
		t.Fatalf("number of errors should be 0 but got: %v", errs)
	}
}

func TestUnmarshal(t *testing.T) {
	y := []byte(`
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
metadata:
  name: kust
  namespace: default
  labels:
    foo: bar
  annotations:
    foo: bar
resources:
- foo
- bar
nameSuffix: dog
namePrefix: cat`)
	var k Kustomization
	err := k.Unmarshal(y)
	if err != nil {
		t.Fatal(err)
	}
	meta := ObjectMeta{
		Name:      "kust",
		Namespace: "default",
		Labels: map[string]string{
			"foo": "bar",
		},
		Annotations: map[string]string{
			"foo": "bar",
		},
	}
	if k.Kind != KustomizationKind || k.APIVersion != KustomizationVersion ||
		len(k.Resources) != 2 || k.NamePrefix != "cat" || k.NameSuffix != "dog" ||
		k.MetaData.Name != meta.Name || k.MetaData.Namespace != meta.Namespace ||
		k.MetaData.Labels["foo"] != meta.Labels["foo"] || k.MetaData.Annotations["foo"] != meta.Annotations["foo"] {
		t.Fatalf("wrong unmarshal result: %v", k)
	}
}

func TestUnmarshal_UnkownField(t *testing.T) {
	y := []byte(`
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
unknown: foo`)
	var k Kustomization
	err := k.Unmarshal(y)
	if err == nil {
		t.Fatalf("expect an error")
	}
	expect := "invalid Kustomization: json: unknown field \"unknown\""
	if err.Error() != expect {
		t.Fatalf("expect %v but got: %v", expect, err.Error())
	}
}

func TestUnmarshal_Failed(t *testing.T) {
	tests := []struct {
		name               string
		kustomizationYamls []byte
		errMsg             string
	}{
		{
			name: "invalid yaml",
			kustomizationYamls: []byte(`apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
unknown`),
			errMsg: "invalid Kustomization: yaml: line 4: could not find expected ':'",
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var k Kustomization
			if err := k.Unmarshal(tt.kustomizationYamls); err == nil || err.Error() != tt.errMsg {
				t.Errorf("Kustomization.Unmarshal() error = %v, wantErr %v", err, tt.errMsg)
			}
		})
	}
}

func TestKustomization_CheckEmpty(t *testing.T) {
	tests := []struct {
		name          string
		kustomization *Kustomization
		wantErr       bool
	}{
		{
			name:          "empty kustomization.yaml",
			kustomization: &Kustomization{},
			wantErr:       true,
		},
		{
			name: "empty kustomization.yaml",
			kustomization: &Kustomization{
				TypeMeta: TypeMeta{
					Kind:       KustomizationKind,
					APIVersion: KustomizationVersion,
				},
			},
			wantErr: true,
		},
		{
			name:          "non empty kustomization.yaml",
			kustomization: &Kustomization{Resources: []string{"res"}},
			wantErr:       false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			k := tt.kustomization
			k.FixKustomization()
			if err := k.CheckEmpty(); (err != nil) != tt.wantErr {
				t.Errorf("Kustomization.CheckEmpty() error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}

repository: kubernetes-sigs/kustomize

repo_name: kubernetes-sigs/kustomize


text:
SUMMARY = "Stand-alone system tray"
DESCRIPTION = "Stalonetray is a stand-alone freedesktop.org and KDE system tray"
SECTION = "x11/graphics"
LICENSE = "GPL-2.0-only"
LIC_FILES_CHKSUM = "file://COPYING;md5=94d55d512a9ba36caa9b7df079bae19f"

DEPENDS = "virtual/libx11"

SRC_URI = "${SOURCEFORGE_MIRROR}/${BPN}/${BPN}-${PV}.tar.bz2"

SRC_URI[md5sum] = "ae95dbbacc2620e032acea8abab8c9ef"
SRC_URI[sha256sum] = "36548a588b2d466913423245dda6ffb6313132cd0cec635a117d37b3dab5fd4c"

inherit autotools features_check

REQUIRED_DISTRO_FEATURES = "x11"

repository: openembedded/meta-openembedded

repo_name: openembedded/meta-openembedded


text:
package main

import (
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"strings"
	"time"

	"github.com/alibaba/pouch/apis/types"
	"github.com/alibaba/pouch/test/command"
	"github.com/alibaba/pouch/test/environment"
	"github.com/alibaba/pouch/test/util"

	"github.com/go-check/check"
	"github.com/gotestyourself/gotestyourself/icmd"
)

// PouchRunSuite is the test suite for run CLI.
type PouchRunSuite struct{}

func init() {
	check.Suite(&PouchRunSuite{})
}

// SetUpSuite does common setup in the beginning of each test suite.
func (suite *PouchRunSuite) SetUpSuite(c *check.C) {
	SkipIfFalse(c, environment.IsLinux)

	environment.PruneAllContainers(apiClient)

	PullImage(c, busyboxImage)
}

// TearDownTest does cleanup work in the end of each test.
func (suite *PouchRunSuite) TearDownTest(c *check.C) {
}

// TestRun is to verify the correctness of run container with specified name.
func (suite *PouchRunSuite) TestRun(c *check.C) {
	name := "test-run"

	command.PouchRun("run", "-d", "--name", name, busyboxImage, "top").Assert(c, icmd.Success)

	res := command.PouchRun("ps").Assert(c, icmd.Success)
	if out := res.Combined(); !strings.Contains(out, name) {
		c.Fatalf("unexpected output %s: should contains container %s\n", out, name)
	}
	DelContainerForceMultyTime(c, name)
}

// TestRunPrintHi is to verify run container with executing a command.
func (suite *PouchRunSuite) TestRunPrintHi(c *check.C) {
	name := "test-run-print-hi"

	res := command.PouchRun("run", "--name", name, busyboxImage, "echo", "hi")
	res.Assert(c, icmd.Success)

	if out := res.Combined(); !strings.Contains(out, "hi") {
		c.Fatalf("unexpected output %s expected hi\n", out)
	}
	DelContainerForceMultyTime(c, name)
}

// TestRunPrintHiByImageID is to verify run container with executing a command by image ID.
func (suite *PouchRunSuite) TestRunPrintHiByImageID(c *check.C) {
	name := "test-run-print-hi-by-image-id"

	res := command.PouchRun("images")
	res.Assert(c, icmd.Success)
	imageID := imagesListToKV(res.Combined())[busyboxImage][0]

	res = command.PouchRun("run", "--name", name, imageID, "echo", "hi")
	res.Assert(c, icmd.Success)

	if out := res.Combined(); !strings.Contains(out, "hi") {
		c.Fatalf("unexpected output %s expected hi\n", out)
	}
	DelContainerForceMultyTime(c, name)
}

// TestRunDeviceMapping is to verify --device param when running a container.
func (suite *PouchRunSuite) TestRunDeviceMapping(c *check.C) {
	if _, err := os.Stat("/dev/zero"); err != nil {
		c.Skip("Host does not have /dev/zero")
	}

	name := "test-run-device-mapping"
	testDev := "/dev/testDev"

	res := command.PouchRun("run", "--name", name, "--device", "/dev/zero:"+testDev, busyboxImage, "ls", testDev)
	res.Assert(c, icmd.Success)

	if out := res.Combined(); !strings.Contains(out, testDev) {
		c.Fatalf("unexpected output %s expected %s\n", out, testDev)
	}
	DelContainerForceMultyTime(c, name)
}

// TestRunDevicePermissions is to verify --device permissions mode when running a container.
func (suite *PouchRunSuite) TestRunDevicePermissions(c *check.C) {
	if _, err := os.Stat("/dev/zero"); err != nil {
		c.Skip("Host does not have /dev/zero")
	}

	name := "test-run-device-permissions"
	testDev := "/dev/testDev"
	permissions := "crw-rw-rw-"

	res := command.PouchRun("run", "--name", name, "--device", "/dev/zero:"+testDev+":rwm", busyboxImage, "ls", "-l", testDev)
	res.Assert(c, icmd.Success)

	if out := res.Combined(); !strings.HasPrefix(out, permissions) {
		c.Fatalf("Output should begin with %s, got %s\n", permissions, out)
	}
	DelContainerForceMultyTime(c, name)
}

// TestRunDeviceInvalidMode is to verify --device wrong mode when running a container.
func (suite *PouchRunSuite) TestRunDeviceInvalidMode(c *check.C) {
	name := "test-run-device-with-wrong-mode"
	wrongMode := "rxm"

	res := command.PouchRun("run", "--name", name, "--device", "/dev/zero:/dev/zero:"+wrongMode, busyboxImage, "ls", "/dev/zero")
	c.Assert(res.Error, check.NotNil)

	expected := "invalid device mode"
	if out := res.Combined(); !strings.Contains(out, expected) {
		c.Fatalf("Output should contain %s unexpected output %s. \n", expected, out)
	}
}

// TestRunDeviceDirectory is to verify --device with a device directory when running a container.
func (suite *PouchRunSuite) TestRunDeviceDirectory(c *check.C) {
	if _, err := os.Stat("/dev/snd"); err != nil {
		c.Skip("Host does not have direcory /dev/snd")
	}

	name := "test-run-with-directory-device"
	srcDev := "/dev/snd"

	res := command.PouchRun("run", "--name", name, "--device", srcDev+":/dev:rwm", busyboxImage, "ls", "-l", "/dev")
	res.Assert(c, icmd.Success)

	// /dev/snd contans two device: timer, seq
	expected := "timer"
	if out := res.Combined(); !strings.Contains(out, expected) {
		c.Fatalf("Output should contain %s, got %s\n", expected, out)
	}
	DelContainerForceMultyTime(c, name)
}

// TestRunWithBadDevice is to verify --device with bad device dir when running a container.
func (suite *PouchRunSuite) TestRunDeviceWithBadDevice(c *check.C) {
	name := "test-run-with-bad-device"

	res := command.PouchRun("run", "--name", name, "--device", "/etc", busyboxImage, "ls", "/etc")
	c.Assert(res.Error, check.NotNil)

	expected := "not a device node"
	if out := res.Combined(); !strings.Contains(out, expected) {
		c.Fatalf("Output should contain %s unexpected output %s. \n", expected, out)
	}
}

// TestRunInWrongWay tries to run create in wrong way.
func (suite *PouchRunSuite) TestRunInWrongWay(c *check.C) {
	for _, tc := range []struct {
		name string
		args string
	}{
		{name: "unknown flag", args: "-a"},

		// TODO: should add the following cases if ready
		// {name: "missing image name", args: ""},
	} {
		res := command.PouchRun("run", tc.args)
		c.Assert(res.Error, check.NotNil, check.Commentf(tc.name))
	}
}

// TestRunEnableLxcfs is to verify run container with lxcfs.
func (suite *PouchRunSuite) TestRunEnableLxcfs(c *check.C) {
	// TODO: also check if the pouchd started with lxcfs option
	SkipIfFalse(c, environment.IsLxcfsEnabled)
	name := "test-run-lxcfs"

	command.PouchRun("run", "-d", "--name", name, "-m", "512M", "--enableLxcfs=true",
		busyboxImage, "sleep", "10000").Assert(c, icmd.Success)

	res := command.PouchRun("exec", name, "head", "-n", "5", "/proc/meminfo")
	res.Assert(c, icmd.Success)

	// the memory should be equal to 512M
	if out := res.Combined(); !strings.Contains(out, "524288 kB") {
		c.Fatalf("upexpected output %v, expected %s\n", res, "524288 kB")
	}
	DelContainerForceMultyTime(c, name)
}

// Comment this flaky test.
// TestRunRestartPolicyAlways is to verify restart policy always works.
//func (suite *PouchRunSuite) TestRunRestartPolicyAlways(c *check.C) {
//	name := "TestRunRestartPolicyAlways"
//
//	command.PouchRun("run", "--name", name, "-d", "--restart=always", busyboxImage, "sh", "-c", "sleep 10000").Assert(c, icmd.Success)
//	command.PouchRun("stop", name).Assert(c, icmd.Success)
//	time.Sleep(5000 * time.Millisecond)
//
//	res := command.PouchRun("ps")
//	res.Assert(c, icmd.Success)
//
//	if out := res.Combined(); !strings.Contains(out, name) {
//		c.Fatalf("expect container %s to be up: %s\n", name, out)
//	}
//	DelContainerForceMultyTime(c,name)
//}

// TestRunRestartPolicyNone is to verify restart policy none works.
func (suite *PouchRunSuite) TestRunRestartPolicyNone(c *check.C) {
	name := "TestRunRestartPolicyNone"

	command.PouchRun("run", "--name", name, "-d", "--restart=no", busyboxImage, "sh", "-c", "sleep 1").Assert(c, icmd.Success)
	time.Sleep(2000 * time.Millisecond)

	res := command.PouchRun("ps")
	res.Assert(c, icmd.Success)

	if out := res.Combined(); strings.Contains(out, name) {
		c.Fatalf("expect container %s to be exited: %s\n", name, out)
	}
	DelContainerForceMultyTime(c, name)
}

// TestRunWithIPCMode is to verify --specific IPC mode when running a container.
// TODO: test container ipc namespace mode.
func (suite *PouchRunSuite) TestRunWithIPCMode(c *check.C) {
	name := "test-run-with-ipc-mode"

	res := command.PouchRun("run", "-d", "--name", name, "--ipc", "host", busyboxImage)
	res.Assert(c, icmd.Success)
	DelContainerForceMultyTime(c, name)
}

// TestRunWithPIDMode is to verify --specific PID mode when running a container.
// TODO: test container pid namespace mode.
func (suite *PouchRunSuite) TestRunWithPIDMode(c *check.C) {
	name := "test-run-with-pid-mode"

	res := command.PouchRun("run", "-d", "--name", name, "--pid", "host", busyboxImage)
	res.Assert(c, icmd.Success)
	DelContainerForceMultyTime(c, name)
}

// TestRunWithUTSMode is to verify --specific UTS mode when running a container.
func (suite *PouchRunSuite) TestRunWithUTSMode(c *check.C) {
	name := "test-run-with-uts-mode"

	res := command.PouchRun("run", "-d", "--name", name, "--uts", "host", busyboxImage)
	res.Assert(c, icmd.Success)
	DelContainerForceMultyTime(c, name)
}

// TestRunWithSysctls is to verify run container with sysctls.
func (suite *PouchRunSuite) TestRunWithSysctls(c *check.C) {
	sysctl := "net.ipv4.ip_forward=1"
	name := "run-sysctl"

	res := command.PouchRun("run", "-d", "--name", name, "--sysctl", sysctl, busyboxImage, "top")
	res.Assert(c, icmd.Success)

	output := command.PouchRun("exec", name, "cat", "/proc/sys/net/ipv4/ip_forward").Stdout()
	if !strings.Contains(output, "1") {
		c.Fatalf("failed to run a container with sysctls: %s", output)
	}
	DelContainerForceMultyTime(c, name)
}

// TestRunWithUser is to verify run container with user.
func (suite *PouchRunSuite) TestRunWithUser(c *check.C) {
	user := "1001"
	name := "run-user"

	res := command.PouchRun("run", "-d", "--name", name, "--user", user, busyboxImage, "top")
	res.Assert(c, icmd.Success)

	output := command.PouchRun("exec", name, "id", "-u").Stdout()
	if !strings.Contains(output, user) {
		c.Fatalf("failed to run a container with user: %s", output)
	}
	DelContainerForceMultyTime(c, name)

	name = "run-user-admin"
	command.PouchRun("run", "-d", "--name", name, busyboxImage, "top").Assert(c, icmd.Success)
	command.PouchRun("exec", name, "adduser", "--disabled-password", "admin").Assert(c, icmd.Success)
	output = command.PouchRun("exec", "-u", "admin", name, "whoami").Stdout()
	if !strings.Contains(output, "admin") {
		c.Errorf("failed to start a container with user: %s", output)
	}
}

// TestRunWithAppArmor is to verify run container with security option AppArmor.
func (suite *PouchRunSuite) TestRunWithAppArmor(c *check.C) {
	appArmor := "apparmor=unconfined"
	name := "run-apparmor"

	res := command.PouchRun("run", "-d", "--name", name, "--security-opt", appArmor, busyboxImage)
	res.Assert(c, icmd.Success)

	// TODO: do the test more strictly with effective AppArmor profile.

	DelContainerForceMultyTime(c, name)
}

// TestRunWithSeccomp is to verify run container with security option seccomp.
func (suite *PouchRunSuite) TestRunWithSeccomp(c *check.C) {
	seccomp := "seccomp=unconfined"
	name := "run-seccomp"

	res := command.PouchRun("run", "-d", "--name", name, "--security-opt", seccomp, busyboxImage)
	res.Assert(c, icmd.Success)

	// TODO: do the test more strictly with effective seccomp profile.

	DelContainerForceMultyTime(c, name)
}

// TestRunWithCapability is to verify run container with capability.
func (suite *PouchRunSuite) TestRunWithCapability(c *check.C) {
	capability := "NET_ADMIN"
	name := "run-capability"

	res := command.PouchRun("run", "--name", name, "--cap-add", capability, busyboxImage, "brctl", "addbr", "foobar")
	res.Assert(c, icmd.Success)
	DelContainerForceMultyTime(c, name)
}

// TestRunWithoutCapability tests running container with --cap-drop
func (suite *PouchRunSuite) TestRunWithoutCapability(c *check.C) {
	capability := "chown"
	name := "run-capability"
	expt := icmd.Expected{
		Err: "Operation not permitted",
	}
	command.PouchRun("run", "--name", name, "--cap-drop", capability, busyboxImage, "chown", "755", "/tmp").Compare(expt)
	DelContainerForceMultyTime(c, name)
}

// TestRunWithPrivilege is to verify run container with privilege.
func (suite *PouchRunSuite) TestRunWithPrivilege(c *check.C) {
	name := "run-privilege"

	res := command.PouchRun("run", "--name", name, "--privileged", busyboxImage, "brctl", "addbr", "foobar")
	res.Assert(c, icmd.Success)
	DelContainerForceMultyTime(c, name)
}

// TestRunWithBlkioWeight is to verify --specific Blkio Weight when running a container.
func (suite *PouchRunSuite) TestRunWithBlkioWeight(c *check.C) {
	name := "test-run-with-blkio-weight"

	res := command.PouchRun("run", "-d", "--name", name, "--blkio-weight", "500", busyboxImage)
	res.Assert(c, icmd.Success)
	DelContainerForceMultyTime(c, name)
}

// TestRunWithLocalVolume is to verify run container with -v volume works.
func (suite *PouchRunSuite) TestRunWithLocalVolume(c *check.C) {
	pc, _, _, _ := runtime.Caller(0)
	tmpname := strings.Split(runtime.FuncForPC(pc).Name(), ".")
	var funcname string
	for i := range tmpname {
		funcname = tmpname[i]
	}

	name := funcname

	command.PouchRun("volume", "create", "--name", funcname).Assert(c, icmd.Success)
	defer func() {
		command.PouchRun("volume", "remove", funcname).Assert(c, icmd.Success)
	}()

	command.PouchRun("run", "--name", name, "-v", funcname+":/tmp", busyboxImage, "touch", "/tmp/test").Assert(c, icmd.Success)
	defer func() {
		DelContainerForceMultyTime(c, name)
	}()

	// check the existence of /var/lib/pouch/volume/function/test
	icmd.RunCommand("stat", DefaultVolumeMountPath+"/"+funcname+"/test").Assert(c, icmd.Success)

}

// checkFileContains checks the content of fname contains expt
func checkFileContains(c *check.C, fname string, expt string) {
	cmdResult := icmd.RunCommand("cat", fname)
	c.Assert(cmdResult.Error, check.IsNil)
	c.Assert(strings.Contains(string(cmdResult.Stdout()), expt), check.Equals, true)
}

// TestRunWithLimitedMemory is to verify the valid running container with -m
func (suite *PouchRunSuite) TestRunWithLimitedMemory(c *check.C) {
	cname := "TestRunWithLimitedMemory"
	command.PouchRun("run", "-d", "-m", "100m", "--name", cname, busyboxImage, "top").Stdout()

	// test if the value is in inspect result
	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}
	c.Assert(result[0].HostConfig.Memory, check.Equals, int64(104857600))

	// test if cgroup has record the real value
	containerID := result[0].ID
	path := fmt.Sprintf("/sys/fs/cgroup/memory/default/%s/memory.limit_in_bytes", containerID)

	checkFileContains(c, path, "104857600")

	// remove the container
	DelContainerForceMultyTime(c, cname)
}

// TestRunWithMemoryswap is to verify the valid running container with --memory-swap
func (suite *PouchRunSuite) TestRunWithMemoryswap(c *check.C) {
	cname := "TestRunWithMemoryswap"
	command.PouchRun("run", "-d", "-m", "100m", "--memory-swap", "200m",
		"--name", cname, busyboxImage, "sleep", "10000").Stdout()

	// test if the value is in inspect result
	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}
	c.Assert(result[0].HostConfig.MemorySwap, check.Equals, int64(209715200))

	// test if cgroup has record the real value
	containerID := result[0].ID
	path := fmt.Sprintf("/sys/fs/cgroup/memory/default/%s/memory.memsw.limit_in_bytes", containerID)
	checkFileContains(c, path, "209715200")

	// remove the container
	DelContainerForceMultyTime(c, cname)
}

// TestRunWithMemoryswappiness is to verify the valid running container with memory-swappiness
func (suite *PouchRunSuite) TestRunWithMemoryswappiness(c *check.C) {
	cname := "TestRunWithMemoryswappiness"
	command.PouchRun("run", "-d", "-m", "100m", "--memory-swappiness", "70",
		"--name", cname, busyboxImage, "sleep", "10000").Stdout()

	// test if the value is in inspect result
	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}
	c.Assert(int64(*result[0].HostConfig.MemorySwappiness), check.Equals, int64(70))

	// test if cgroup has record the real value
	containerID := result[0].ID
	path := fmt.Sprintf("/sys/fs/cgroup/memory/default/%s/memory.swappiness", containerID)
	checkFileContains(c, path, "70")

	DelContainerForceMultyTime(c, cname)
}

// TestRunWithCPULimit tests CPU related flags.
func (suite *PouchRunSuite) TestRunWithCPULimit(c *check.C) {
	cname := "TestRunWithCPULimit"
	command.PouchRun("run", "-d",
		"--cpuset-cpus", "0",
		"--cpuset-mems", "0",
		"--cpu-share", "1000",
		"--cpu-period", "1000",
		"--cpu-quota", "1000",
		"--name", cname,
		busyboxImage,
		"sleep", "10000").Stdout()

	// test if the value is in inspect result
	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}

	// check whether the user setting options are in containers' metadata
	c.Assert(result[0].HostConfig.CpusetMems, check.Equals, "0")
	c.Assert(result[0].HostConfig.CPUShares, check.Equals, int64(1000))
	c.Assert(result[0].HostConfig.CpusetCpus, check.Equals, "0")
	c.Assert(result[0].HostConfig.CPUPeriod, check.Equals, int64(1000))
	c.Assert(result[0].HostConfig.CPUQuota, check.Equals, int64(1000))

	// test if cgroup has record the real value
	containerID := result[0].ID
	{
		path := fmt.Sprintf("/sys/fs/cgroup/cpuset/default/%s/cpuset.cpus", containerID)
		checkFileContains(c, path, "0")
	}
	{
		path := fmt.Sprintf("/sys/fs/cgroup/cpuset/default/%s/cpuset.mems", containerID)
		checkFileContains(c, path, "0")
	}
	{
		path := fmt.Sprintf("/sys/fs/cgroup/cpu/default/%s/cpu.shares", containerID)
		checkFileContains(c, path, "1000")
	}
	{
		path := fmt.Sprintf("/sys/fs/cgroup/cpu/default/%s/cpu.cfs_period_us", containerID)
		checkFileContains(c, path, "1000")
	}
	{
		path := fmt.Sprintf("/sys/fs/cgroup/cpu/default/%s/cpu.cfs_quota_us", containerID)
		checkFileContains(c, path, "1000")
	}

	DelContainerForceMultyTime(c, cname)
}

// TestRunBlockIOWeight tests running container with --blkio-weight flag.
func (suite *PouchRunSuite) TestRunBlockIOWeight(c *check.C) {
	cname := "TestRunBlockIOWeight"
	command.PouchRun("run", "-d", "--blkio-weight", "100",
		"--name", cname, busyboxImage, "sleep", "10000").Stdout()

	// test if the value is in inspect result
	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}

	c.Assert(result[0].HostConfig.BlkioWeight, check.Equals, uint16(100))

	// test if cgroup has record the real value
	containerID := result[0].ID
	{
		path := fmt.Sprintf("/sys/fs/cgroup/blkio/default/%s/blkio.weight", containerID)
		checkFileContains(c, path, "100")
	}
	DelContainerForceMultyTime(c, cname)
}

// TestRunBlockIOWeightDevice tests running container with --blkio-weight-device flag.
func (suite *PouchRunSuite) TestRunBlockIOWeightDevice(c *check.C) {
	cname := "TestRunBlockIOWeightDevice"
	testDisk, found := environment.FindDisk()
	if !found {
		c.Skip("fail to find available disk for blkio test")
	}

	command.PouchRun("run", "-d", "--blkio-weight-device", testDisk+":100",
		"--name", cname, busyboxImage, "sleep", "10000").Stdout()

	// test if the value is in inspect result
	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}

	c.Assert(len(result[0].HostConfig.BlkioWeightDevice), check.Equals, 1)
	c.Assert(result[0].HostConfig.BlkioWeightDevice[0].Path, check.Equals, testDisk)
	c.Assert(result[0].HostConfig.BlkioWeightDevice[0].Weight, check.Equals, uint16(100))

	// test if cgroup has record the real value
	//containerID := result.ID
	//{
	//	path := fmt.Sprintf("/sys/fs/cgroup/blkio/default/%s/blkio.weight_device", containerID)
	//	checkFileContains(c, path, "100")
	//}
	DelContainerForceMultyTime(c, cname)
}

// TestRunDeviceReadBps tests running container with --device-read-bps flag.
func (suite *PouchRunSuite) TestRunDeviceReadBps(c *check.C) {
	cname := "TestRunDeviceReadBps"
	testDisk, found := environment.FindDisk()
	if !found {
		c.Skip("fail to find available disk for blkio test")
	}

	command.PouchRun("run", "-d", "--device-read-bps", testDisk+":1mb",
		"--name", cname, busyboxImage, "sleep", "10000").Stdout()

	// test if the value is in inspect result
	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}

	c.Assert(len(result[0].HostConfig.BlkioDeviceReadBps), check.Equals, 1)
	c.Assert(result[0].HostConfig.BlkioDeviceReadBps[0].Path, check.Equals, testDisk)
	c.Assert(result[0].HostConfig.BlkioDeviceReadBps[0].Rate, check.Equals, uint64(1048576))

	// test if cgroup has record the real value
	containerID := result[0].ID
	{
		path := fmt.Sprintf("/sys/fs/cgroup/blkio/default/%s/blkio.throttle.read_bps_device", containerID)
		checkFileContains(c, path, "1048576")
	}
	DelContainerForceMultyTime(c, cname)
}

// TestRunDeviceWriteBps tests running container with --device-write-bps flag.
func (suite *PouchRunSuite) TestRunDeviceWriteBps(c *check.C) {
	cname := "TestRunDeviceWriteBps"
	testDisk, found := environment.FindDisk()
	if !found {
		c.Skip("fail to find available disk for blkio test")
	}

	command.PouchRun("run", "-d", "--device-write-bps", testDisk+":1mb",
		"--name", cname, busyboxImage, "sleep", "10000").Stdout()

	// test if the value is in inspect result
	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}

	c.Assert(len(result[0].HostConfig.BlkioDeviceWriteBps), check.Equals, 1)
	c.Assert(result[0].HostConfig.BlkioDeviceWriteBps[0].Path, check.Equals, testDisk)
	c.Assert(result[0].HostConfig.BlkioDeviceWriteBps[0].Rate, check.Equals, uint64(1048576))

	// test if cgroup has record the real value
	containerID := result[0].ID
	{
		path := fmt.Sprintf("/sys/fs/cgroup/blkio/default/%s/blkio.throttle.write_bps_device", containerID)
		checkFileContains(c, path, "1048576")
	}
	DelContainerForceMultyTime(c, cname)
}

// TestRunDeviceReadIops tests running container with --device-read-iops flag.
func (suite *PouchRunSuite) TestRunDeviceReadIops(c *check.C) {
	cname := "TestRunDeviceReadIops"
	testDisk, found := environment.FindDisk()
	if !found {
		c.Skip("fail to find available disk for blkio test")
	}

	command.PouchRun("run", "-d", "--device-read-iops", testDisk+":1000",
		"--name", cname, busyboxImage, "sleep", "10000").Stdout()

	// test if the value is in inspect result
	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}

	c.Assert(len(result[0].HostConfig.BlkioDeviceReadIOps), check.Equals, 1)
	c.Assert(result[0].HostConfig.BlkioDeviceReadIOps[0].Path, check.Equals, testDisk)
	c.Assert(result[0].HostConfig.BlkioDeviceReadIOps[0].Rate, check.Equals, uint64(1000))

	// test if cgroup has record the real value
	containerID := result[0].ID
	{
		path := fmt.Sprintf("/sys/fs/cgroup/blkio/default/%s/blkio.throttle.read_iops_device", containerID)
		checkFileContains(c, path, "1000")
	}
	DelContainerForceMultyTime(c, cname)
}

// TestRunDeviceWriteIops tests running container with --device-write-iops flag.
func (suite *PouchRunSuite) TestRunDeviceWriteIops(c *check.C) {
	cname := "TestRunDeviceWriteIops"
	testDisk, found := environment.FindDisk()
	if !found {
		c.Skip("fail to find available disk for blkio test")
	}

	command.PouchRun("run", "-d", "--device-write-iops", testDisk+":1000",
		"--name", cname, busyboxImage, "sleep", "10000").Stdout()

	// test if the value is in inspect result
	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}

	c.Assert(len(result[0].HostConfig.BlkioDeviceWriteIOps), check.Equals, 1)
	c.Assert(result[0].HostConfig.BlkioDeviceWriteIOps[0].Path, check.Equals, testDisk)
	c.Assert(result[0].HostConfig.BlkioDeviceWriteIOps[0].Rate, check.Equals, uint64(1000))

	// test if cgroup has record the real value
	containerID := result[0].ID
	{
		path := fmt.Sprintf("/sys/fs/cgroup/blkio/default/%s/blkio.throttle.write_iops_device", containerID)
		checkFileContains(c, path, "1000")
	}
	DelContainerForceMultyTime(c, cname)
}

//
func (suite *PouchRunSuite) TestRunAlikernelScheLatSwitch(c *check.C) {
	// TODO: as runc has not implemented it, add test later
	SkipIfFalse(c, environment.IsAliKernel)
}

//
func (suite *PouchRunSuite) TestRunAlikernelMemoryWmarkRatio(c *check.C) {
	// TODO: as runc has not implemented it, add test later
	SkipIfFalse(c, environment.IsAliKernel)
}

//
func (suite *PouchRunSuite) TestRunAlikernelMemoryExtra(c *check.C) {
	// TODO: as runc has not implemented it, add test later
	SkipIfFalse(c, environment.IsAliKernel)
}

//
func (suite *PouchRunSuite) TestRunAlikernelMemoryForceEmptyCtl(c *check.C) {
	// TODO: as runc has not implemented it, add test later
	SkipIfFalse(c, environment.IsAliKernel)
}

// TestRunWithHostFileVolume tests binding a host file as a volume into container.
// fixes https://github.com/alibaba/pouch/issues/813
func (suite *PouchRunSuite) TestRunWithHostFileVolume(c *check.C) {
	// first create a file on the host
	filepath := "/tmp/TestRunWithHostFileVolume.md"
	icmd.RunCommand("touch", filepath).Assert(c, icmd.Success)

	cname := "TestRunWithHostFileVolume"
	command.PouchRun("run", "-d", "--name", cname, "-v", fmt.Sprintf("%s:%s", filepath, filepath), busyboxImage).Assert(c, icmd.Success)

	DelContainerForceMultyTime(c, cname)
}

// TestRunWithCgroupParent tests running container with --cgroup-parent.
func (suite *PouchRunSuite) TestRunWithCgroupParent(c *check.C) {
	// cgroup-parent relative path
	testRunWithCgroupParent(c, "pouch", "TestRunWithRelativePathOfCgroupParent")

	// cgroup-parent absolute path
	testRunWithCgroupParent(c, "/pouch/test", "TestRunWithAbsolutePathOfCgroupParent")
}

func testRunWithCgroupParent(c *check.C, cgroupParent, name string) {
	command.PouchRun("run", "-d", "-m", "300M", "--cgroup-parent", cgroupParent, "--name", name, busyboxImage, "top").Assert(c, icmd.Success)

	output := command.PouchRun("inspect", name).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}
	containerID := result[0].ID

	// this code slice may not robust, but for this test case is enough.
	if strings.HasPrefix(cgroupParent, "/") {
		cgroupParent = cgroupParent[1:]
	}

	if cgroupParent == "" {
		cgroupParent = "default"
	}

	file := "/sys/fs/cgroup/memory/" + cgroupParent + "/" + containerID + "/memory.limit_in_bytes"
	if _, err := os.Stat(file); err != nil {
		c.Fatalf("container %s cgroup mountpoint not exists", name)
	}

	out, err := exec.Command("cat", file).Output()
	if err != nil {
		c.Fatalf("execute cat command failed: %v", err)
	}

	if !strings.Contains(string(out), "314572800") {
		c.Fatalf("unexpected output %s expected %s\n", string(out), "314572800")
	}

}

// TestRunInvalidCgroupParent checks that a specially-crafted cgroup parent doesn't cause Docker to crash or start modifying /.
func (suite *PouchRunSuite) TestRunInvalidCgroupParent(c *check.C) {
	testRunInvalidCgroupParent(c, "../../../../../../../../SHOULD_NOT_EXIST", "SHOULD_NOT_EXIST", "cgroup-invalid-test")

	testRunInvalidCgroupParent(c, "/../../../../../../../../SHOULD_NOT_EXIST", "/SHOULD_NOT_EXIST", "cgroup-absolute-invalid-test")
}

func testRunInvalidCgroupParent(c *check.C, cgroupParent, cleanCgroupParent, name string) {
	command.PouchRun("run", "-m", "300M", "--cgroup-parent", cgroupParent, "--name", name, busyboxImage, "cat", "/proc/self/cgroup").Assert(c, icmd.Success)

	// We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue.
	if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) {
		c.Fatalf("SECURITY: --cgroup-parent with ../../ relative paths cause files to be created in the host (this is bad) !!")
	}
}

// TestRunWithDiskQuota tests running container with --disk-quota.
func (suite *PouchRunSuite) TestRunWithDiskQuota(c *check.C) {
	if !environment.IsDiskQuota() {
		c.Skip("Host does not support disk quota")
	}

	ret := command.PouchRun("run", "--disk-quota", "2000m", "--name", "TestRunWithDiskQuota", busyboxImage, "df")
	defer func() {
		command.PouchRun("rm", "-f", "TestRunWithDiskQuota").Assert(c, icmd.Success)
	}()

	ret.Assert(c, icmd.Success)

	out := ret.Combined()

	found := false
	for _, line := range strings.Split(out, "\n") {
		if strings.Contains(line, "/") && strings.Contains(line, "2048000") {
			found = true
			break
		}
	}

	c.Assert(found, check.Equals, true)
}

// TestRunWithAnnotation is to verify the valid running container with annotation, and verify SpecAnnotation filed has been in inspect output.
func (suite *PouchRunSuite) TestRunWithAnnotation(c *check.C) {
	cname := "TestRunWithAnnotation"
	command.PouchRun("run", "-d", "--annotation", "a=b", "--annotation", "foo=bar", "--name", cname, busyboxImage).Assert(c, icmd.Success)

	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}

	// kv in map not in order.
	var annotationSlice []string
	for k, v := range result[0].Config.SpecAnnotation {
		annotationSlice = append(annotationSlice, fmt.Sprintf("%s=%s", k, v))
	}
	annotationStr := strings.Join(annotationSlice, " ")

	c.Assert(util.PartialEqual(annotationStr, "a=b"), check.IsNil)
	c.Assert(util.PartialEqual(annotationStr, "foo=bar"), check.IsNil)
}

// TestRunWithExitCode is to verify the valid running container with exit code != 0.
func (suite *PouchRunSuite) TestRunWithExitCode(c *check.C) {
	cname := "TestRunWithExitCode"
	ret := command.PouchRun("run", "--name", cname, busyboxImage, "sh", "-c", "exit 101")
	// test process exit code $? == 101
	ret.Assert(c, icmd.Expected{ExitCode: 101})

	// test container ExitCode == 101
	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}
	c.Assert(result[0].State.ExitCode, check.Equals, int64(101))
}

// TestRunWithDiskQuotaRegular tests running container with --disk-quota.
func (suite *PouchRunSuite) TestRunWithDiskQuotaRegular(c *check.C) {
	if !environment.IsDiskQuota() {
		c.Skip("Host does not support disk quota")
	}

	volumeName := "diskquota-volume"
	containerName := "diskquota-regular"

	ret := command.PouchRun("volume", "create", "-n", volumeName, "-o", "size=256m", "-o", "mount=/data/volume")
	defer func() {
		command.PouchRun("volume", "rm", volumeName).Assert(c, icmd.Success)
	}()
	ret.Assert(c, icmd.Success)

	ret = command.PouchRun("run",
		"--disk-quota=1024m",
		`--disk-quota=".*=512m"`,
		`--disk-quota="/mnt/mount1=768m"`,
		"-v", "/data/mount1:/mnt/mount1",
		"-v", "/data/mount2:/mnt/mount2",
		"-v", "diskquota-volume:/mnt/mount3",
		"--name", containerName, busyboxImage, "df")
	defer func() {
		command.PouchRun("rm", "-f", containerName).Assert(c, icmd.Success)
	}()
	ret.Assert(c, icmd.Success)

	out := ret.Stdout()

	rootFound := false
	mount1Found := false
	mount2Found := false
	mount3Found := false
	for _, line := range strings.Split(out, "\n") {
		if strings.Contains(line, "/") && strings.Contains(line, "1048576") {
			rootFound = true
			continue
		}

		if strings.Contains(line, "/mnt/mount1") && strings.Contains(line, "786432") {
			mount1Found = true
			continue
		}

		if strings.Contains(line, "/mnt/mount2") && strings.Contains(line, "524288") {
			mount2Found = true
			continue
		}

		if strings.Contains(line, "/mnt/mount3") && strings.Contains(line, "262144") {
			mount3Found = true
			continue
		}
	}

	c.Assert(rootFound, check.Equals, true)
	c.Assert(mount1Found, check.Equals, true)
	c.Assert(mount2Found, check.Equals, true)
	c.Assert(mount3Found, check.Equals, true)
}

// TestRunWithRM is to verify the valid running container with rm flag
func (suite *PouchRunSuite) TestRunWithRM(c *check.C) {
	cname := "TestRunWithRM"
	command.PouchRun("run", "--rm", "--name", cname, busyboxImage, "echo", "hello").Assert(c, icmd.Success)

	output := command.PouchRun("inspect", cname).Stderr()
	c.Assert(util.PartialEqual(output, cname+": not found"), check.IsNil)
}

// TestRunWithVolumesFrom tests running container with --volumes-from.
func (suite *PouchRunSuite) TestRunWithVolumesFrom(c *check.C) {
	volumeName := "volumesfrom-test-volume"
	containerName1 := "volumesfrom-test-1"
	containerName2 := "volumesfrom-test-2"

	// create volume
	command.PouchRun("volume", "create", "-n", volumeName).Assert(c, icmd.Success)
	defer func() {
		command.PouchRun("volume", "rm", volumeName).Assert(c, icmd.Success)
	}()

	// run container1
	command.PouchRun("run", "-d",
		"-v", volumeName+":/mnt",
		"-v", "/tmp:/tmp",
		"--name", containerName1, busyboxImage, "top").Assert(c, icmd.Success)
	defer func() {
		command.PouchRun("rm", "-f", containerName1).Assert(c, icmd.Success)
	}()

	// stop container1
	command.PouchRun("stop", containerName1).Assert(c, icmd.Success)

	// run container2
	command.PouchRun("run", "-d",
		"--volumes-from", containerName1,
		"--name", containerName2, busyboxImage, "top").Assert(c, icmd.Success)
	defer func() {
		command.PouchRun("rm", "-f", containerName2).Assert(c, icmd.Success)
	}()

	// inspect container2
	ret := command.PouchRun("inspect", containerName2)
	ret.Assert(c, icmd.Success)
	out := ret.Stdout()

	volumeFound := false
	for _, line := range strings.Split(out, "\n") {
		if strings.Contains(line, "\"volumesfrom-test-volume\"") {
			volumeFound = true
			break
		}
	}

	c.Assert(volumeFound, check.Equals, true)
}

// TestRunWithVolumesFromWithDupclicate tests running container with --volumes-from.
func (suite *PouchRunSuite) TestRunWithVolumesFromWithDupclicate(c *check.C) {
	volumeName := "volumesfromDupclicate-test-volume"
	containerName1 := "volumesfromDupclicate-test-1"
	containerName2 := "volumesfromDupclicate-test-2"

	// create volume
	command.PouchRun("volume", "create", "-n", volumeName).Assert(c, icmd.Success)
	defer func() {
		command.PouchRun("volume", "rm", volumeName).Assert(c, icmd.Success)
	}()

	// run container1
	command.PouchRun("run", "-d",
		"-v", volumeName+":/mnt",
		"-v", "/tmp:/tmp",
		"--name", containerName1, busyboxImage, "top").Assert(c, icmd.Success)
	defer func() {
		command.PouchRun("rm", "-f", containerName1).Assert(c, icmd.Success)
	}()

	// stop container1
	command.PouchRun("stop", containerName1).Assert(c, icmd.Success)

	// run container2
	command.PouchRun("run", "-d",
		"-v", "/tmp:/tmp",
		"--volumes-from", containerName1,
		"--name", containerName2, busyboxImage, "top").Assert(c, icmd.Success)
	defer func() {
		command.PouchRun("rm", "-f", containerName2).Assert(c, icmd.Success)
	}()

	// inspect container2
	ret := command.PouchRun("inspect", containerName2)
	ret.Assert(c, icmd.Success)
	out := ret.Stdout()

	volumeFound := false
	for _, line := range strings.Split(out, "\n") {
		if strings.Contains(line, "\"volumesfromDupclicate-test-volume\"") {
			volumeFound = true
			break
		}
	}

	c.Assert(volumeFound, check.Equals, true)
}

// TestRunWithUlimit tests running container with --ulimit flag.
func (suite *PouchRunSuite) TestRunWithUlimit(c *check.C) {
	cname := "TestRunWithUlimit"
	res := command.PouchRun("run", "--ulimit", "nproc=256", "--name", cname, busyboxImage, "sh", "-c", "ulimit -p")
	res.Assert(c, icmd.Success)

	out := res.Stdout()
	c.Assert(out, check.Equals, "256\n")

	output := command.PouchRun("inspect", cname).Stdout()
	result := []types.ContainerJSON{}
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		c.Errorf("failed to decode inspect output: %v", err)
	}
	ul := result[0].HostConfig.Ulimits[0]
	c.Assert(ul.Name, check.Equals, "nproc")
	c.Assert(int(ul.Hard), check.Equals, 256)
	c.Assert(int(ul.Soft), check.Equals, 256)

}


text:
DESCRIPTION = "PMU Firmware"

LICENSE = "CLOSED"

PROVIDES = "virtual/pmu-firmware"

INHERIT_DEFAULT_DEPENDS = "1"

COMPATIBLE_MACHINE = "^$"
COMPATIBLE_MACHINE:zynqmp = ".*"

# Since we're just copying, we can run any config
COMPATIBLE_HOST = ".*"

PACKAGE_ARCH = "${MACHINE_ARCH}"

# Default expects the user to provide the pmu-firmware in the deploy
# directory, named "pmu-firmware-${MACHINE}.elf" and "pmu-firmware-${MACHINE}.bin"
# A machine, multiconfig, or local.conf should override this
PMU_DEPENDS ??= ""
PMU_MCDEPENDS ??= ""
PMU_FIRMWARE_DEPLOY_DIR ??= "${DEPLOY_DIR_IMAGE}"
PMU_FIRMWARE_DEPLOY_DIR[vardepsexclude] += "TOPDIR"
PMU_FIRMWARE_IMAGE_NAME ??= "pmu-firmware-${MACHINE}"

# Default is for the multilib case (without the extension .elf/.bin)
PMU_FILE ??= "${PMU_FIRMWARE_DEPLOY_DIR}/${PMU_FIRMWARE_IMAGE_NAME}"
PMU_FILE[vardepsexclude] = "PMU_FIRMWARE_DEPLOY_DIR"

do_fetch[depends] += "${PMU_DEPENDS}"
do_fetch[mcdepends] += "${PMU_MCDEPENDS}"

inherit deploy

do_install() {
    if [ ! -e ${PMU_FILE}.elf ]; then
        echo "Unable to find PMU_FILE (${PMU_FILE}.elf)"
        exit 1
    fi

    install -Dm 0644 ${PMU_FILE}.elf ${D}/boot/${PN}.elf
}

# If the item is already in OUR deploy_image_dir, nothing to deploy!
SHOULD_DEPLOY = "${@'false' if (d.getVar('PMU_FILE')).startswith(d.getVar('DEPLOY_DIR_IMAGE')) else 'true'}"
do_deploy() {
    if ${SHOULD_DEPLOY}; then
        install -Dm 0644 ${PMU_FILE}.elf ${DEPLOYDIR}/${PMU_FIRMWARE_IMAGE_NAME}.elf
        install -Dm 0644 ${PMU_FILE}.bin ${DEPLOYDIR}/${PMU_FIRMWARE_IMAGE_NAME}.bin
    fi
}

addtask deploy before do_build after do_install

INSANE_SKIP:${PN} = "arch"
INSANE_SKIP:${PN}-dbg = "arch"

# Disable buildpaths QA check warnings.
INSANE_SKIP:${PN} += "buildpaths"

SYSROOT_DIRS += "/boot"
FILES:${PN} = "/boot/${PN}.elf"

def check_pmu_vars(d):
    # If both are blank, the user MUST pass in the path to the firmware!
    if not d.getVar('PMU_DEPENDS') and not d.getVar('PMU_MCDEPENDS'):
        # Don't cache this, as the items on disk can change!
        d.setVar('BB_DONT_CACHE', '1')

        msg = ""
        fail = False
        if not os.path.exists(d.getVar('PMU_FILE') + ".elf"):
            msg = msg + "The expected file %s.elf is not available.  " % d.getVar('PMU_FILE')
            fail = True
        if not os.path.exists(d.getVar('PMU_FILE') + ".bin"):
            msg = msg + "The expected file %s.bin is not available.  " % d.getVar('PMU_FILE')
            fail = True
        if fail:
            if not d.getVar('WITHIN_EXT_SDK'):
                raise bb.parse.SkipRecipe("%s  See the meta-xilinx-core README." % msg)
        else:
            # We found the file, so be sure to track it
            d.setVar('SRC_URI', 'file://${PMU_FILE}.elf file://${PMU_FILE}.bin')
            d.setVarFlag('do_install', 'file-checksums', '${PMU_FILE}.elf:True')
            d.setVarFlag('do_deploy', 'file-checksums', '${PMU_FILE}.elf:True ${PMU_FILE}.bin:True')

python() {
    # Need to allow bbappends to change the check
    check_pmu_vars(d)
}

repository: Xilinx/meta-xilinx

repo_name: Xilinx/meta-xilinx

gha_language: C


text:
package main

import (
	"os"

	"github.com/Sirupsen/logrus"
	cloudflare "github.com/arkan/cloudflare-ddns"
)

func main() {
	c, err := cloudflare.New(os.Getenv("CF_API_KEY"), os.Getenv("CF_API_EMAIL"))
	if err != nil {
		logrus.WithError(err).Fatal("unable to instantiate ddns")
	}

	c.KeepUpdated(os.Getenv("CF_HOST"))
}

repository: arkan/cloudflare-ddns

repo_name: arkan/cloudflare-ddns


text:
package main

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"log"
	"os"

	"github.com/jawher/mow.cli"
)

func main() {
	app := cli.App("expandenv", "Expand environment variables in input file")
	app.Spec = "[-b] FILE"
	app.Version("v version", "0.0.2")

	var (
		encode = app.BoolOpt("b base64", false, "base64 encode values")
		src    = app.StringArg("FILE", "", "input file")
	)

	app.Action = func() {
		buf, err := ioutil.ReadFile(*src)
		if err != nil {
			log.Fatal(err)
		}

		fileData := string(buf)
		var mapper func(string) string
		if !*encode {
			mapper = os.Getenv
		} else {
			mapper = envBase64Encoder
		}
		fmt.Print(os.Expand(fileData, mapper))
	}

	app.Run(os.Args)
}

func envBase64Encoder(key string) string {
	return base64.StdEncoding.EncodeToString([]byte(os.Getenv(key)))
}

repository: vially/expandenv

repo_name: vially/expandenv


text:
package httpfake

import (
	"net/url"
	"strings"
)

// Request stores the settings for a request handler
// Such as how to match this handler for the incoming requests
// And how this request will respond back
type Request struct {
	Method       string
	URL          *url.URL
	Response     *Response
	CustomHandle Responder
}

// NewRequest creates a new Request
func NewRequest() *Request {
	return &Request{
		URL:      &url.URL{},
		Response: NewResponse(),
	}
}

// Get sets a GET request handler for a given path
func (r *Request) Get(path string) *Request {
	return r.method("GET", path)
}

// Post sets a POST request handler for a given path
func (r *Request) Post(path string) *Request {
	return r.method("POST", path)
}

// Put sets a PUT request handler for a given path
func (r *Request) Put(path string) *Request {
	return r.method("PUT", path)
}

// Patch sets a PATCH request handler for a given path
func (r *Request) Patch(path string) *Request {
	return r.method("PATCH", path)
}

// Delete ...
func (r *Request) Delete(path string) *Request {
	return r.method("DELETE", path)
}

// Head sets a HEAD request handler for a given path
func (r *Request) Head(path string) *Request {
	return r.method("HEAD", path)
}

// Handle sets a custom handle
// By setting this responder it gives full control to the user over this request handler
func (r *Request) Handle(handle Responder) {
	r.CustomHandle = handle
}

// Reply sets a response status for this request
// And returns the Response struct to allow chaining the response settings
func (r *Request) Reply(status int) *Response {
	return r.Response.Status(status)
}

func (r *Request) method(method, path string) *Request {
	if path != "/" {
		r.URL.Path = path
	}
	r.Method = strings.ToUpper(method)
	return r
}

repository: erutherford/httpfake

repo_name: erutherford/httpfake


text:
@article{ueckermann_lermusiaux_JCP2016,
              author = {Ueckermann, M. P. and Lermusiaux, P. F. J.},
              title = {Hybridizable Discontinuous {G}alerkin Projection Methods for {N}avier--{S}tokes and {B}oussinesq Equations},
              journal = {Journal of Computational Physics},
              volume = {306},
              year = {2016},
              pages = {390--421},
              doi = {10.1016/j.jcp.2015.11.028}
}

@misc{quadpy,
    author = {Schloemer, Nico},
    title = {\texttt{quadpy}: numerical integration in Python},
    year = {2018},
    publisher = {GitHub},
    howpublished = \url{\texttt{https://github.com/nschloe/quadpy}}
}

@book{hesthaven2007nodal,
    title={Nodal discontinuous Galerkin methods: algorithms, analysis, and applications},
      author={Hesthaven, Jan S and Warburton, Tim},
        year={2007},
          publisher={Springer Science \& Business Media}
}

repository: CorbinFoucart/FEMexperiment

repo_name: CorbinFoucart/FEMexperiment

gha_language: Jupyter Notebook


text:
/*
 * qmqtt_WssNetwork.cpp - qmqtt WssNetwork
 *
 * Copyright (c) 2013  Ery Lee <ery.lee at gmail dot com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the name of mqttc nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <QDataStream>
#include <QDebug>
//#include <QLoggingCategory>
#include "qmqtt_wss_network.h"

namespace QMQTT {

//Q_LOGGING_CATEGORY(WssNetwork, "qmqtt.WssNetwork")

WssNetwork::WssNetwork(QObject *parent) :
    QMQTT::AbstractNetwork(parent)
{
    _buffer = new QBuffer(this);
    _offsetBuf = 0;
    _leftSize = 0;
    _autoreconn = false;
    _timeout = 3000;
    _connected = false;
    _buffer->open(QIODevice::ReadWrite);
    initSocket();
}

void WssNetwork::initSocket()
{
    if(_socket) {
        _socket->abort();
        delete _socket;
    }

    _socket = new QtWebsocket::QWsSocket(this, NULL, QtWebsocket::WS_V13);

    QObject::connect(_socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
    QObject::connect(_socket, SIGNAL(frameReceived(QByteArray)), this, SLOT(sockReadReady(QByteArray)));
    QObject::connect(_socket, SIGNAL(connected()), this, SLOT(sockConnected()));
    QObject::connect(_socket, SIGNAL(disconnected()), this, SLOT(sockDisconnected()));
    QObject::connect(_socket, SIGNAL(sslErrors(const QList<QSslError>&)), this, SLOT(displaySslErrors(const QList<QSslError>&)));
}

WssNetwork::~WssNetwork()
{
    disconnect();
}

bool WssNetwork::isConnected()
{
    return _connected;
}

void WssNetwork::connectTo(const QString & host, const quint32 port)
{

    if(!_socket)
    {
        //qCWarning(WssNetwork) << "AMQP: Socket didn't create.";
        return;
    }
    QUrl url(host);
    _host = url.scheme()+"://"+url.host();
    _resource = host.right(host.length()-_host.length());
    _port = port;
    //qCDebug(WssNetwork) << "Connect to" << _host << _port;

    _socket->setProtocol("mqtt");
    //_socket->setExtensions("permessage-deflate; client_max_window_bits");
    _socket->setResourceName(_resource);
    _socket->setOrigin("qmqtt_client");
    _socket->connectToHost(_host, _port);
    //qDebug() << "Connecting..";
}

void WssNetwork::sendFrame(Frame & frame)
{

    if(_socket->state() == QAbstractSocket::ConnectedState)
    {
        QByteArray data;
        QDataStream stream(&data,QIODevice::WriteOnly);
        frame.write(stream);
        //qDebug() << "MQTT TX:" << data.toHex();
        _socket->write(data);
    }

}

void WssNetwork::disconnect()
{
    if(_socket) _socket->disconnectFromHost();
}

QAbstractSocket::SocketState WssNetwork::state() const
{
    if(_socket)
    {
        return _socket->state();
    } else {
        return QAbstractSocket::UnconnectedState;
    }
}

bool WssNetwork::autoReconnect() const
{
    return _autoreconn;
}

void WssNetwork::setAutoReconnect(bool b)
{
    _autoreconn = b;
}

//PRIVATE SLOTS
void WssNetwork::sockConnected()
{
    qDebug() << "WssNetwork connected...";
    _connected = true;
    emit connected();
}

void WssNetwork::sockReadReady(QByteArray data)
{
    QDataStream in(data);
    QDataStream out(_buffer);
    while(!in.atEnd())
    {
        if(_leftSize == 0)
        {
            _leftSize  = 0;
            _offsetBuf = 0;

            in >> _header;
            _leftSize = readRemaingLength(in);
        }
        QByteArray data;
        data.resize(_leftSize);
        _offsetBuf = in.readRawData(data.data(), data.size());
        _leftSize -= _offsetBuf;
        out.writeRawData(data.data(), _offsetBuf);
        if(_leftSize == 0)
        {
            _buffer->reset();
            Frame frame(_header, _buffer->buffer());
            _buffer->buffer().clear();
            //qCDebug(WssNetwork) << "WssNetwork emit received(frame), header: " << _header;
            emit received(frame);
        }
    }
}

/*
 * Read remaining length
 */
int WssNetwork::readRemaingLength(QDataStream &in)
{
     qint8 byte;
     int len = 0;
     int mul = 1;
     do {
         in >> byte;
         len += (byte & 127) * mul;
         mul *= 128  ;
     } while ((byte & 128) != 0);
     return len;
}

void WssNetwork::socketStateChanged(QAbstractSocket::SocketState socketState)
{
    switch (socketState)
    {
        case QAbstractSocket::UnconnectedState:
            qDebug() << "ws:  Unconnected";
            break;
        case QAbstractSocket::HostLookupState:
            qDebug() << "ws:  HostLookup";
            break;
        case QAbstractSocket::ConnectingState:
            qDebug() << "ws:  Connecting";
            break;
        case QAbstractSocket::ConnectedState:
            qDebug() << "ws:  Connected";
            break;
        case QAbstractSocket::BoundState:
            qDebug() << "ws:  Bound";
            break;
        case QAbstractSocket::ClosingState:
            qDebug() << "ws:  Closing";
            break;
        case QAbstractSocket::ListeningState:
            qDebug() << "ws:  Listening";
            break;
        default:
            qDebug() << "ws:  Unknown";
            break;
    }
}

void WssNetwork::displaySslErrors(const QList<QSslError>& errors)
{
    for (int i=0, sz=errors.size(); i<sz; i++)
    {
        QString errorString = errors.at(i).errorString();
        qDebug() << "SSL error: " << errorString;
    }
}

void WssNetwork::sockDisconnected()
{
    _connected = false;
    emit disconnected();
}

} // namespace QMQTT

repository: czzCreator/QMQTT-collection

repo_name: czzCreator/QMQTT-collection

extension: cpp


text:
require postgresql.inc

LIC_FILES_CHKSUM = "file://COPYRIGHT;md5=6dc95e63aa4d72502ff8193dfe2ddd38"

SRC_URI += "\
   file://not-check-libperl.patch \
"

SRC_URI[md5sum] = "5e45f6d5b859cc76b5d62f1e328e9711"
SRC_URI[sha256sum] = "90815e812874831e9a4bf6e1136bf73bc2c5a0464ef142e2dfea40cda206db08"

repository: adhameed/meta-openembedded

repo_name: adhameed/meta-openembedded


text:
package greddis

import (
	"context"
	"testing"

	gomock "github.com/golang/mock/gomock"
	"github.com/mikn/greddis/mocks/mock_net"
	"github.com/stretchr/testify/require"
)

func TestPing(t *testing.T) {
	t.Run("fail on Flush", func(t *testing.T) {
		var ctx, cancel = context.WithCancel(context.Background())
		var ctrl = gomock.NewController(t)
		defer ctrl.Finish()
		var mockConn = mock_net.NewMockConn(ctrl)
		conn := newConn(mockConn, 4096)
		mockConn.EXPECT().Write(gomock.Any()).Return(0, ErrConnWrite)
		err := ping(ctx, conn)
		require.Error(t, err)
		cancel()
	})
	t.Run("fail on Scan", func(t *testing.T) {
		var ctx, cancel = context.WithCancel(context.Background())
		var ctrl = gomock.NewController(t)
		defer ctrl.Finish()
		var mockConn = mock_net.NewMockConn(ctrl)
		conn := newConn(mockConn, 4096)
		mockConn.EXPECT().Write(gomock.Any()).Return(14, nil)
		mockConn.EXPECT().Read(gomock.Any()).DoAndReturn(func(b []byte) (int, error) {
			copy(b, []byte("*1\r\n$4\r\nPONG\r\n"))
			return 14, nil
		})
		err := ping(ctx, conn)
		require.Error(t, err)
		cancel()
	})
	t.Run("fail on reply", func(t *testing.T) {
		var ctx, cancel = context.WithCancel(context.Background())
		var ctrl = gomock.NewController(t)
		defer ctrl.Finish()
		var mockConn = mock_net.NewMockConn(ctrl)
		conn := newConn(mockConn, 4096)
		mockConn.EXPECT().Write(gomock.Any()).Return(14, nil)
		mockConn.EXPECT().Read(gomock.Any()).DoAndReturn(func(b []byte) (int, error) {
			copy(b, []byte("+PON\r\n"))
			return 10, nil
		})
		err := ping(ctx, conn)
		require.Error(t, err)
		cancel()
	})
	t.Run("success", func(t *testing.T) {
		var ctx, cancel = context.WithCancel(context.Background())
		var ctrl = gomock.NewController(t)
		defer ctrl.Finish()
		var mockConn = mock_net.NewMockConn(ctrl)
		conn := newConn(mockConn, 4096)
		mockConn.EXPECT().Write(gomock.Any()).Return(14, nil)
		mockConn.EXPECT().Read(gomock.Any()).DoAndReturn(func(b []byte) (int, error) {
			copy(b, []byte("+PONG\r\n"))
			return 7, nil
		})
		err := ping(ctx, conn)
		require.NoError(t, err)
		cancel()
	})
}

repository: mikn/greddis

repo_name: mikn/greddis


text:
DESCRIPTION = "U-Boot port for RaspberryPi"

require recipes-bsp/u-boot/u-boot.inc

DEPENDS += "rpi-mkimage-native"

PROVIDES += "u-boot"

LICENSE = "GPLv2+"
LIC_FILES_CHKSUM = "file://COPYING;md5=1707d6db1d42237583f50183a5651ecb"

SRCREV = "6709570cdc947c2a546f96d571551acf4474778c"
SRC_URI = "git://github.com/gonzoua/u-boot-pi.git;branch=rpi"

S = "${WORKDIR}/git"

UBOOT_MACHINE = "rpi_b"
UBOOT_MAKE_TARGET = "u-boot.bin"
UBOOT_SUFFIX = "img"

PACKAGE_ARCH = "${MACHINE_ARCH}"

COMPATIBLE_MACHINE = "raspberrypi"

do_compile_append() {
    # Create kernel.img from uboot.bin and name it u-boot.img
    ${STAGING_BINDIR_NATIVE}/imagetool-uncompressed.py u-boot.bin
    mv kernel.img u-boot.img
}


text:
@article{chung2014efficient,
 author = {Chung, Szu-Chi and Wu, Jing-Yu and Fu, Hsing-Ping and Lee, Jen-Wei and Chang, Hsie-Chia and Lee, Chen-Yi},
 journal = {IEEE Transactions on Very Large Scale Integration (VLSI) Systems},
 number = {1},
 pages = {88--97},
 publisher = {IEEE},
 title = {Efficient Hardware Architecture of $$\backslash$eta_ $\$T$\$ $ Pairing Accelerator Over Characteristic Three},
 volume = {23},
 year = {2014}
}


text:
package factorymethod

import (
	"fmt"
)

type IButton interface {
	Click()
}

type IButtonFactory interface {
	CreateButton() IButton
}

type WindowsButton struct{}
type MacButton struct{}

func (this WindowsButton) Click() { fmt.Println("WindowsButton.Click") }
func (this MacButton) Click()     { fmt.Println("MacButton.Click") }

type WindowsButtonFactory struct{}
type MacButtonFactory struct{}

func (this WindowsButtonFactory) CreateButton() IButton {
	return WindowsButton{}
}

func (this MacButtonFactory) CreateButton() IButton {
	return MacButton{}
}

repository: eggfly/gopattern

repo_name: eggfly/gopattern


text:
package util

import (
	"fmt"
	"strconv"
)

func Str2intLollipopgo(data string) int {
	v, err := strconv.Atoi(data)
	if err != nil {
		return -1
	}
	return v
}

func Int2str_LollipopGo(data int) string {
	return strconv.Itoa(data)
}

// data to string all
func ToString(arg interface{}) string {
	switch arg.(type) {
	case bool:
		return boolToString(arg.(bool))
	case float32:
		return floatToString(float64(arg.(float32)))
	case float64:
		return floatToString(arg.(float64))
	case int:
		return intToString(int64(arg.(int)))
	case int8:
		return intToString(int64(arg.(int8)))
	case int16:
		return intToString(int64(arg.(int16)))
	case int32:
		return intToString(int64(arg.(int32)))
	case int64:
		return intToString(int64(arg.(int64)))
	default:
		return fmt.Sprint(arg)
	}
}

func floatToString(f float64) string {
	return strconv.FormatFloat(f, 'E', -1, 64)
}
func intToString(i int64) string {
	return strconv.FormatInt(i, 10)
}
func boolToString(b bool) string {
	if b {
		return "true"
	} else {
		return "false"
	}
}

repository: Golangltd/LollipopGo

repo_name: Golangltd/LollipopGo


text:
#require kolibrecommon.inc
require recipes-kolibre/images/kolibre-common.inc

export IMAGE_BASENAME = "kolibre-image"

IMAGE_ROOTFS_EXTRA_SPACE = "524000"

repository: kolibre/meta-kolibre

repo_name: kolibre/meta-kolibre


text:
package akash

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

	"github.com/gorilla/mux"
	"github.com/openfaas/faas-provider/types"
	akashTypes "github.com/vitwit/faas-akash/types"
)

func ReplicaReader(serviceMap akashTypes.ServiceMap) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		functionName := vars["name"]

		if _, ok := serviceMap[functionName]; ok {
			found := types.FunctionStatus{
				Name:              functionName,
				AvailableReplicas: 1,
				Replicas:          1,
			}

			functionBytes, _ := json.Marshal(found)
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusOK)
			_, _ = w.Write(functionBytes)
		} else {
			w.WriteHeader(http.StatusNotFound)
		}
	}
}

func ReadHandler(serviceMap akashTypes.ServiceMap) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {

		res := []types.FunctionStatus{}
		for k := range serviceMap {
			res = append(res, types.FunctionStatus{
				Name:     k,
				Replicas: 1,
			})
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		_ = json.NewEncoder(w).Encode(res)
	}
}

repository: vitwit/faas-akash

repo_name: vitwit/faas-akash