text:
DESCRIPTION = "bkeymaps and initscript"

HOMEPAGE = "http://dev.alpinelinux.org/bkeymaps"
LICENSE = "GPL"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/GPL-1.0;md5=e9e36a9de734199567a4d769498f743d"

PV = "1.13"

SRC_URI = "http://dev.alpinelinux.org/bkeymaps/bkeymaps-${PV}.tar.gz \
           file://bkeymap.sh"

SRC_URI[sha256sum] = "59d41ddb0c7a92d8ac155a82ed2875b7880c8957ea4308afa633c8b81e5b8887"

KEYMAPS_DEST_PREFIX = "/usr/share/bkeymaps"

do_install() {
	install -d ${D}${sysconfdir}/init.d
	install -m 0755 ${WORKDIR}/bkeymap.sh ${D}${sysconfdir}/init.d

	update-rc.d -r ${D} bkeymap.sh start 53 S .

	install -d ${D}${KEYMAPS_DEST_PREFIX}
	cp -r ${WORKDIR}/bkeymaps-1.13/bkeymaps/* ${D}${KEYMAPS_DEST_PREFIX}
}

repository: MildePM/meta-jens

repo_name: MildePM/meta-jens


text:
MAINTAINER = "Chris Larson <kergoth@handhelds.org>"
HOMEPAGE = "http://www.intel.com/design/network/products/npfamily/download_ixp400.htm"
LICENSE = "${PN}"
LICENSE_HOMEPAGE = "http://www.intel.com/design/network/swsup/ixp400AccessLibrary-1_4.htm"
SRC_URI = "http://www.intel.com/design/network/swsup/ixp400AccessLibrary-1_4.zip \
	   http://www.wnk.at/ixp400_accesslib_kernel26/data/patch_accesslib_kernel26_20040811.diff;patch=1 \
	   file://badpaths.patch;patch=1 \
	   file://build-timing-annoyance.patch;patch=1"
S = "${WORKDIR}/ixp400_xscale_sw"
PR = "r4"

COMPATIBLE_HOST = "^armeb-linux.*"

inherit module

# Add the architecture compiler flags to KERNEL_CC and KERNEL_LD as
# required.  Notice that this has to be done for each separately built
# module as well!
KERNEL_CC += "${TARGET_CC_KERNEL_ARCH}"
KERNEL_LD += "${TARGET_LD_KERNEL_ARCH}"

#LINUX_MACH_CFLAGS := -D__LINUX_ARM_ARCH__=5 -mcpu=xscale -mtune=xscale
CFLAGS = "-fno-common -D__KERNEL__ -DMODULE -D__linux -DCPU=33 -DXSCALE=33 \
	  -D__LINUX_ARM_ARCH__=5 \
	  -I${S}/src/linux -I${S}/src/include \
	  ${BUILD_OPTIMIZATION} \
	  -I${STAGING_KERNEL_DIR}/include"

EXTRA_OEMAKE = "'CFLAGS=${CFLAGS}' \
		'CC=${KERNEL_CC}' \
		'LD=${KERNEL_LD}' \
		'IX_TARGET=linuxbe' \
		'LINUX_SRC=${STAGING_KERNEL_DIR}' \
		'ARCH=${ARCH}'"
#EXTRA_OEMAKE = "'LINUX_SRC=${STAGING_KERNEL_DIR}' 'IX_TARGET=${IX_TARGET}' \
#	        'ARCH=${TARGET_ARCH}' 'CROSS_COMPILE=${TARGET_PREFIX}'"

do_compile () {
	oe_runmake ixp400.ko
}

do_stage () {
	install -d ${STAGING_INCDIR}/linux/ixp4xx-csr
	install -m 0644 src/include/*.h ${STAGING_INCDIR}/linux/ixp4xx-csr/
	cp -rf --dereference src/linux/* ${STAGING_INCDIR}/linux/ixp4xx-csr/
}

do_install () {
	install -d ${D}${base_libdir}/modules/${KERNEL_VERSION}/drivers/ixp400
	install -m 0644 lib/linuxbe/ixp400.ko ${D}${base_libdir}/modules/${KERNEL_VERSION}/drivers/ixp400/
}

license: MIT

repository: Terentyev/familiar-linux

license_type: permissive

repo_name: Terentyev/familiar-linux

branch_name: refs/heads/master

extension: bb


text:
package main

import (
	"log"

	"github.com/teamwork/nylas-go"
)

const (
	clientSecret = "nylas client secret"
)

func main() {
	listener := nylas.NewWebhookListener(clientSecret)
	log.Fatal(listener.Listen(":8080", func(delta nylas.WebhookDelta) error {
		// Handle the webhook, if doing long running work do it in
		// another routine as the request will timeout
		log.Printf("%s\nDate: %v\nData: %+v", delta.Type, delta.Date, delta.ObjectData)

		return nil // non-nil error will be returned to Nylas as 500
	}))
}

repository: Teamwork/nylas-go

repo_name: Teamwork/nylas-go

gha_license_id: MIT

gha_language: Go

extension: go


text:
@article{cardoso2015genome,
 author = {Cardoso, T and Quintanilla, R and Amills, M and Canela, O and González-Prendes, R and Cánovas, A and others},
 journal = {XVI Jornadas sobre Producción Animal, 19 y 20 de mayo de 2015, Zaragoza, España. Tomo I & II},
 pages = {459--461},
 publisher = {Asociación Interprofesional para el Desarrollo Agrario},
 title = {A genome-wide analysis of differentially expressed messenger RNA isoforms in pigs with divergent lipid profiles.},
 year = {2015}
}

repository: rprendes/starter-academic-rayner

repo_name: rprendes/starter-academic-rayner

extension: bib


text:
DESCRIPTION = "Board configuration tool"
MAINTAINER = "nian.gao@siemens.com"

SRC_URI = "file://iot2050setup.py"

DEBIAN_DEPENDS = "python3-newt, mraa"

inherit dpkg-raw

do_install() {
    install -v -d ${D}/usr/bin/
    install -v -m 755 ${WORKDIR}/iot2050setup.py ${D}/usr/bin/iot2050setup
}


text:
package main

import (
	"fmt"
	"net/url"

	"github.com/murlokswarm/app"
)

// Sf is the component displaying San Francisco.
type Sf struct{}

// Render returns the HTML describing the Sf component content.
// It contains a link to show how to navigate to an other component (Paris).
func (s *Sf) Render() string {
	return `

San Francisco

		San Francisco, in northern California, is a hilly city on the tip of a
		peninsula surrounded by the Pacific Ocean and San Francisco Bay.
		It's known for its year-round fog, iconic Golden Gate Bridge, cable cars
		and colorful Victorian houses.
		The Financial District's Transamerica Pyramid is its most distinctive
		skyscraper.
		In the bay sits Alcatraz Island, site of the notorious former prison.

	Go to Paris

	`
}

// OnHref is defined to satisfy the Hrefer interface. It is called when a link
// with href="Sf" is clicked.
func (s *Sf) OnHref(URL *url.URL) {
	fmt.Println("mounted from a link click:", URL)
}

// /!\ Register the component. Required to use the component into a context.
func init() {
	app.RegisterComponent(&Sf{})
}


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

package snatchs

import (
	"strings"
	"testing"
)

func TestBQ5IsBookUrl(t *testing.T) {
	bq := NewBqg5()

	url := "https://www.bqg5.cc/0_1/"
	if !bq.IsBookURL(url) {
		t.Fatal("小说简介页面匹配失败")
	}

	url = "https://www.bqg5.cc/xiuzhenxiaoshuo/"
	if bq.IsBookURL(url) {
		t.Fatal("小说简介页面匹配失败")
	}

	url = "https://www.bqg5.cc/0_1/1492.html"
	if bq.IsBookURL(url) {
		t.Fatal("小说简介页面匹配失败")
	}
}

func TestBQ5IsCrawlerUrl(t *testing.T) {
	bq := NewBqg5()

	url := "https://www.bqg5.cc/0_1/1492.html"
	if bq.IsCrawlerURL(url) {
		t.Fatal("爬虫URL匹配失败")
	}

	url = "https://www.bqg5.cc/0_1/"
	if bq.IsCrawlerURL(url) {
		t.Fatal("爬虫匹配失败")
	}

	url = "https://www.bqg5.cc/xuanhuanxiaoshuo/"
	if !bq.IsCrawlerURL(url) {
		t.Fatal("爬虫匹配失败")
	}
}

func TestBQ5GetNovel(t *testing.T) {
	bq := NewBqg5()

	url := "https://www.bqg5.cc/10_10440/"
	info, err := bq.GetNovel(url)
	if err != nil {
		t.Fatal(err.Error())
	}

	nov := info.Nov

	if nov == nil {
		t.Fatal("获取小说失败")
	}

	if nov.Name != "圣墟" {
		t.Fatal("获取小说标题错误", nov.Name)
	}

	if !strings.Contains(nov.Desc, "败中崛起，在寂灭中复苏") {
		t.Fatal("获取小说内容错误", nov.Desc)
	}

	if nov.Author != "辰东" {
		t.Fatal("获取小说作者错误", nov.Author)
	}

	if nov.CateName != "玄幻小说" {
		t.Fatal("获取小说分类名称错误", nov.CateName)
	}

	if nov.CateId != 1 {
		t.Fatal("匹配小说分类ID错误", nov.CateId)
	}

	if nov.Cover != "http://r.m.bqg5.cc/files/article/image/10/10440/10440s.jpg" {
		t.Fatal("匹配小说封面错误", nov.Cover)
	}

	if info.ChapterUrl != url {
		t.Fatal("获取小说章节链接错误", info.ChapterUrl)
	}
}

func TestBQ5FindNovel(t *testing.T) {
	bq := NewBqg5()
	info, err := bq.FindNovel("圣墟")
	if err != nil {
		t.Fatal(err.Error())
	}

	nov := info.Nov

	if nov == nil {
		t.Fatal("获取小说失败")
	}

	if nov.Name != "圣墟" {
		t.Fatal("获取小说标题错误", nov.Name)
	}

	if !strings.Contains(nov.Desc, "在寂灭中复苏") {
		//t.Fatal("获取小说内容错误")
	}

	if nov.Author != "辰东" {
		t.Fatal("获取小说作者错误", nov.Author)
	}

	if info.Url != "https://www.bqg5.cc/10_10440/" {
		t.Fatal("获取小说链接错误", info.Url)
	}

	if info.ChapterUrl != "https://www.bqg5.cc/10_10440/" {
		t.Fatal("获取小说章节链接错误", info.ChapterUrl)
	}
}

func TestBQ5GetChapter(t *testing.T) {
	bq := NewBqg5()

	info, err := bq.GetChapter("https://www.bqg5.cc/10_10440/4499479.html")
	if err != nil {
		t.Fatal(err.Error())
	}
	chap := info.Chap

	if chap.Title != "第一章 沙漠中的彼岸花" {
		t.Fatal("获取章节标题错误", chap.Title)
	}

	if !strings.Contains(chap.Desc, "的大漠，空旷而高远，壮阔") {
		t.Fatal("获取章节内容错误", chap.Desc)
	}

	if info.PreUrl != "" {
		t.Fatal("获取上一页连接错误", info.PreUrl)
	}

	if info.NextUrl != "https://www.bqg5.cc/10_10440/4499481.html" {
		t.Fatal("获取下一页连接错误", info.NextUrl)
	}
}

func TestBQ5GetChapters(t *testing.T) {
	bq := NewBqg5()

	links, err := bq.GetChapters("https://www.bqg5.cc/10_10440/")
	if err != nil {
		t.Fatal("获取章节列表失败", err.Error())
	}
	if len(links) == 0 {
		t.Fatal("获取章节列表失败")
	}

	if links[0].Chap.Link != "https://www.bqg5.cc/10_10440/4499479.html" {
		t.Fatal("获取小说链接错误", links[0].Chap.Link)
	}
}

repository: weishanyun/novel

repo_name: weishanyun/novel


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

package resultdb

import (
	"context"
	"testing"

	pb "go.chromium.org/luci/resultdb/proto/v1"
	"go.chromium.org/luci/resultdb/rdbperms"
	"google.golang.org/grpc/codes"

	"go.chromium.org/luci/common/tsmon"

	"go.chromium.org/luci/server/auth"
	"go.chromium.org/luci/server/auth/authtest"
	"go.chromium.org/luci/server/span"

	"go.chromium.org/luci/resultdb/internal/invocations"
	"go.chromium.org/luci/resultdb/internal/resultcount"
	"go.chromium.org/luci/resultdb/internal/testutil"
	"go.chromium.org/luci/resultdb/internal/testutil/insert"

	. "github.com/smartystreets/goconvey/convey"
	. "go.chromium.org/luci/common/testing/assertions"
)

func TestQueryTestResultStatistics(t *testing.T) {
	Convey(`QueryTestResultStatistics`, t, func() {
		ctx := auth.WithState(testutil.SpannerTestContext(t), &authtest.FakeState{
			Identity: "user:someone@example.com",
			IdentityPermissions: []authtest.RealmPermission{
				{Realm: "testproject:testrealm", Permission: rdbperms.PermListTestResults},
			},
		})
		ctx, _ = tsmon.WithDummyInMemory(ctx)

		incCount := func(invID invocations.ID, count int64) {
			_, err := span.ReadWriteTransaction(ctx, func(ctx context.Context) error {
				return resultcount.IncrementTestResultCount(ctx, invID, count)
			})
			So(err, ShouldBeNil)
		}

		testutil.MustApply(ctx,
			insert.Invocation(
				"x", pb.Invocation_FINALIZED, map[string]any{
					"Realm": "secretproject:testrealm",
				}),
			insert.Invocation(
				"a", pb.Invocation_FINALIZED, map[string]any{
					"Realm": "testproject:testrealm",
				}),
			insert.Invocation(
				"b", pb.Invocation_FINALIZED, map[string]any{
					"Realm": "otherproject:testrealm",
				}),
			insert.Invocation(
				"c", pb.Invocation_FINALIZED, map[string]any{
					"Realm": "otherproject:testrealm",
				}),
			// The invocation d doesn't have any included invocation.
			insert.Invocation(
				"d", pb.Invocation_FINALIZED, map[string]any{
					"Realm": "testproject:testrealm",
				}),
			insert.Inclusion("a", "b"),
			insert.Inclusion("a", "c"),
			// To test no double count if an invocation is included by multiple
			// invocations.
			insert.Inclusion("b", "d"),
			insert.Inclusion("c", "d"),
		)

		incCount(invocations.ID("b"), 5)
		incCount(invocations.ID("c"), 10)
		incCount(invocations.ID("d"), 20)

		srv := newTestResultDBService()

		Convey(`Permission denied`, func() {
			_, err := srv.QueryTestResultStatistics(ctx, &pb.QueryTestResultStatisticsRequest{
				Invocations: []string{"invocations/x"},
			})
			So(err, ShouldHaveAppStatus, codes.PermissionDenied)
		})

		Convey(`Valid with included invocation`, func() {
			res, err := srv.QueryTestResultStatistics(ctx, &pb.QueryTestResultStatisticsRequest{
				Invocations: []string{"invocations/a"},
			})
			So(err, ShouldBeNil)
			So(res.TotalTestResults, ShouldEqual, 35)
		})

		Convey(`Valid without included invocation`, func() {
			res, err := srv.QueryTestResultStatistics(ctx, &pb.QueryTestResultStatisticsRequest{
				Invocations: []string{"invocations/d"},
			})
			So(err, ShouldBeNil)
			So(res.TotalTestResults, ShouldEqual, 20)
		})

		Convey(`Valid with missing included invocation`, func() {
			testutil.MustApply(
				ctx,
				// The invocation missinginv is missing in Invocations table.
				insert.Inclusion("a", "missinginv"),
			)
			res, err := srv.QueryTestResultStatistics(ctx, &pb.QueryTestResultStatisticsRequest{
				Invocations: []string{"invocations/a"},
			})
			So(err, ShouldBeNil)
			So(res.TotalTestResults, ShouldEqual, 35)
		})
	})
}

repository: luci/luci-go

repo_name: luci/luci-go

branch_name: refs/heads/main


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

###############################################################################
# Set common CPACK variables.
###############################################################################

set(CPACK_PACKAGE_NAME ${PROJECT_NAME})

set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "${CPACK_PACKAGE_NAME} - ${${PROJECT_NAME}_DESCRIPTION_SUMMARY}")

set(CPACK_PACKAGE_DESCRIPTION "${${PROJECT_NAME}_DESCRIPTION}")

set(CPACK_PACKAGE_VENDOR "eProsima")
set(CPACK_PACKAGE_CONTACT "eProsima Support <support@eprosima.com>")

set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR})
set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR})
set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH})
set(CPACK_PACKAGE_VERSION ${PROJECT_VERSION})

set(CPACK_COMPONENT_CMAKE_HIDDEN 1)
set(CPACK_COMPONENTS_ALL ${CPACK_COMPONENTS_ALL} cmake)

include(CPack)

extension: cmake


text:
/*
Copyright 2021 The KodeRover Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/koderover/zadig/lib/microservice/cron/server"
)

func main() {
	stopCh := make(chan struct{})

	signals := make(chan os.Signal, 1)
	defer close(signals)

	signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT)
	go func() {
		<-signals
		signal.Stop(signals)
		close(stopCh)
	}()

	if err := server.Serve(stopCh); err != nil {
		log.Fatal(err)
	}
}


text:
DESCRIPTION = "Python template engine and code generation tool"
SECTION = "devel/python"
PRIORITY = "optional"
LICENSE = "MIT"
SRCNAME = "Cheetah"
PR = "r2"

SRC_URI = "${SOURCEFORGE_MIRROR}/cheetahtemplate/${SRCNAME}-${PV}.tar.gz"
S = "${WORKDIR}/${SRCNAME}-${PV}"

inherit distutils

DEPENDS = "python"
RDEPENDS_${PN} = "python-pickle python-pprint"

NATIVE_INSTALL_WORKS = "1"
BBCLASSEXTEND = "native"

SRC_URI[md5sum] = "7845a2950ea850a13c488a26b61ac50a"
SRC_URI[sha256sum] = "70b618a03506831f59ba1ff8433907ee8d4ead5fc9f1b3f610d384e08a26938c"

repository: overo/overo-oe-natty

repo_name: overo/overo-oe-natty

branch_name: HEAD


text:
SUMMARY = "CLucene is a indexing and searching API"
HOMEPAGE = "http://www.sourceforge.net/projects/clucene"
LICENSE = "LGPLv2+ & Apache-2.0"
LIC_FILES_CHKSUM = " \
    file://APACHE.license;md5=86d3f3a95c324c9479bd8986968f4327 \
    file://LGPL.license;md5=464215a90afcdfbae965d89feb928c7e \
    file://COPYING;md5=b2e941b2872bb8566f505130d6d61ba4 \
"
SRC_URI = " \
    ${SOURCEFORGE_MIRROR}/project/clucene/${BPN}-unstable/2.3/${BPN}-${PV}.tar.gz \
    file://0001-cmake-remplace-CHECK_CXX_SOURCE_RUNS-by-CHECK_CXX_SO.patch \
    file://0002-exclude-external-sources-from-build.patch \
    file://0003-align-pkg-config.patch \
    file://0004-fix-location-s-for-our-cmake-config.patch \
    file://0005-install-contribs-lib.patch \
"
SRC_URI[md5sum] = "48d647fbd8ef8889e5a7f422c1bfda94"
SRC_URI[sha256sum] = "ddfdc433dd8ad31b5c5819cc4404a8d2127472a3b720d3e744e8c51d79732eab"

inherit cmake

DEPENDS = "boost zlib"

EXTRA_OECMAKE = "-DENABLE_COMPILE_TESTS=OFF -DBUILD_CONTRIBS_LIB=ON"

FILES_${PN}-dev += "${libdir}/cmake"

BBCLASSEXTEND = "native"

repository: OSSystems/meta-office

repo_name: OSSystems/meta-office


text:
@inproceedings{minah2019spatiotemporal,
 author = {Lee, Minah and Mudassar, Burhan A and Na, Taesik and Mukhopadhyay, Saibal},
 booktitle = {British Machine Vision Conference (BMVC)},
 title = {A Spatiotemporal Pre-processing Network for Activity Recognition Under Rain},
 year = {2019}
}

repository: burhanmudassar/burhanmudassar

repo_name: burhanmudassar/burhanmudassar


text:
file(REMOVE_RECURSE
  "CMakeFiles/cuckoofilter_master.dir/benchmarks/bulk-insert-and-query.cc.o"
  "CMakeFiles/cuckoofilter_master.dir/benchmarks/conext-figure5.cc.o"
  "CMakeFiles/cuckoofilter_master.dir/benchmarks/conext-table3.cc.o"
  "CMakeFiles/cuckoofilter_master.dir/example/test.cc.o"
  "CMakeFiles/cuckoofilter_master.dir/src/hashutil.cc.o"
  "CMakeFiles/cuckoofilter_master.dir/src/printutil.cc.o"
  "cuckoofilter_master.pdb"
  "cuckoofilter_master"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/cuckoofilter_master.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()

repository: Wangfeiyue/BCF

repo_name: Wangfeiyue/BCF


text:
@book{cormen_introduction_2009,
	address = {Cambridge, MA, USA},
	title = {Introduction to algorithms},
	publisher = {MIT Press},
	author = {Cormen, Thomas H. and Leiserson, Charles E. and Rivest, Ronald L. and Stein, Clifford},
	year = {2009}
}

@book{zipf_human_1949,
	address = {Cambridge, MA, USA},
	title = {Human behavior and the principle of least effort},
	publisher = {Addison-Wesley Press},
	author = {Zipf, George Kingsley},
	year = {1949}
}

@misc{weide2014carnegie,
  title={The Carnegie mellon pronouncing dictionary [cmudict. 0.7b]},
  author={Weide, Robert},
  year={2014},
  publisher={Carnegie Mellon University: http://www.speech.cs.cmu.edu/cgi-bin/cmudict.}
}

@article{marslen-wilson_temporal_1980,
	title = {The temporal structure of spoken language understanding},
	volume = {8},
	issn = {0010-0277},
	url = {http://www.sciencedirect.com/science/article/pii/0010027780900153},
	doi = {10.1016/0010-0277(80)90015-3},
	abstract = {The word-by-word time-course of spoken language understanding was investigated in two experiments, focussing simultaneously on word-recognition (local) processes and on structural and interpretative (global) processes. Both experiments used three word-monitoring tasks, which varied the description under which the word-target was monitored for (phonetic, semantic, or both) and three different prose contexts (normal, semantically anomalous, and scrambled), as well as distributing word-targets across nine word-positions in the test-sentences. The presence or absence of a context sentence, varied across the two experiments, allowed an estimate of between-sentence effects on local and global processes. The combined results, presenting a detailed picture of the temporal structuring of these various processes, provided evidence for an on-line interactive language processing theory, in which lexical, structural (syntactic), and interpretative knowledge sources communicate and interact during processing in an optimally efficient and accurate manner.
Résumé
On présente deux expériences faites pour étudier la compréhension du langage parlé en fonction du parcours temporel dans la chaîne. La recherche a porté à la fois sur les processus (locaux) de reconnaissance des mots et sur les processus structuraux et interprétatifs (globaux). Dans chacune des expériences on a utilisé trois tâches de détection de mots. Ces tâches se distinguaient par la qualification sous laquelle le mot á détecter était décrit (phonétique, sémantique oú les deux) et par trois contextes différents (normal, sémantiquement anormal oú brouillé). D'autre part les mots cibles se distribuaient selon neuf positions dans les phrase-tests. La présence oú l'absence d'un contexte phrastique permettait une estimation des effects inter-phrases sur les processus locaux et globaux. L'ensemble des résultats donnent une image détaillé de la structuration temporelle des différents processus. L'hypothése d'un calcul du langage interactif en temps réel est favorisée. Selon cette hypothése, durant le traitement, les diverses sources de connaissance, lexicales, structurales (syntaxiques) et interprétatives communiquent et interagissent d'une façon maximalement précise et efficace.},
	number = {1},
	urldate = {2019-09-30},
	journal = {Cognition},
	author = {Marslen-Wilson, William and Tyler, Lorraine Komisarjevsky},
	month = jan,
	year = {1980},
	pages = {1--71},
	file = {Marslen-Wilson_Tyler_1980_The temporal structure of spoken language understanding.pdf:/home/matt/Dropbox/Zotero/Marslen-Wilson_Tyler_1980_The temporal structure of spoken language understanding.pdf:application/pdf;ScienceDirect Snapshot:/home/matt/Zotero/storage/2P4FLSGG/0010027780900153.html:text/html}
}

@article{marslen-wilson_processing_1978,
	title = {Processing interactions and lexical access during word recognition in continuous speech},
	volume = {10},
	issn = {0010-0285},
	url = {http://www.sciencedirect.com/science/article/pii/001002857890018X},
	doi = {10.1016/0010-0285(78)90018-X},
	abstract = {The interactions, during word-recognition in continuous speech, between the bottom-up analyses of the input and different forms of internally generated top-down constraint, were investigated using a shadowing task and a mispronunciation detection task (in the detection task the subject saw a text of the original passage as he listened to it). The listener's dependence on bottom-up analyses in the shadowing task, as measured by the number of fluent restorations of mispronounced words, was found to vary as a function of the syllable position of the mispronunciation within the word and of the contextual constraints on the word as a whole. In the detection task only syllable position effects were obtained. The results, discussed in conjunction with earlier research, were found to be inconsistent with either the logogen model of word-recognition or an autonomous search model. Instead, an active direct access model is proposed, in which top-down processing constraints interact directly with bottom-up information to produce the primary lexical interpretation of the acoustic-phonetic input.},
	number = {1},
	urldate = {2019-09-30},
	journal = {Cognitive Psychology},
	author = {Marslen-Wilson, William D and Welsh, Alan},
	month = jan,
	year = {1978},
	pages = {29--63},
	file = {Marslen-Wilson_Welsh_1978_Processing interactions and lexical access during word recognition in.pdf:/home/matt/Dropbox/Zotero/Marslen-Wilson_Welsh_1978_Processing interactions and lexical access during word recognition in.pdf:application/pdf;ScienceDirect Snapshot:/home/matt/Zotero/storage/894UB5PG/001002857890018X.html:text/html}
}

@book{eddington_philosophy_1939,
  title={The philosophy of physical science: Tarner Lectures 1938},
  author={Eddington, Arthur Stanley},
  place={New York},
  year={1939},
  publisher={Cambridge University Press}
}

@book{silk_shores_2005,
  title={On the shores of the unknown: a short history of the universe},
  author={Silk, Joseph},
  year={2005},
  publisher={Cambridge University Press}
}

repository: maetshju/prefix-length-zipf

repo_name: maetshju/prefix-length-zipf


text:
/*
Copyright 2019 The HAProxy Ingress Controller Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package haproxy

import (
	"fmt"
	"os"
	"reflect"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/jcmoraisjr/haproxy-ingress/pkg/haproxy/socket"
	hatypes "github.com/jcmoraisjr/haproxy-ingress/pkg/haproxy/types"
	"github.com/jcmoraisjr/haproxy-ingress/pkg/types"
)

type dynUpdater struct {
	logger  types.Logger
	config  *config
	socket  socket.HAProxySocket
	cmdCnt  int
	metrics types.Metrics
}

type hostPair struct {
	old *hatypes.Host
	cur *hatypes.Host
}

type backendPair struct {
	old *hatypes.Backend
	cur *hatypes.Backend
}

type epPair struct {
	old *hatypes.Endpoint
	cur *hatypes.Endpoint
}

func (i *instance) newDynUpdater() *dynUpdater {
	return &dynUpdater{
		logger:  i.logger,
		config:  i.config.(*config),
		socket:  i.conns.DynUpdate(),
		metrics: i.metrics,
	}
}

func (d *dynUpdater) update() bool {
	updated := d.config.hasCommittedData() && d.checkConfigChange()
	if !updated {
		// Need to reload, time to adjust empty slots according to config
		d.alignSlots()
	}
	return updated
}

// checkConfigChange defines if dynamic update was successfully applied.
// The updated host and backend lists are fully verified even if a restart
// should be made in order to leave haproxy as update as possible if a
// reload fails.
func (d *dynUpdater) checkConfigChange() bool {
	// TODO use two steps update and perform full dynamic update only if the reload failed.

	var diff []string
	if d.config.globalOld != nil && !reflect.DeepEqual(d.config.globalOld, d.config.global) {
		diff = append(diff, "global")
	}
	if d.config.tcpbackends.Changed() {
		diff = append(diff, "tcp-services (configmap)")
	}
	if d.config.tcpservices.Changed() {
		diff = append(diff, "tcp-services")
	}
	if d.config.frontend.Changed() {
		diff = append(diff, "frontend")
	}
	if d.config.userlists.Changed() {
		diff = append(diff, "userlists")
	}
	if !d.frontendUpdated() {
		diff = append(diff, "hosts")
	}
	if !d.backendUpdated() {
		diff = append(diff, "backends")
	}
	if len(diff) > 0 {
		d.logger.InfoV(2, "need to reload due to config changes: %v", diff)
		return false
	}
	return true
}

func (d *dynUpdater) frontendUpdated() bool {
	updated := true

	hosts := make(map[string]*hostPair, len(d.config.hosts.ItemsDel()))
	for _, host := range d.config.hosts.ItemsDel() {
		hosts[host.Hostname] = &hostPair{old: host}
	}
	for _, host := range d.config.hosts.ItemsAdd() {
		id := host.Hostname
		h, found := hosts[id]
		if !found {
			d.logger.InfoV(2, "added host '%s'", id)
			updated = false
		} else {
			h.cur = host
		}
	}

	for _, pair := range hosts {
		if pair.cur == nil {
			d.logger.InfoV(2, "removed host '%s'", pair.old.Hostname)
			updated = false
		} else if !d.checkHostPair(pair) {
			updated = false
		}
	}

	return updated
}

func (d *dynUpdater) backendUpdated() bool {
	updated := true

	// group reusable backends together
	// return false on new backend which cannot be dynamically created
	backends := make(map[string]*backendPair, len(d.config.backends.ItemsDel()))
	for _, backend := range d.config.backends.ItemsDel() {
		backends[backend.BackendID().String()] = &backendPair{old: backend}
	}
	for _, backend := range d.config.backends.ItemsAdd() {
		id := backend.BackendID().String()
		back, found := backends[id]
		if !found {
			d.logger.InfoV(2, "added backend '%s'", id)
			updated = false
		} else {
			back.cur = backend
		}
	}

	// try to dynamically update every single backend
	// true if deep equals or successfully updated
	// false if cannot be dynamically updated or update failed
	for _, pair := range backends {
		if pair.cur != nil && !d.checkBackendPair(pair) {
			updated = false
		}
	}

	return updated
}

func (d *dynUpdater) checkHostPair(pair *hostPair) bool {
	oldHost := pair.old
	curHost := pair.cur

	updated := true

	// check equality of everything but server certificate
	// TODO move this check to the host type
	oldHostCopy := *oldHost
	oldHostCopy.TLS.TLSCommonName = curHost.TLS.TLSCommonName
	oldHostCopy.TLS.TLSHash = curHost.TLS.TLSHash
	oldHostCopy.TLS.TLSNotAfter = curHost.TLS.TLSNotAfter
	if !reflect.DeepEqual(&oldHostCopy, curHost) {
		d.logger.InfoV(2, "diff outside server certificate of host '%s'", curHost.Hostname)
		updated = false
	}

	if curHost.TLS.HasTLS() && oldHost.TLS.TLSHash != curHost.TLS.TLSHash &&
		oldHost.TLS.TLSFilename == curHost.TLS.TLSFilename &&
		!d.execUpdateCert(curHost.Hostname, curHost.TLS.TLSFilename) {
		updated = false
	}

	return updated
}

func (d *dynUpdater) checkBackendPair(pair *backendPair) bool {
	oldBack := pair.old
	curBack := pair.cur

	// Track if dynamic update was successfully applied.
	// Socket updates will continue to be applied even if updated
	// is false, so haproxy will stay as updated as possible even
	// if a reload fail
	updated := true

	// check equality of everything but endpoints
	// TODO move this check to the backend type
	oldBackCopy := *oldBack
	oldBackCopy.ID = curBack.ID
	oldBackCopy.Dynamic = curBack.Dynamic
	oldBackCopy.Endpoints = curBack.Endpoints
	if !reflect.DeepEqual(&oldBackCopy, curBack) {
		d.logger.InfoV(2, "diff outside endpoints of backend '%s'", curBack.ID)
		updated = false
	}

	// can decrease endpoints, cannot increase
	if len(oldBack.Endpoints) < len(curBack.Endpoints) {
		d.logger.InfoV(2, "added endpoints on backend '%s'", curBack.ID)
		// cannot continue -- missing empty slots in the backend
		return false
	}

	// Resolver == update via DNS discovery
	if curBack.Resolver != "" {
		if updated {
			// DNS based updates finishes prematurely. Ensure the ep
			// list size of the new one is at least as big as the old one.
			for i := len(curBack.Endpoints); i < len(oldBack.Endpoints); i++ {
				curBack.AddEmptyEndpoint()
			}
		}
		return updated
	}

	// DynUpdate is disabled, check if differs and quit
	// TODO check if endpoints are the same and only the order differ
	if !curBack.Dynamic.DynUpdate {
		if updated && !reflect.DeepEqual(oldBack.Endpoints, curBack.Endpoints) {
			d.logger.InfoV(2, "backend '%s' changed and its dynamic-scaling is 'false'", curBack.ID)
			return false
		}
		return updated
	}

	// map endpoints of old and new config together
	endpoints := make(map[string]*epPair, len(oldBack.Endpoints))
	targets := make([]string, 0, len(oldBack.Endpoints))
	var empty []*hatypes.Endpoint
	for _, endpoint := range oldBack.Endpoints {
		if endpoint.Enabled {
			endpoints[endpoint.Target] = &epPair{old: endpoint}
			targets = append(targets, endpoint.Target)
		} else {
			empty = append(empty, endpoint)
		}
	}

	// reuse the backend/server which has the same target endpoint, if found,
	// this will save some socket calls and will not mess endpoint metrics
	var added []*hatypes.Endpoint
	for _, endpoint := range curBack.Endpoints {
		if pair, found := endpoints[endpoint.Target]; found {
			pair.cur = endpoint
			pair.cur.Name = pair.old.Name
		} else {
			added = append(added, endpoint)
		}
	}

	// Try to dynamically remove/update/add endpoints.
	// Targets being used here only to have predictable results (tests).
	// Endpoint.Label != "" means use-server of blue/green config, need reload
	sort.Strings(targets)
	for _, target := range targets {
		pair := endpoints[target]
		if pair.cur == nil && len(added) > 0 {
			pair.cur = added[0]
			pair.cur.Name = pair.old.Name
			added = added[1:]
		}
		if pair.cur == nil {
			if !d.execDisableEndpoint(curBack.ID, pair.old) || pair.old.Label != "" {
				updated = false
			}
			empty = append(empty, pair.old)
		} else if !d.checkEndpointPair(curBack, pair) {
			updated = false
		}
	}
	for i := range added {
		// reusing empty slots from oldBack
		added[i].Name = empty[i].Name
		if curBack.Cookie.Preserve && added[i].CookieValue != empty[i].CookieValue {
			// if cookie doesn't match here and preserving the value is
			// important, don't even enable the endpoint before reloading
			updated = false
		} else if !d.execEnableEndpoint(curBack.ID, nil, added[i]) || added[i].Label != "" {
			updated = false
		}
	}

	// copy remaining empty slots from oldBack to curBack, so it can be used in a future update
	for i := len(added); i < len(empty); i++ {
		curBack.AddEmptyEndpoint().Name = empty[i].Name
	}

	return updated
}

func (d *dynUpdater) checkEndpointPair(backend *hatypes.Backend, pair *epPair) bool {
	oldEPCopy := *pair.old
	// SourceIP is lazily updated via FillSourceIPs() after dynupdate run
	// A reload is already scheduled due to backend.SourceIPs changed
	oldEPCopy.SourceIP = pair.cur.SourceIP
	if reflect.DeepEqual(&oldEPCopy, pair.cur) {
		return true
	}
	if backend.Cookie.Preserve && pair.old.CookieValue != pair.cur.CookieValue {
		// if cookie doesn't match here and preserving the value is
		// important, don't even enable the endpoint before reloading
		return false
	}
	updated := d.execEnableEndpoint(backend.ID, pair.old, pair.cur)
	if !updated || pair.old.Label != "" || pair.cur.Label != "" {
		return false
	}
	return true
}

func (d *dynUpdater) alignSlots() {
	backends := d.config.Backends()
	for _, back := range backends.Items() {
		if !back.Dynamic.DynUpdate {
			// no need to add empty slots if won't dynamically update
			continue
		}
		minFreeSlots := back.Dynamic.MinFreeSlots
		blockSize := back.Dynamic.BlockSize
		if blockSize < 1 {
			blockSize = 1
		}
		var newFreeSlots int
		changed := false
		if minFreeSlots == 0 && len(back.Endpoints) == 0 {
			newFreeSlots = blockSize
		} else {
			totalFreeSlots := 0
			for _, ep := range back.Endpoints {
				if ep.IsEmpty() {
					totalFreeSlots++
				}
			}
			for i := totalFreeSlots; i < minFreeSlots; i++ {
				back.AddEmptyEndpoint()
				changed = true
			}
			// * []endpoints == group of blocks
			// * block == group of slots
			// * slot == a single server
			// newFreeSlots := blockSize - (1 <= <size-of-last-block> <= blockSize)
			newFreeSlots = blockSize - (((len(back.Endpoints) + blockSize - 1) % blockSize) + 1)
		}
		for i := 0; i < newFreeSlots; i++ {
			back.AddEmptyEndpoint()
			changed = true
		}
		if changed {
			// backends from the Items() map are read only and their changes might not be
			// reflected in the final configuration. Currently only sharded backends have
			// this behavior but this can be expanded to another scenarios in the future,
			// so this should be properly handled by the model.
			//
			// TODO move to the model the responsibility to know that a backend was changed.
			backends.BackendChanged(back)
		}
	}
}

var readFile = os.ReadFile

func (d *dynUpdater) execUpdateCert(hostname, filename string) bool {
	// TODO read from the internal storage
	payload, err := readFile(filename)
	if err != nil {
		d.logger.Error("error reading certificate file for %s: %v", hostname, err)
		return false
	}
	// TODO removing an empty line between crt and key, runtime api didn't like it.
	// Remove this work around after the factoring of the ssl storage.
	payloadStr := strings.ReplaceAll(string(payload), "\n\n", "\n")
	cmd := []string{
		fmt.Sprintf("set ssl cert %s <<\n%s\n", filename, payloadStr),
		fmt.Sprintf("commit ssl cert %s", filename),
	}
	msg, err := d.execCommand(d.metrics.HAProxySetSSLCertResponseTime, cmd)
	if err != nil {
		d.logger.Error("error updating certificate for %s: %v", hostname, err)
		return false
	}
	for _, m := range msg {
		if m != "" {
			outmsg := strings.ReplaceAll(strings.TrimRight(m, "\n"), "\n", " \\\\ ")
			d.logger.InfoV(2, "response from server: %s", outmsg)
		}
	}
	if !cmdResponseOK("commit ssl cert", msg[1]) {
		d.logger.Warn("cannot update certificate for %s", hostname)
		return false
	}
	d.logger.Info("certificate updated for %s", hostname)
	return true
}

func (d *dynUpdater) execDisableEndpoint(backname string, ep *hatypes.Endpoint) bool {
	server := fmt.Sprintf("set server %s/%s ", backname, ep.Name)
	cmd := []string{
		server + "state maint",
		server + "addr 127.0.0.1 port 1023",
		server + "weight 0",
	}
	msg, err := d.execCommand(d.metrics.HAProxySetServerResponseTime, cmd)
	if err != nil {
		d.logger.Error("error disabling endpoint %s/%s: %v", backname, ep.Name, err)
		return false
	}
	for _, m := range msg {
		if m != "" {
			if !cmdResponseOK("set server", m) {
				d.logger.Warn("unrecognized response disabling endpoint %s/%s: %s", backname, ep.Name, m)
				return false
			}
			d.logger.InfoV(2, "response from server: %s", m)
		}
	}
	d.logger.InfoV(2, "disabled endpoint '%s' on backend/server '%s/%s'", ep.Target, backname, ep.Name)
	return true
}

func (d *dynUpdater) execEnableEndpoint(backname string, oldEP, curEP *hatypes.Endpoint) bool {
	state := map[bool]string{true: "ready", false: "drain"}[curEP.Weight > 0]
	server := fmt.Sprintf("set server %s/%s ", backname, curEP.Name)
	cmd := []string{
		server + "addr " + curEP.IP + " port " + strconv.Itoa(curEP.Port),
		server + "state " + state,
		server + "weight " + strconv.Itoa(curEP.Weight),
	}
	msg, err := d.execCommand(d.metrics.HAProxySetServerResponseTime, cmd)
	if err != nil {
		d.logger.Error("error adding/updating endpoint %s/%s: %v", backname, curEP.Name, err)
		return false
	}
	for _, m := range msg {
		if m != "" {
			if !cmdResponseOK("set server", m) {
				d.logger.Warn("unrecognized response adding/updating endpoint %s/%s: %s", backname, curEP.Name, m)
				return false
			}
			d.logger.InfoV(2, "response from server: %s", m)
		}
	}
	event := map[bool]string{true: "updated", false: "added"}[oldEP != nil]
	d.logger.InfoV(2, "%s endpoint '%s' weight '%d' state '%s' on backend/server '%s/%s'",
		event, curEP.Target, curEP.Weight, state, backname, curEP.Name)
	return true
}

func (d *dynUpdater) execCommand(observer func(duration time.Duration), cmd []string) ([]string, error) {
	msg, err := d.socket.Send(observer, cmd...)
	d.cmdCnt = d.cmdCnt + len(cmd)
	return msg, err
}

func cmdResponseOK(cmd, response string) bool {
	switch cmd {
	case "set server":
		return response == "" || strings.HasPrefix(response, "IP changed from ") || strings.HasPrefix(response, "no need to change ")
	case "commit ssl cert":
		return strings.Contains(response, "Success")
	default:
		panic(fmt.Errorf("invalid cmd: %s", cmd))
	}
}

repository: jcmoraisjr/haproxy-ingress

repo_name: jcmoraisjr/haproxy-ingress


text:
package actions

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"yac-go/log"
	"yac-go/model/note"
	service "yac-go/service/note"
)

func GetAllNotes(ctx *gin.Context) {
	db := GetDepsFromCtx(ctx).Db

	_, full := ctx.GetQuery("full")
	bookId, _ := ctx.GetQuery("book")

	if full || bookId != "" {
		notes, err := service.GetAll(db, bookId)
		if err != nil {
			log.Panic("Error while loading all notes:", err)
		}
		ctx.JSON(http.StatusOK, notes)
		return
	}

	notes, err := service.GetAllIds(db)
	if err != nil {
		log.Panic("Error while loading all notes:", err)
	}
	ctx.JSON(http.StatusOK, notes)
}

func PostNewNode(ctx *gin.Context) {
	db := GetDepsFromCtx(ctx).Db

	n := &note.Note{}
	if err := ctx.ShouldBindJSON(n); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	id, otherId, err := service.Add(db, n)
	if id == 0 && otherId == 0 && err != nil {
		log.Panic("Insert error:", err)
	}

	if id == 0 && otherId != 0 {
		ctx.JSON(http.StatusPreconditionFailed, gin.H{"error": err.Error(), "id": otherId})
		return
	}

	ctx.JSON(http.StatusCreated, gin.H{"id": id, "note": n})
}

func GetNote(ctx *gin.Context) {
	nid, err := strconv.Atoi(ctx.Param("id"))
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	db := GetDepsFromCtx(ctx).Db

	n, err := service.GetById(db, nid)
	if err != nil {
		ctx.Status(http.StatusNotFound)
		return
	}

	ctx.JSON(http.StatusOK, n)
}

func GetQueryNote(ctx *gin.Context) {
	db := GetDepsFromCtx(ctx).Db

	rawDay := ctx.Param("day")
	rawMonth := ctx.Param("month")
	rawYear := ctx.Param("year")

	bookId := ctx.Query("book")

	day, err := strconv.Atoi(rawDay)
	if err != nil {
		day = 0
	}
	month, err := strconv.Atoi(rawMonth)
	if err != nil {
		month = 0
	}
	year, err := strconv.Atoi(rawYear)
	if err != nil {
		year = 0
	}

	notes, err := service.Query(db, year, month, day, bookId)
	if err != nil {
		log.Panic("Failed to query for notes:", err)
	}

	ctx.JSON(http.StatusOK, notes)
}

func DeleteNote(ctx *gin.Context) {
	db := GetDepsFromCtx(ctx).Db

	id, err := strconv.Atoi(ctx.Param("id"))
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if err = service.DeleteById(db, id); err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
		return
	}

	ctx.Status(http.StatusOK)
}

repository: yacnotes/yac-go

repo_name: yacnotes/yac-go


text:
package vote

import (
	sdk "github.com/cosmos/cosmos-sdk/types"

	"github.com/lino-network/lino/param"
	linotypes "github.com/lino-network/lino/types"
	"github.com/lino-network/lino/x/vote/model"
	"github.com/lino-network/lino/x/vote/types"
)

// VoteManager - vote manager
type VoteManager struct {
	storage     model.VoteStorage
	paramHolder param.ParamHolder
}

func NewVoteManager(key sdk.StoreKey, holder param.ParamHolder) VoteManager {
	return VoteManager{
		storage:     model.NewVoteStorage(key),
		paramHolder: holder,
	}
}

// InitGenesis - initialize KV Store
func (vm VoteManager) InitGenesis(ctx sdk.Context) error {
	if err := vm.storage.InitGenesis(ctx); err != nil {
		return err
	}
	return nil
}

// DoesVoterExist - check if voter exist or not
func (vm VoteManager) DoesVoterExist(ctx sdk.Context, accKey linotypes.AccountKey) bool {
	return vm.storage.DoesVoterExist(ctx, accKey)
}

// DoesVoterExist - check if vote exist or not
func (vm VoteManager) DoesVoteExist(ctx sdk.Context, proposalID linotypes.ProposalKey, accKey linotypes.AccountKey) bool {
	return vm.storage.DoesVoteExist(ctx, proposalID, accKey)
}

// DoesVoterExist - check if delegation exist or not
func (vm VoteManager) DoesDelegationExist(ctx sdk.Context, voter linotypes.AccountKey, delegator linotypes.AccountKey) bool {
	return vm.storage.DoesDelegationExist(ctx, voter, delegator)
}

// DoesVoterExist - check if a voter is validator or not
func (vm VoteManager) IsInValidatorList(ctx sdk.Context, username linotypes.AccountKey) bool {
	lst, err := vm.storage.GetReferenceList(ctx)
	if err != nil {
		return false
	}
	for _, validator := range lst.AllValidators {
		if validator == username {
			return true
		}
	}
	return false
}

// IsLegalVoterWithdraw - check withdraw voter is not validator
func (vm VoteManager) IsLegalVoterWithdraw(
	ctx sdk.Context, username linotypes.AccountKey, coin linotypes.Coin) bool {
	voter, err := vm.storage.GetVoter(ctx, username)
	if err != nil {
		return false
	}
	// reject if this is a validator
	if vm.IsInValidatorList(ctx, username) {
		return false
	}

	availableStakes := voter.LinoStake.Minus(voter.DelegateToOthers)
	//reject if the remaining coins are not enough
	return availableStakes.IsGTE(coin) && coin.IsPositive()
}

// IsLegalDelegatorWithdraw - check if delegator withdraw is valid or not
func (vm VoteManager) IsLegalDelegatorWithdraw(
	ctx sdk.Context, voterName linotypes.AccountKey, delegatorName linotypes.AccountKey, coin linotypes.Coin) bool {
	delegation, err := vm.storage.GetDelegation(ctx, voterName, delegatorName)
	if err != nil {
		return false
	}

	//reject if the remaining delegation are less than zero
	return delegation.Amount.IsGTE(coin) && coin.IsPositive()
}

// CanBecomeValidator - check if vote deposit meet requirement or not
func (vm VoteManager) CanBecomeValidator(ctx sdk.Context, username linotypes.AccountKey) bool {
	voter, err := vm.storage.GetVoter(ctx, username)
	if err != nil {
		return false
	}
	param, err := vm.paramHolder.GetValidatorParam(ctx)
	if err != nil {
		return false
	}
	// check minimum voting deposit for validator
	return voter.LinoStake.IsGTE(param.ValidatorMinVotingDeposit)
}

// AddVote - voter vote for a proposal
func (vm VoteManager) AddVote(ctx sdk.Context, proposalID linotypes.ProposalKey, voter linotypes.AccountKey, res bool) sdk.Error {
	// check if the vote exist
	if vm.DoesVoteExist(ctx, proposalID, voter) {
		return ErrVoteAlreadyExist()
	}

	votingPower, err := vm.GetVotingPower(ctx, voter)
	if err != nil {
		return err
	}

	vote := model.Vote{
		Voter:       voter,
		Result:      res,
		VotingPower: votingPower,
	}

	if err := vm.storage.SetVote(ctx, proposalID, voter, &vote); err != nil {
		return err
	}
	return nil
}

// GetVote - get vote detail based on voter and proposal ID
func (vm VoteManager) GetVote(ctx sdk.Context, proposalID linotypes.ProposalKey, voter linotypes.AccountKey) (*model.Vote, sdk.Error) {
	return vm.storage.GetVote(ctx, proposalID, voter)
}

// AddDelegation - add delegation
func (vm VoteManager) AddDelegation(ctx sdk.Context, voterName linotypes.AccountKey, delegatorName linotypes.AccountKey, coin linotypes.Coin) sdk.Error {
	var delegation *model.Delegation
	var err sdk.Error

	if !vm.DoesDelegationExist(ctx, voterName, delegatorName) {
		delegation = &model.Delegation{
			Delegator: delegatorName,
			Amount:    linotypes.NewCoinFromInt64(0),
		}
	} else {
		delegation, err = vm.storage.GetDelegation(ctx, voterName, delegatorName)
		if err != nil {
			return err
		}
	}

	// add voter if not exist
	if !vm.DoesVoterExist(ctx, voterName) {
		if err := vm.AddVoter(ctx, voterName, linotypes.NewCoinFromInt64(0)); err != nil {
			return err
		}
	}

	// add delegatedPower for voter
	voter, err := vm.storage.GetVoter(ctx, voterName)
	if err != nil {
		return err
	}
	voter.DelegatedPower = voter.DelegatedPower.Plus(coin)
	// add delegateToOthers for delegator
	delegator, err := vm.storage.GetVoter(ctx, delegatorName)
	if err != nil {
		return err
	}
	delegator.DelegateToOthers = delegator.DelegateToOthers.Plus(coin)

	delegation.Amount = delegation.Amount.Plus(coin)

	if err := vm.storage.SetDelegation(ctx, voterName, delegatorName, delegation); err != nil {
		return err
	}
	if err := vm.storage.SetVoter(ctx, voterName, voter); err != nil {
		return err
	}
	if err := vm.storage.SetVoter(ctx, delegatorName, delegator); err != nil {
		return err
	}
	return nil
}

// AddVoter - add voter
func (vm VoteManager) AddVoter(ctx sdk.Context, username linotypes.AccountKey, coin linotypes.Coin) sdk.Error {
	voter := &model.Voter{
		Username:          username,
		LinoStake:         coin,
		LastPowerChangeAt: ctx.BlockHeader().Time.Unix(),
	}

	if err := vm.storage.SetVoter(ctx, username, voter); err != nil {
		return err
	}
	return nil
}

// AddLinoStake - add lino power
func (vm VoteManager) AddLinoStake(ctx sdk.Context, username linotypes.AccountKey, coin linotypes.Coin) sdk.Error {
	voter, err := vm.storage.GetVoter(ctx, username)
	if err != nil {
		return err
	}
	voter.LinoStake = voter.LinoStake.Plus(coin)
	voter.LastPowerChangeAt = ctx.BlockHeader().Time.Unix()
	if err := vm.storage.SetVoter(ctx, username, voter); err != nil {
		return err
	}
	return nil
}

// MinusLinoStake - this method won't check if it is a legal withdraw, caller should check by itself
func (vm VoteManager) MinusLinoStake(ctx sdk.Context, username linotypes.AccountKey, coin linotypes.Coin) sdk.Error {
	if coin.IsZero() {
		return ErrInvalidCoin()
	}
	voter, err := vm.storage.GetVoter(ctx, username)
	if err != nil {
		return err
	}
	voter.LinoStake = voter.LinoStake.Minus(coin)
	voter.LastPowerChangeAt = ctx.BlockHeader().Time.Unix()
	if err := vm.storage.SetVoter(ctx, username, voter); err != nil {
		return err
	}
	return nil
}

// DelegatorWithdraw - withdraw delegation
func (vm VoteManager) DelegatorWithdraw(
	ctx sdk.Context, voterName linotypes.AccountKey, delegatorName linotypes.AccountKey, coin linotypes.Coin) sdk.Error {
	if coin.IsZero() {
		return ErrInvalidCoin()
	}
	// change voter's delegated power
	voter, err := vm.storage.GetVoter(ctx, voterName)
	if err != nil {
		return err
	}
	voter.DelegatedPower = voter.DelegatedPower.Minus(coin)
	if err := vm.storage.SetVoter(ctx, voterName, voter); err != nil {
		return err
	}

	// change delegator's delegateToOthers
	delegator, err := vm.storage.GetVoter(ctx, delegatorName)
	if err != nil {
		return err
	}
	delegator.DelegateToOthers = delegator.DelegateToOthers.Minus(coin)
	if err := vm.storage.SetVoter(ctx, delegatorName, delegator); err != nil {
		return err
	}

	// change this delegation's amount
	delegation, err := vm.storage.GetDelegation(ctx, voterName, delegatorName)
	if err != nil {
		return err
	}
	delegation.Amount = delegation.Amount.Minus(coin)

	if delegation.Amount.IsZero() {
		if err := vm.storage.DeleteDelegation(ctx, voterName, delegatorName); err != nil {
			return err
		}
	} else {
		vm.storage.SetDelegation(ctx, voterName, delegatorName, delegation)
	}

	return nil
}

// ClaimInterest - add lino power interst to user balance
func (vm VoteManager) ClaimInterest(
	ctx sdk.Context, username linotypes.AccountKey) (linotypes.Coin, sdk.Error) {
	voter, err := vm.storage.GetVoter(ctx, username)
	if err != nil {
		return linotypes.NewCoinFromInt64(0), err
	}
	claimedInterest := voter.Interest
	voter.Interest = linotypes.NewCoinFromInt64(0)
	if err := vm.storage.SetVoter(ctx, username, voter); err != nil {
		return linotypes.NewCoinFromInt64(0), err
	}
	return claimedInterest, nil
}

// AddInterest - add interst
func (vm VoteManager) AddInterest(
	ctx sdk.Context, username linotypes.AccountKey, interest linotypes.Coin) sdk.Error {
	voter, err := vm.storage.GetVoter(ctx, username)
	if err != nil {
		return err
	}
	voter.Interest = voter.Interest.Plus(interest)
	if err := vm.storage.SetVoter(ctx, username, voter); err != nil {
		return err
	}
	return nil
}

// GetVotingPower - get voter voting power
func (vm VoteManager) GetVotingPower(ctx sdk.Context, voterName linotypes.AccountKey) (linotypes.Coin, sdk.Error) {
	voter, err := vm.storage.GetVoter(ctx, voterName)
	if err != nil {
		return linotypes.Coin{}, err
	}
	res := voter.LinoStake.Plus(voter.DelegatedPower).Minus(voter.DelegateToOthers)
	return res, nil
}

// GetPenaltyList - get penalty list if voter is also validator doesn't vote
func (vm VoteManager) GetPenaltyList(
	ctx sdk.Context, proposalID linotypes.ProposalKey, proposalType linotypes.ProposalType,
	oncallValidators []linotypes.AccountKey) (linotypes.PenaltyList, sdk.Error) {
	penaltyList := linotypes.PenaltyList{
		PenaltyList: []linotypes.AccountKey{},
	}

	// get all votes to calculate the voting result
	votes, err := vm.storage.GetAllVotes(ctx, proposalID)
	if err != nil {
		return penaltyList, err
	}

	for _, vote := range votes {
		// remove from list if the validator voted
		for idx, validator := range oncallValidators {
			if validator == vote.Voter {
				oncallValidators = append(oncallValidators[:idx], oncallValidators[idx+1:]...)
				break
			}
		}
		// TODO: Decide if we wanna delete vote.
		// vm.storage.DeleteVote(ctx, proposalID, vote.Voter)
	}

	// put all validators who didn't vote on these two linotypes.proposal into penalty list
	if proposalType == linotypes.ChangeParam || proposalType == linotypes.ProtocolUpgrade {
		penaltyList.PenaltyList = oncallValidators
	}
	return penaltyList, nil
}

// GetLinoStake - get lino stake
func (vm VoteManager) GetLinoStake(ctx sdk.Context, accKey linotypes.AccountKey) (linotypes.Coin, sdk.Error) {
	voter, err := vm.storage.GetVoter(ctx, accKey)
	if err != nil {
		return linotypes.NewCoinFromInt64(0), err
	}
	return voter.LinoStake, nil
}

// GetLinoStakeLastChangedAt - get linoStake last changed time
func (vm VoteManager) GetLinoStakeLastChangedAt(ctx sdk.Context, accKey linotypes.AccountKey) (int64, sdk.Error) {
	voter, err := vm.storage.GetVoter(ctx, accKey)
	if err != nil {
		return 0, err
	}
	return voter.LastPowerChangeAt, nil
}

// SetLinoStakeLastChangedAt - set linoStake last changed time
func (vm VoteManager) SetLinoStakeLastChangedAt(ctx sdk.Context, accKey linotypes.AccountKey, lastChangedAt int64) sdk.Error {
	voter, err := vm.storage.GetVoter(ctx, accKey)
	if err != nil {
		return err
	}
	voter.LastPowerChangeAt = lastChangedAt
	if err := vm.storage.SetVoter(ctx, accKey, voter); err != nil {
		return err
	}
	return nil
}

// GetAllDelegators - get all delegators of a voter
func (vm VoteManager) GetAllDelegators(ctx sdk.Context, voterName linotypes.AccountKey) ([]linotypes.AccountKey, sdk.Error) {
	return vm.storage.GetAllDelegators(ctx, voterName)
}

// GetValidatorReferenceList - get all delegatee
func (vm VoteManager) GetValidatorReferenceList(ctx sdk.Context) (*model.ReferenceList, sdk.Error) {
	return vm.storage.GetReferenceList(ctx)
}

// SetValidatorReferenceList - set validator reference list
func (vm VoteManager) SetValidatorReferenceList(ctx sdk.Context, lst *model.ReferenceList) sdk.Error {
	return vm.storage.SetReferenceList(ctx, lst)
}

func (vm VoteManager) GetVoterDuty(ctx sdk.Context, accKey linotypes.AccountKey) types.VoterDuty {
	panic(linotypes.NewError(linotypes.CodeUnimplementedError, "voter duty unimplemented"))
}

// Export storage state.
func (vm VoteManager) Export(ctx sdk.Context) *model.VoterTables {
	return vm.storage.Export(ctx)
}

// Import storage state.
func (vm VoteManager) Import(ctx sdk.Context, voter *model.VoterTablesIR) {
	vm.storage.Import(ctx, voter)
}

repository: goldfintech/lino

repo_name: goldfintech/lino


text:
SUMMARY = "TI RTOS low level driver for Serial Rapid IO (SRIO)"

inherit ti-pdk

require recipes-bsp/srio-lld/srio-lld.inc

PR = "${INC_PR}.0"

DEPENDS_append = " cppi-lld-rtos \
                   qmss-lld-rtos \
"
COMPATIBLE_MACHINE_append = "|c66x"

PACKAGE_ARCH = "${MACHINE_ARCH}"

# HTML doc link params
PDK_COMP_LINK_TEXT = "SRIO LLD"

repository: bjornwilliam/meta-ti

repo_name: bjornwilliam/meta-ti


text:
#
# This file is the python-webserver recipe.
#

SUMMARY = "Simple python-webserver application"
SECTION = "PETALINUX/apps"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"

COMPATIBLE_MACHINE = "uz|pz"

# Packages
RDEPENDS_${PN} += "\
  python3-core \
  python-core \
    "

SRC_URI = "file://cgi.py \
     file://index.html \
     file://launch_server.sh \
     file://server.py \
     file://setup_gpio.sh \
     file://stop_server.sh \
     file://unexport_gpio.sh \
     file://css/main.css \
     file://html/sata_results.html \
     file://html/usb3_results.html \
     file://images/Avnet_logo_tagline_rgb.png \
     file://images/favicon.ico \
     file://images/board.jpg \
     file://pdfs/Delkin_Devices_Product_Line.pdf \
      "

SRC_URI_append_uz = "\
     file://images/ultrazed.png \
      "

SRC_URI_append_uz3eg-iocc = "\
     file://pdfs/5043-PB-AES-ZU3EG-1-SOM-G-V3.pdf \
     file://pdfs/5080-PB-AES-ZU-IOCC-G-V2e.pdf \
      "
SRC_URI_append_uz3eg-pciec = "\
     file://pdfs/5043-PB-AES-ZU3EG-1-SOM-G-V3.pdf \
     file://pdfs/5081-PB-AES-ZU-PCIECC-G-V2d.pdf \
      "
SRC_URI_append_uz7ev-evcc = "\
     file://pdfs/5342-pb-ultrazed-ev-som-v1.pdf \
     file://pdfs/5342-pb-ultrazed-ev-starter-kit-v1.pdf \
      "

SRC_URI_append_pz = "\
     file://images/picozed.png \
     file://pdfs/5048-PB-PDP-AES-Z7PZ-SOM-G-V2.pdf \
     file://pdfs/PB-AES-PZCC-FMC-V2-G-V1.pdf \
      "

S = "${WORKDIR}"

do_install() {
       install -d ${D}/home/root/webserver
       install -d ${D}/home/root/webserver/css
       install -d ${D}/home/root/webserver/html
       install -d ${D}/home/root/webserver/images
       install -d ${D}/home/root/webserver/pdfs
       install -m 0755 ${S}/cgi.py ${D}/home/root/webserver
       install -m 0755 ${S}/index.html ${D}/home/root/webserver
       install -m 0755 ${S}/launch_server.sh ${D}/home/root/webserver
       install -m 0755 ${S}/server.py ${D}/home/root/webserver
       install -m 0755 ${S}/setup_gpio.sh ${D}/home/root/webserver
       install -m 0755 ${S}/stop_server.sh ${D}/home/root/webserver
       install -m 0755 ${S}/unexport_gpio.sh ${D}/home/root/webserver
       install -m 0755 ${S}/css/main.css ${D}/home/root/webserver/css
       install -m 0755 ${S}/html/sata_results.html ${D}/home/root/webserver/html
       install -m 0755 ${S}/html/usb3_results.html ${D}/home/root/webserver/html
       install -m 0755 ${S}/images/Avnet_logo_tagline_rgb.png ${D}/home/root/webserver/images
       install -m 0755 ${S}/images/board.jpg ${D}/home/root/webserver/images
       install -m 0755 ${S}/images/favicon.ico ${D}/home/root/webserver/images
       install -m 0755 ${S}/pdfs/Delkin_Devices_Product_Line.pdf ${D}/home/root/webserver/pdfs
}

do_install_append_uz () {
       install -m 0755 ${S}/images/ultrazed.png ${D}/home/root/webserver/images
}
do_install_append_uz3eg-iocc () {
       install -m 0755 ${S}/pdfs/5043-PB-AES-ZU3EG-1-SOM-G-V3.pdf ${D}/home/root/webserver/pdfs
       install -m 0755 ${S}/pdfs/5080-PB-AES-ZU-IOCC-G-V2e.pdf ${D}/home/root/webserver/pdfs
}

do_install_append_uz3eg-pciec () {
       install -m 0755 ${S}/pdfs/5043-PB-AES-ZU3EG-1-SOM-G-V3.pdf ${D}/home/root/webserver/pdfs
       install -m 0755 ${S}/pdfs/5081-PB-AES-ZU-PCIECC-G-V2d.pdf ${D}/home/root/webserver/pdfs
}

do_install_append_uz7ev-evcc () {
       install -m 0755 ${S}/pdfs/5342-pb-ultrazed-ev-som-v1.pdf ${D}/home/root/webserver/pdfs
       install -m 0755 ${S}/pdfs/5342-pb-ultrazed-ev-starter-kit-v1.pdf ${D}/home/root/webserver/pdfs
}

do_install_append_pz () {
       install -m 0755 ${S}/images/picozed.png ${D}/home/root/webserver/images
       install -m 0755 ${S}/pdfs/5048-PB-PDP-AES-Z7PZ-SOM-G-V2.pdf ${D}/home/root/webserver/pdfs
       install -m 0755 ${S}/pdfs/PB-AES-PZCC-FMC-V2-G-V1.pdf ${D}/home/root/webserver/pdfs
}

FILES_${PN} += "/home/root/webserver/cgi.py \
           /home/root/webserver/index.html \
           /home/root/webserver/launch_server.sh \
           /home/root/webserver/server.py \
           /home/root/webserver/setup_gpio.sh \
           /home/root/webserver/stop_server.sh \
           /home/root/webserver/unexport_gpio.sh \
           /home/root/webserver/css/main.css \
           /home/root/webserver/html/sata_results.html \
           /home/root/webserver/html/usb3_results.html \
           /home/root/webserver/images/Avnet_logo_tagline_rgb.png \
           /home/root/webserver/images/board.jpg \
           /home/root/webserver/images/favicon.ico \
           /home/root/webserver/pdfs/Delkin_Devices_Product_Line.pdf \
               "

FILES_${PN}_append_uz = "\
           /home/root/webserver/images/ultrazed.png \
               "
FILES_${PN}_append_uz3eg-iocc = "\
           /home/root/webserver/pdfs/5043-PB-AES-ZU3EG-1-SOM-G-V3.pdf \
           /home/root/webserver/pdfs/5080-PB-AES-ZU-IOCC-G-V2e.pdf \
               "
FILES_${PN}_append_uz3eg-pciec = "\
           /home/root/webserver/pdfs/5043-PB-AES-ZU3EG-1-SOM-G-V3.pdf \
           /home/root/webserver/pdfs/5081-PB-AES-ZU-PCIECC-G-V2d.pdf \
               "
FILES_${PN}_append_uz7ev-evcc = "\
           /home/root/webserver/pdfs/5342-pb-ultrazed-ev-som-v1.pdf \
           /home/root/webserver/pdfs/5342-pb-ultrazed-ev-starter-kit-v1.pdf \
               "

FILES_${PN}_append_pz = "\
           /home/root/webserver/images/picozed.png \
           /home/root/webserver/pdfs/5048-PB-PDP-AES-Z7PZ-SOM-G-V2.pdf \
           /home/root/webserver/pdfs/PB-AES-PZCC-FMC-V2-G-V1.pdf \
               "

repository: ubfx/meta-avnet

repo_name: ubfx/meta-avnet


text:
DESCRIPTION = "Python Serial Port Extension for Win32, Linux, BSD, Jython, IronPython"
HOMEPAGE = "http://pyserial.sourceforge.net/"
SECTION = "devel/python"
LICENSE = "PSF"
LIC_FILES_CHKSUM = "file://LICENSE.txt;md5=d88c706961680d5d232a4ae0879b1714"

SRCNAME = "pyserial"
PR = "r0"

SRC_URI = "https://pypi.python.org/packages/source/p/pyserial/${SRCNAME}-${PV}.tar.gz"
S = "${WORKDIR}/${SRCNAME}-${PV}"

#inherit setuptools
inherit distutils

COMPATIBLE_MACHINE = "raspberrypi"

SRC_URI[md5sum] = "cde799970b7c1ce1f7d6e9ceebe64c98"
SRC_URI[sha256sum] = "049dbcda0cd475d3be903e721d60889ee2cc4ec3b62892a81ecef144196413ed"

repository: xtacocorex/meta-rpi

repo_name: xtacocorex/meta-rpi

branch_name: refs/heads/jethro


text:
package converter

import "reflect"

type Converter interface {
	CovertStringToInterface(value string) (interface{}, error)
	CovertStringToPrimitiveTypeAndSetField(field reflect.Value, value string, isPtr bool) error
}

func StringConverterFactory(vType string) Converter {
	switch vType {
	case "string":
		return StringConverter{}
	case "int32":
		return Int32Converter{}
	case "int64":
		return Int64Converter{}
	case "float32":
		return Float32Converter{}
	case "float64":
		return Float32Converter{}
	case "bool":
		return BooleanConverter{}
	default:
		return nil
	}
}

repository: digitalocean/autoscaler

repo_name: digitalocean/autoscaler


text:
DESCRIPTION = "Framebuffer console driver for displaylink based usb devices"
LICENSE = "GPLv2"

PV = "0.2.3"

SRC_URI = "file://udlfb.c \
           file://udlfb.h \
           file://Makefile \
"

inherit module

S = "${WORKDIR}"

do_install() {
	install -d ${D}/lib/modules/${KERNEL_VERSION}/drivers/usb/
	install -m 0644 *.ko ${D}/lib/modules/${KERNEL_VERSION}/drivers/usb/
}


text:
package mysqldb

import (
	"errors"
	"log"
	"os"
	"strings"
	"time"

	"github.com/xxjwxc/public/dev"
	myerrors "github.com/xxjwxc/public/errors"
	"gorm.io/driver/clickhouse"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"

	"github.com/xxjwxc/public/mylog"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// MySqlDB ...
type MySqlDB struct {
	*gorm.DB
}

// OnInitDBOrm init MySqlDB
func OnInitDBOrm(dataSourceName string, maxIdleConns, maxOpenConns int, ignoreRecordNotFoundError bool) (orm *MySqlDB) {
	orm = new(MySqlDB)
	orm.OnGetDBOrm(dataSourceName, maxIdleConns, maxOpenConns, ignoreRecordNotFoundError)
	return
}

// OnGetDBOrm get gorm.db
func (i *MySqlDB) OnGetDBOrm(dataSourceName string, maxIdleConns, maxOpenConns int, ignoreRecordNotFoundError bool) *gorm.DB {
	if i.DB == nil {
		Default := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{
			SlowThreshold:             200 * time.Millisecond,
			LogLevel:                  logger.Warn,
			IgnoreRecordNotFoundError: ignoreRecordNotFoundError,
			Colorful:                  true,
		}) //
		dialector := mysql.Open(dataSourceName)
		if strings.Contains(dataSourceName, "clickhouse") {
			dialector = clickhouse.Open(dataSourceName)
		}
		var err error
		i.DB, err = gorm.Open(dialector, &gorm.Config{PrepareStmt: false,
			NamingStrategy: schema.NamingStrategy{SingularTable: true}, // 全局禁用表名复数
			Logger:         Default})                                   // logger.Default
		if err != nil {
			mylog.Error(myerrors.Wrap(err, "Got error when connect database:"+dataSourceName))
			return nil
		}

		sqlDB, _ := i.DB.DB()
		// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
		sqlDB.SetMaxIdleConns(maxIdleConns) // 空闲连接池中最大连接数

		// SetMaxOpenConns sets the maximum number of open connections to the database.
		sqlDB.SetMaxOpenConns(maxOpenConns) // 设置数据库的最大打开连接数。
	}

	// i.DB.SingularTable(true) //全局禁用表名复数
	if dev.IsDev() {
		i.DB = i.DB.Debug()
	} else {
		i.DB.Logger = GetDBlog(ignoreRecordNotFoundError)
	}

	return i.DB
}

// OnDestoryDB destorydb
func (i *MySqlDB) OnDestoryDB() {
	if i.DB != nil {
		sqldb, _ := i.DB.DB()
		sqldb.Close()
		i.DB = nil
	}
}

// IsNotFound 判断错误是否未找到
func (i *MySqlDB) IsNotFound(errs ...error) bool {
	if len(errs) > 0 {
		for _, err := range errs {
			if err == gorm.ErrRecordNotFound {
				return true
			}
		}
	}
	return i.RecordNotFound()
}

// RecordNotFound check if returning ErrRecordNotFound error
func (i *MySqlDB) RecordNotFound() bool {
	return !errors.Is(i.Error, gorm.ErrRecordNotFound)
}

// Commit 自动提交(如果有错，Rollback)
func (i *MySqlDB) Commit(db *gorm.DB) {
	if db.Error != nil {
		db.Rollback() // 回滚
	} else {
		db.Commit()
	}
}

repository: xxjwxc/public

repo_name: xxjwxc/public