_id stringlengths 2 7 | title stringlengths 1 118 | partition stringclasses 3
values | text stringlengths 52 85.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q18000 | PanicOnError | train | func PanicOnError(err error, msg string) {
if revErr, ok := err.(*Error); (ok && revErr != nil) || (!ok && err != nil) {
Logger.Panicf("Abort: %s: %s %s", msg, revErr, err)
}
} | go | {
"resource": ""
} |
q18001 | CopyDir | train | func CopyDir(destDir, srcDir string, data map[string]interface{}) error {
if !DirExists(srcDir) {
return nil
}
return fsWalk(srcDir, srcDir, func(srcPath string, info os.FileInfo, err error) error {
// Get the relative path from the source base, and the corresponding path in
// the dest directory.
relSrcPath... | go | {
"resource": ""
} |
q18002 | TarGzDir | train | func TarGzDir(destFilename, srcDir string) (name string, err error) {
zipFile, err := os.Create(destFilename)
if err != nil {
return "", NewBuildIfError(err, "Failed to create archive", "file", destFilename)
}
defer func() {
_ = zipFile.Close()
}()
gzipWriter := gzip.NewWriter(zipFile)
defer func() {
_ =... | go | {
"resource": ""
} |
q18003 | Empty | train | func Empty(dirname string) bool {
dir, err := os.Open(dirname)
if err != nil {
Logger.Infof("error opening directory: %s", err)
}
defer func() {
_ = dir.Close()
}()
results, _ := dir.Readdir(1)
return len(results) == 0
} | go | {
"resource": ""
} |
q18004 | FindSrcPaths | train | func FindSrcPaths(appImportPath, revelImportPath string, packageResolver func(pkgName string) error) (appSourcePath, revelSourcePath string, err error) {
var (
gopaths = filepath.SplitList(build.Default.GOPATH)
goroot = build.Default.GOROOT
)
if len(gopaths) == 0 {
err = errors.New("GOPATH environment variab... | go | {
"resource": ""
} |
q18005 | intOrZero | train | func (v *Version) intOrZero(input string) (value int) {
if input != "" {
value, _ = strconv.Atoi(input)
}
return value
} | go | {
"resource": ""
} |
q18006 | CompatibleFramework | train | func (v *Version) CompatibleFramework(c *CommandConfig) error {
for i, rv := range frameworkCompatibleRangeList {
start, _ := ParseVersion(rv[0])
end, _ := ParseVersion(rv[1])
if !v.Newer(start) || v.Newer(end) {
continue
}
// Framework is older then 0.20, turn on historic mode
if i == 0 {
c.Historic... | go | {
"resource": ""
} |
q18007 | MajorNewer | train | func (v *Version) MajorNewer(o *Version) bool {
if v.Major != o.Major {
return v.Major > o.Major
}
return false
} | go | {
"resource": ""
} |
q18008 | MinorNewer | train | func (v *Version) MinorNewer(o *Version) bool {
if v.Major != o.Major {
return v.Major > o.Major
}
if v.Minor != o.Minor {
return v.Minor > o.Minor
}
return false
} | go | {
"resource": ""
} |
q18009 | Newer | train | func (v *Version) Newer(o *Version) bool {
if v.Major != o.Major {
return v.Major > o.Major
}
if v.Minor != o.Minor {
return v.Minor > o.Minor
}
if v.Maintenance != o.Maintenance {
return v.Maintenance > o.Maintenance
}
return false
} | go | {
"resource": ""
} |
q18010 | VersionString | train | func (v *Version) VersionString() string {
return fmt.Sprintf("%s%d.%d.%d%s", v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix)
} | go | {
"resource": ""
} |
q18011 | String | train | func (v *Version) String() string {
return fmt.Sprintf("Version: %s%d.%d.%d%s\nBuild Date: %s\n Minimium Go Version: %s",
v.Prefix, v.Major, v.Minor, v.Maintenance, v.Suffix, v.BuildDate, v.MinGoVersion)
} | go | {
"resource": ""
} |
q18012 | ServeHTTP | train | func (h *Harness) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Don't rebuild the app for favicon requests.
if lastRequestHadError > 0 && r.URL.Path == "/favicon.ico" {
return
}
// Flush any change events and rebuild app if necessary.
// Render an error page if the rebuild / restart failed.
err := h.w... | go | {
"resource": ""
} |
q18013 | NewHarness | train | func NewHarness(c *model.CommandConfig, paths *model.RevelContainer, runMode string, noProxy bool) *Harness {
// Get a template loader to render errors.
// Prefer the app's views/errors directory, and fall back to the stock error pages.
//revel.MainTemplateLoader = revel.NewTemplateLoader(
// []string{filepath.Join... | go | {
"resource": ""
} |
q18014 | Refresh | train | func (h *Harness) Refresh() (err *utils.Error) {
// Allow only one thread to rebuild the process
// If multiple requests to rebuild are queued only the last one is executed on
// So before a build is started we wait for a second to determine if
// more requests for a build are triggered.
// Once no more requests a... | go | {
"resource": ""
} |
q18015 | WatchDir | train | func (h *Harness) WatchDir(info os.FileInfo) bool {
return !utils.ContainsString(doNotWatch, info.Name())
} | go | {
"resource": ""
} |
q18016 | Run | train | func (h *Harness) Run() {
var paths []string
if h.paths.Config.BoolDefault("watch.gopath", false) {
gopaths := filepath.SplitList(build.Default.GOPATH)
paths = append(paths, gopaths...)
}
paths = append(paths, h.paths.CodePaths...)
h.watcher = watcher.NewWatcher(h.paths, false)
h.watcher.Listen(h, paths...)
... | go | {
"resource": ""
} |
q18017 | getFreePort | train | func getFreePort() (port int) {
conn, err := net.Listen("tcp", ":0")
if err != nil {
utils.Logger.Fatal("Unable to fetch a freee port address", "error", err)
}
port = conn.Addr().(*net.TCPAddr).Port
err = conn.Close()
if err != nil {
utils.Logger.Fatal("Unable to close port", "error", err)
}
return port
} | go | {
"resource": ""
} |
q18018 | appendStruct | train | func appendStruct(fileName string, specs []*model.TypeInfo, pkgImportPath string, pkg *ast.Package, decl ast.Decl, imports map[string]string, fset *token.FileSet) []*model.TypeInfo {
// Filter out non-Struct type declarations.
spec, found := getStructTypeDecl(decl, fset)
if !found {
return specs
}
structType :=... | go | {
"resource": ""
} |
q18019 | appendSourceInfo | train | func appendSourceInfo(srcInfo1, srcInfo2 *model.SourceInfo) *model.SourceInfo {
if srcInfo1 == nil {
return srcInfo2
}
srcInfo1.StructSpecs = append(srcInfo1.StructSpecs, srcInfo2.StructSpecs...)
srcInfo1.InitImportPaths = append(srcInfo1.InitImportPaths, srcInfo2.InitImportPaths...)
for k, v := range srcInfo2.... | go | {
"resource": ""
} |
q18020 | NewBuildError | train | func NewBuildError(message string, args ...interface{}) (b *BuildError) {
Logger.Info(message, args...)
b = &BuildError{}
b.Message = message
b.Args = args
b.Stack = logger.NewCallStack()
Logger.Info("Stack", "stack", b.Stack)
return b
} | go | {
"resource": ""
} |
q18021 | NewBuildIfError | train | func NewBuildIfError(err error, message string, args ...interface{}) (b error) {
if err != nil {
if berr, ok := err.(*BuildError); ok {
// This is already a build error so just append the args
berr.Args = append(berr.Args, args...)
return berr
} else {
args = append(args, "error", err.Error())
b = N... | go | {
"resource": ""
} |
q18022 | ProcessSource | train | func ProcessSource(paths *model.RevelContainer) (_ *model.SourceInfo, compileError error) {
pc := &processContainer{paths: paths}
for _, root := range paths.CodePaths {
rootImportPath := importPathFromPath(root, paths.BasePath)
if rootImportPath == "" {
utils.Logger.Info("Skipping empty code path", "path", roo... | go | {
"resource": ""
} |
q18023 | processPath | train | func (pc *processContainer) processPath(path string, info os.FileInfo, err error) error {
if err != nil {
utils.Logger.Error("Error scanning app source:", "error", err)
return nil
}
if !info.IsDir() || info.Name() == "tmp" {
return nil
}
// Get the import path of the package.
pkgImportPath := pc.rootImpor... | go | {
"resource": ""
} |
q18024 | processPackage | train | func processPackage(fset *token.FileSet, pkgImportPath, pkgPath string, pkg *ast.Package) *model.SourceInfo {
var (
structSpecs []*model.TypeInfo
initImportPaths []string
methodSpecs = make(methodMap)
validationKeys = make(map[string]map[int]string)
scanControllers = strings.HasSuffix(pkgImportPath... | go | {
"resource": ""
} |
q18025 | getStructTypeDecl | train | func getStructTypeDecl(decl ast.Decl, fset *token.FileSet) (spec *ast.TypeSpec, found bool) {
genDecl, ok := decl.(*ast.GenDecl)
if !ok {
return
}
if genDecl.Tok != token.TYPE {
return
}
if len(genDecl.Specs) == 0 {
utils.Logger.Warn("Warn: Surprising: %s:%d Decl contains no specifications", fset.Position... | go | {
"resource": ""
} |
q18026 | NewApp | train | func NewApp(binPath string, paths *model.RevelContainer) *App {
return &App{BinaryPath: binPath, Paths: paths, Port: paths.HTTPPort}
} | go | {
"resource": ""
} |
q18027 | Cmd | train | func (a *App) Cmd(runMode string) AppCmd {
a.cmd = NewAppCmd(a.BinaryPath, a.Port, runMode, a.Paths)
return a.cmd
} | go | {
"resource": ""
} |
q18028 | NewAppCmd | train | func NewAppCmd(binPath string, port int, runMode string, paths *model.RevelContainer) AppCmd {
cmd := exec.Command(binPath,
fmt.Sprintf("-port=%d", port),
fmt.Sprintf("-importPath=%s", paths.ImportPath),
fmt.Sprintf("-runMode=%s", runMode))
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
return AppCmd{cmd}
} | go | {
"resource": ""
} |
q18029 | Start | train | func (cmd AppCmd) Start(c *model.CommandConfig) error {
listeningWriter := &startupListeningWriter{os.Stdout, make(chan bool), c, &bytes.Buffer{}}
cmd.Stdout = listeningWriter
utils.Logger.Info("Exec app:", "path", cmd.Path, "args", cmd.Args, "dir", cmd.Dir, "env", cmd.Env)
utils.CmdInit(cmd.Cmd, c.AppPath)
if err... | go | {
"resource": ""
} |
q18030 | Run | train | func (cmd AppCmd) Run() {
utils.Logger.Info("Exec app:", "path", cmd.Path, "args", cmd.Args)
if err := cmd.Cmd.Run(); err != nil {
utils.Logger.Fatal("Error running:", "error", err)
}
} | go | {
"resource": ""
} |
q18031 | Kill | train | func (cmd AppCmd) Kill() {
if cmd.Cmd != nil && (cmd.ProcessState == nil || !cmd.ProcessState.Exited()) {
// Windows appears to send the kill to all threads, shutting down the
// server before this can, this check will ensure the process is still running
if _, err := os.FindProcess(int(cmd.Process.Pid));err!=ni... | go | {
"resource": ""
} |
q18032 | Write | train | func (w *startupListeningWriter) Write(p []byte) (int, error) {
if w.notifyReady != nil && bytes.Contains(p, []byte("Revel engine is listening on")) {
w.notifyReady <- true
w.notifyReady = nil
}
if w.c.HistoricMode {
if w.notifyReady != nil && bytes.Contains(p, []byte("Listening on")) {
w.notifyReady <- tru... | go | {
"resource": ""
} |
q18033 | NewWatcher | train | func NewWatcher(paths *model.RevelContainer, eagerRefresh bool) *Watcher {
return &Watcher{
forceRefresh: true,
lastError: -1,
paths: paths,
refreshTimerMS: time.Duration(paths.Config.IntDefault("watch.rebuild.delay", 10)),
eagerRefresh: eagerRefresh ||
paths.DevMode &&
paths.Config.Bo... | go | {
"resource": ""
} |
q18034 | NotifyWhenUpdated | train | func (w *Watcher) NotifyWhenUpdated(listener Listener, watcher *fsnotify.Watcher) {
for {
select {
case ev := <-watcher.Events:
if w.rebuildRequired(ev, listener) {
if w.serial {
// Serialize listener.Refresh() calls.
w.notifyMutex.Lock()
if err := listener.Refresh(); err != nil {
uti... | go | {
"resource": ""
} |
q18035 | notifyInProcess | train | func (w *Watcher) notifyInProcess(listener Listener) (err *utils.Error) {
shouldReturn := false
// This code block ensures that either a timer is created
// or that a process would be added the the h.refreshChannel
func() {
w.timerMutex.Lock()
defer w.timerMutex.Unlock()
// If we are in the process of a rebui... | go | {
"resource": ""
} |
q18036 | updateCleanConfig | train | func updateCleanConfig(c *model.CommandConfig, args []string) bool {
c.Index = model.CLEAN
if len(args) == 0 {
fmt.Fprintf(os.Stderr, cmdClean.Long)
return false
}
c.Clean.ImportPath = args[0]
return true
} | go | {
"resource": ""
} |
q18037 | cleanApp | train | func cleanApp(c *model.CommandConfig) (err error) {
appPkg, err := build.Import(c.ImportPath, "", build.FindOnly)
if err != nil {
utils.Logger.Fatal("Abort: Failed to find import path:", "error", err)
}
purgeDirs := []string{
filepath.Join(appPkg.Dir, "app", "tmp"),
filepath.Join(appPkg.Dir, "app", "routes")... | go | {
"resource": ""
} |
q18038 | generateSecret | train | func generateSecret() string {
chars := make([]byte, 64)
for i := 0; i < 64; i++ {
chars[i] = alphaNumeric[rand.Intn(len(alphaNumeric))]
}
return string(chars)
} | go | {
"resource": ""
} |
q18039 | setApplicationPath | train | func setApplicationPath(c *model.CommandConfig) (err error) {
// revel/revel#1014 validate relative path, we cannot use built-in functions
// since Go import path is valid relative path too.
// so check basic part of the path, which is "."
if filepath.IsAbs(c.ImportPath) || strings.HasPrefix(c.ImportPath, ".") {
... | go | {
"resource": ""
} |
q18040 | setSkeletonPath | train | func setSkeletonPath(c *model.CommandConfig) (err error) {
if len(c.New.SkeletonPath) == 0 {
c.New.SkeletonPath = "https://" + RevelSkeletonsImportPath + ":basic/bootstrap4"
}
// First check to see the protocol of the string
sp, err := url.Parse(c.New.SkeletonPath)
if err == nil {
utils.Logger.Info("Detected ... | go | {
"resource": ""
} |
q18041 | newLoadFromGit | train | func newLoadFromGit(c *model.CommandConfig, sp *url.URL) (err error) {
// This method indicates we need to fetch from a repository using git
// Execute "git clone get <pkg>"
targetPath := filepath.Join(os.TempDir(), "revel", "skeleton")
os.RemoveAll(targetPath)
pathpart := strings.Split(sp.Path, ":")
getCmd := ex... | go | {
"resource": ""
} |
q18042 | Retry | train | func Retry(format string, args ...interface{}) {
// Ensure the user's command prompt starts on the next line.
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
fmt.Fprintf(os.Stderr, format, args...)
panic(format) // Panic instead of os.Exit so that deferred will run.
} | go | {
"resource": ""
} |
q18043 | New | train | func New(key string) *Client {
c := &Client{
Endpoint: Endpoint,
Interval: 5 * time.Second,
Size: 250,
Logger: log.New(os.Stderr, "segment ", log.LstdFlags),
Verbose: false,
Client: *http.DefaultClient,
key: key,
msgs: make(chan interface{}, 100),
quit: make(chan struct{}),
sh... | go | {
"resource": ""
} |
q18044 | Alias | train | func (c *Client) Alias(msg *Alias) error {
if msg.UserId == "" {
return errors.New("You must pass a 'userId'.")
}
if msg.PreviousId == "" {
return errors.New("You must pass a 'previousId'.")
}
msg.Type = "alias"
c.queue(msg)
return nil
} | go | {
"resource": ""
} |
q18045 | Page | train | func (c *Client) Page(msg *Page) error {
if msg.UserId == "" && msg.AnonymousId == "" {
return errors.New("You must pass either an 'anonymousId' or 'userId'.")
}
msg.Type = "page"
c.queue(msg)
return nil
} | go | {
"resource": ""
} |
q18046 | Group | train | func (c *Client) Group(msg *Group) error {
if msg.GroupId == "" {
return errors.New("You must pass a 'groupId'.")
}
if msg.UserId == "" && msg.AnonymousId == "" {
return errors.New("You must pass either an 'anonymousId' or 'userId'.")
}
msg.Type = "group"
c.queue(msg)
return nil
} | go | {
"resource": ""
} |
q18047 | Track | train | func (c *Client) Track(msg *Track) error {
if msg.Event == "" {
return errors.New("You must pass 'event'.")
}
if msg.UserId == "" && msg.AnonymousId == "" {
return errors.New("You must pass either an 'anonymousId' or 'userId'.")
}
msg.Type = "track"
c.queue(msg)
return nil
} | go | {
"resource": ""
} |
q18048 | queue | train | func (c *Client) queue(msg message) {
c.once.Do(c.startLoop)
msg.setMessageId(c.uid())
msg.setTimestamp(timestamp(c.now()))
c.msgs <- msg
} | go | {
"resource": ""
} |
q18049 | Close | train | func (c *Client) Close() error {
c.once.Do(c.startLoop)
c.quit <- struct{}{}
close(c.msgs)
<-c.shutdown
return nil
} | go | {
"resource": ""
} |
q18050 | send | train | func (c *Client) send(msgs []interface{}) error {
if len(msgs) == 0 {
return nil
}
batch := new(Batch)
batch.Messages = msgs
batch.MessageId = c.uid()
batch.SentAt = timestamp(c.now())
batch.Context = DefaultContext
b, err := json.Marshal(batch)
if err != nil {
return fmt.Errorf("error marshalling msgs: ... | go | {
"resource": ""
} |
q18051 | upload | train | func (c *Client) upload(b []byte) error {
url := c.Endpoint + "/v1/batch"
req, err := http.NewRequest("POST", url, bytes.NewReader(b))
if err != nil {
return fmt.Errorf("error creating request: %s", err)
}
req.Header.Add("User-Agent", "analytics-go (version: "+Version+")")
req.Header.Add("Content-Type", "appli... | go | {
"resource": ""
} |
q18052 | loop | train | func (c *Client) loop() {
var msgs []interface{}
tick := time.NewTicker(c.Interval)
for {
select {
case msg := <-c.msgs:
c.verbose("buffer (%d/%d) %v", len(msgs), c.Size, msg)
msgs = append(msgs, msg)
if len(msgs) == c.Size {
c.verbose("exceeded %d messages – flushing", c.Size)
c.sendAsync(msgs... | go | {
"resource": ""
} |
q18053 | verbose | train | func (c *Client) verbose(msg string, args ...interface{}) {
if c.Verbose {
c.Logger.Printf(msg, args...)
}
} | go | {
"resource": ""
} |
q18054 | logf | train | func (c *Client) logf(msg string, args ...interface{}) {
c.Logger.Printf(msg, args...)
} | go | {
"resource": ""
} |
q18055 | setTimestamp | train | func (m *Message) setTimestamp(s string) {
if m.Timestamp == "" {
m.Timestamp = s
}
} | go | {
"resource": ""
} |
q18056 | setMessageId | train | func (m *Message) setMessageId(s string) {
if m.MessageId == "" {
m.MessageId = s
}
} | go | {
"resource": ""
} |
q18057 | New | train | func New(db *gorm.DB) i18n.Backend {
db.AutoMigrate(&Translation{})
if err := db.Model(&Translation{}).AddUniqueIndex("idx_translations_key_with_locale", "locale", "key").Error; err != nil {
fmt.Printf("Failed to create unique index for translations key & locale, got: %v\n", err.Error())
}
return &Backend{DB: db}... | go | {
"resource": ""
} |
q18058 | LoadTranslations | train | func (backend *Backend) LoadTranslations() (translations []*i18n.Translation) {
backend.DB.Find(&translations)
return translations
} | go | {
"resource": ""
} |
q18059 | SaveTranslation | train | func (backend *Backend) SaveTranslation(t *i18n.Translation) error {
return backend.DB.Where(Translation{Key: t.Key, Locale: t.Locale}).
Assign(Translation{Value: t.Value}).
FirstOrCreate(&Translation{}).Error
} | go | {
"resource": ""
} |
q18060 | DeleteTranslation | train | func (backend *Backend) DeleteTranslation(t *i18n.Translation) error {
return backend.DB.Where(Translation{Key: t.Key, Locale: t.Locale}).Delete(&Translation{}).Error
} | go | {
"resource": ""
} |
q18061 | New | train | func New(paths ...string) *Backend {
backend := &Backend{}
var files []string
for _, p := range paths {
if file, err := os.Open(p); err == nil {
defer file.Close()
if fileInfo, err := file.Stat(); err == nil {
if fileInfo.IsDir() {
yamlFiles, _ := filepath.Glob(filepath.Join(p, "*.yaml"))
file... | go | {
"resource": ""
} |
q18062 | NewWithWalk | train | func NewWithWalk(paths ...string) i18n.Backend {
backend := &Backend{}
var files []string
for _, p := range paths {
filepath.Walk(p, func(path string, fileInfo os.FileInfo, err error) error {
if isYamlFile(fileInfo) {
files = append(files, path)
}
return nil
})
}
for _, file := range files {
if... | go | {
"resource": ""
} |
q18063 | NewWithFilesystem | train | func NewWithFilesystem(fss ...http.FileSystem) i18n.Backend {
backend := &Backend{}
for _, fs := range fss {
backend.contents = append(backend.contents, walkFilesystem(fs, nil, "/")...)
}
return backend
} | go | {
"resource": ""
} |
q18064 | LoadYAMLContent | train | func (backend *Backend) LoadYAMLContent(content []byte) (translations []*i18n.Translation, err error) {
var slice yaml.MapSlice
if err = yaml.Unmarshal(content, &slice); err == nil {
for _, item := range slice {
translations = append(translations, loadTranslationsFromYaml(item.Key.(string) /* locale */, item.Va... | go | {
"resource": ""
} |
q18065 | LoadTranslations | train | func (backend *Backend) LoadTranslations() (translations []*i18n.Translation) {
for _, content := range backend.contents {
if results, err := backend.LoadYAMLContent(content); err == nil {
translations = append(translations, results...)
} else {
panic(err)
}
}
return translations
} | go | {
"resource": ""
} |
q18066 | New | train | func New(backends ...Backend) *I18n {
i18n := &I18n{Backends: backends, cacheStore: memory.New()}
i18n.loadToCacheStore()
return i18n
} | go | {
"resource": ""
} |
q18067 | SetCacheStore | train | func (i18n *I18n) SetCacheStore(cacheStore cache.CacheStoreInterface) {
i18n.cacheStore = cacheStore
i18n.loadToCacheStore()
} | go | {
"resource": ""
} |
q18068 | AddTranslation | train | func (i18n *I18n) AddTranslation(translation *Translation) error {
return i18n.cacheStore.Set(cacheKey(translation.Locale, translation.Key), translation)
} | go | {
"resource": ""
} |
q18069 | SaveTranslation | train | func (i18n *I18n) SaveTranslation(translation *Translation) error {
for _, backend := range i18n.Backends {
if backend.SaveTranslation(translation) == nil {
i18n.AddTranslation(translation)
return nil
}
}
return errors.New("failed to save translation")
} | go | {
"resource": ""
} |
q18070 | DeleteTranslation | train | func (i18n *I18n) DeleteTranslation(translation *Translation) (err error) {
for _, backend := range i18n.Backends {
backend.DeleteTranslation(translation)
}
return i18n.cacheStore.Delete(cacheKey(translation.Locale, translation.Key))
} | go | {
"resource": ""
} |
q18071 | Scope | train | func (i18n *I18n) Scope(scope string) admin.I18n {
return &I18n{cacheStore: i18n.cacheStore, scope: scope, value: i18n.value, Backends: i18n.Backends, Resource: i18n.Resource, FallbackLocales: i18n.FallbackLocales, fallbackLocales: i18n.fallbackLocales}
} | go | {
"resource": ""
} |
q18072 | Fallbacks | train | func (i18n *I18n) Fallbacks(locale ...string) admin.I18n {
return &I18n{cacheStore: i18n.cacheStore, scope: i18n.scope, value: i18n.value, Backends: i18n.Backends, Resource: i18n.Resource, FallbackLocales: i18n.FallbackLocales, fallbackLocales: locale}
} | go | {
"resource": ""
} |
q18073 | T | train | func (i18n *I18n) T(locale, key string, args ...interface{}) template.HTML {
var (
value = i18n.value
translationKey = key
fallbackLocales = i18n.fallbackLocales
)
if locale == "" {
locale = Default
}
if locales, ok := i18n.FallbackLocales[locale]; ok {
fallbackLocales = append(fallbackLocal... | go | {
"resource": ""
} |
q18074 | FuncMap | train | func FuncMap(I18n *i18n.I18n, locale string, enableInlineEdit bool) template.FuncMap {
return template.FuncMap{
"t": InlineEdit(I18n, locale, enableInlineEdit),
}
} | go | {
"resource": ""
} |
q18075 | InlineEdit | train | func InlineEdit(I18n *i18n.I18n, locale string, isInline bool) func(string, ...interface{}) template.HTML {
return func(key string, args ...interface{}) template.HTML {
// Get Translation Value
var value template.HTML
var defaultValue string
if len(args) > 0 {
if args[0] == nil {
defaultValue = key
}... | go | {
"resource": ""
} |
q18076 | AsFloatBuffer | train | func (b *PCMBuffer) AsFloatBuffer() *FloatBuffer {
newB := &FloatBuffer{}
newB.Data = b.AsF64()
if b.Format != nil {
newB.Format = &Format{
NumChannels: b.Format.NumChannels,
SampleRate: b.Format.SampleRate,
}
}
return newB
} | go | {
"resource": ""
} |
q18077 | AsIntBuffer | train | func (b *PCMBuffer) AsIntBuffer() *IntBuffer {
newB := &IntBuffer{}
newB.Data = b.AsInt()
if b.Format != nil {
newB.Format = &Format{
NumChannels: b.Format.NumChannels,
SampleRate: b.Format.SampleRate,
}
}
return newB
} | go | {
"resource": ""
} |
q18078 | AsI8 | train | func (b *PCMBuffer) AsI8() (out []int8) {
if b == nil {
return nil
}
switch b.DataType {
case DataTypeI8:
return b.I8
case DataTypeI16:
out = make([]int8, len(b.I16))
for i := 0; i < len(b.I16); i++ {
out[i] = int8(b.I16[i])
}
case DataTypeI32:
out = make([]int8, len(b.I32))
for i := 0; i < len(b... | go | {
"resource": ""
} |
q18079 | AsF64 | train | func (b *PCMBuffer) AsF64() (out []float64) {
if b == nil {
return nil
}
switch b.DataType {
case DataTypeI8:
bitDepth := b.calculateIntBitDepth()
factor := math.Pow(2, 8*float64(bitDepth/8)-1)
out = make([]float64, len(b.I8))
for i := 0; i < len(b.I8); i++ {
out[i] = float64(int64(b.I8[i])) / factor
... | go | {
"resource": ""
} |
q18080 | calculateIntBitDepth | train | func (b *PCMBuffer) calculateIntBitDepth() uint8 {
if b == nil {
return 0
}
bitDepth := b.SourceBitDepth
if bitDepth != 0 {
return bitDepth
}
var max int64
switch b.DataType {
case DataTypeI8:
var i8max int8
for _, s := range b.I8 {
if s > i8max {
i8max = s
}
}
max = int64(i8max)
case Dat... | go | {
"resource": ""
} |
q18081 | AsFloat32Buffer | train | func (buf *IntBuffer) AsFloat32Buffer() *Float32Buffer {
newB := &Float32Buffer{}
newB.Data = make([]float32, len(buf.Data))
max := int64(0)
// try to guess the bit depths without knowing the source
if buf.SourceBitDepth == 0 {
for _, s := range buf.Data {
if int64(s) > max {
max = int64(s)
}
}
buf... | go | {
"resource": ""
} |
q18082 | IEEEFloatToInt | train | func IEEEFloatToInt(b [10]byte) int {
var i uint32
// Negative number
if (b[0] & 0x80) == 1 {
return 0
}
// Less than 1
if b[0] <= 0x3F {
return 1
}
// Too big
if b[0] > 0x40 {
return 67108864
}
// Still too big
if b[0] == 0x40 && b[1] > 0x1C {
return 800000000
}
i = (uint32(b[2]) << 23) | (ui... | go | {
"resource": ""
} |
q18083 | IntToIEEEFloat | train | func IntToIEEEFloat(i int) [10]byte {
b := [10]byte{}
num := float64(i)
var sign int
var expon int
var fMant, fsMant float64
var hiMant, loMant uint
if num < 0 {
sign = 0x8000
} else {
sign = 0
}
if num == 0 {
expon = 0
hiMant = 0
loMant = 0
} else {
fMant, expon = math.Frexp(num)
if (expon ... | go | {
"resource": ""
} |
q18084 | Uint24to32 | train | func Uint24to32(bytes []byte) uint32 {
var output uint32
output |= uint32(bytes[2]) << 0
output |= uint32(bytes[1]) << 8
output |= uint32(bytes[0]) << 16
return output
} | go | {
"resource": ""
} |
q18085 | Int24BETo32 | train | func Int24BETo32(bytes []byte) int32 {
if len(bytes) < 3 {
return 0
}
ss := int32(0xFF&bytes[0])<<16 | int32(0xFF&bytes[1])<<8 | int32(0xFF&bytes[2])
if (ss & 0x800000) > 0 {
ss |= ^0xffffff
}
return ss
} | go | {
"resource": ""
} |
q18086 | Int24LETo32 | train | func Int24LETo32(bytes []byte) int32 {
if len(bytes) < 3 {
return 0
}
ss := int32(bytes[0]) | int32(bytes[1])<<8 | int32(bytes[2])<<16
if (ss & 0x800000) > 0 {
ss |= ^0xffffff
}
return ss
} | go | {
"resource": ""
} |
q18087 | Uint32toUint24Bytes | train | func Uint32toUint24Bytes(n uint32) []byte {
bytes := make([]byte, 3)
bytes[0] = byte(n >> 16)
bytes[1] = byte(n >> 8)
bytes[2] = byte(n >> 0)
return bytes
} | go | {
"resource": ""
} |
q18088 | Int32toInt24LEBytes | train | func Int32toInt24LEBytes(n int32) []byte {
bytes := make([]byte, 3)
if (n & 0x800000) > 0 {
n |= ^0xffffff
}
bytes[2] = byte(n >> 16)
bytes[1] = byte(n >> 8)
bytes[0] = byte(n >> 0)
return bytes
} | go | {
"resource": ""
} |
q18089 | Int32toInt24BEBytes | train | func Int32toInt24BEBytes(n int32) []byte {
bytes := make([]byte, 3)
if (n & 0x800000) > 0 {
n |= ^0xffffff
}
bytes[0] = byte(n >> 16)
bytes[1] = byte(n >> 8)
bytes[2] = byte(n >> 0)
return bytes
} | go | {
"resource": ""
} |
q18090 | AsFloatBuffer | train | func (buf *Float32Buffer) AsFloatBuffer() *FloatBuffer {
newB := &FloatBuffer{}
newB.Data = make([]float64, len(buf.Data))
for i := 0; i < len(buf.Data); i++ {
newB.Data[i] = float64(buf.Data[i])
}
newB.Format = &Format{
NumChannels: buf.Format.NumChannels,
SampleRate: buf.Format.SampleRate,
}
return newB... | go | {
"resource": ""
} |
q18091 | TraceHandler | train | func (s *Sensor) TraceHandler(name, pattern string, handler http.HandlerFunc) (string, http.HandlerFunc) {
return pattern, s.TracingHandler(name, handler)
} | go | {
"resource": ""
} |
q18092 | TracingHandler | train | func (s *Sensor) TracingHandler(name string, handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
s.WithTracingContext(name, w, req, func(span ot.Span, ctx context.Context) {
// Capture response code for span
hooks := httpsnoop.Hooks{
WriteHeader: func(next h... | go | {
"resource": ""
} |
q18093 | TracingHttpRequest | train | func (s *Sensor) TracingHttpRequest(name string, parent, req *http.Request, client http.Client) (res *http.Response, err error) {
var span ot.Span
if parentSpan, ok := parent.Context().Value("parentSpan").(ot.Span); ok {
span = s.tracer.StartSpan("client", ot.ChildOf(parentSpan.Context()))
} else {
span = s.trac... | go | {
"resource": ""
} |
q18094 | WithTracingContext | train | func (s *Sensor) WithTracingContext(name string, w http.ResponseWriter, req *http.Request, f ContextSensitiveFunc) {
s.WithTracingSpan(name, w, req, func(span ot.Span) {
ctx := context.WithValue(req.Context(), "parentSpan", span)
f(span, ctx)
})
} | go | {
"resource": ""
} |
q18095 | EumSnippet | train | func EumSnippet(apiKey string, traceID string, meta map[string]string) string {
if len(apiKey) == 0 || len(traceID) == 0 {
return ""
}
b, err := ioutil.ReadFile(eumTemplate)
if err != nil {
return ""
}
var snippet = string(b)
var metaBuffer bytes.Buffer
snippet = strings.Replace(snippet, "$apiKey", api... | go | {
"resource": ""
} |
q18096 | Header2ID | train | func Header2ID(header string) (int64, error) {
// FIXME: We're assuming LittleEndian here
// Parse unsigned 64 bit hex string into unsigned 64 bit base 10 integer
if unsignedID, err := strconv.ParseUint(header, 16, 64); err == nil {
// Write out _unsigned_ 64bit integer to byte buffer
buf := new(bytes.Buffer)
... | go | {
"resource": ""
} |
q18097 | hexGatewayToAddr | train | func hexGatewayToAddr(gateway []rune) (string, error) {
// gateway address is encoded in reverse order in hex
if len(gateway) != 8 {
return "", errors.New("invalid gateway length")
}
var octets [4]uint8
for i, hexOctet := range [4]string{
string(gateway[6:8]), // first octet of IP Address
string(gateway[4:6... | go | {
"resource": ""
} |
q18098 | SendDefaultServiceEvent | train | func SendDefaultServiceEvent(title string, text string, sev severity, duration time.Duration) {
if sensor == nil {
// Since no sensor was initialized, there is no default service (as
// configured on the sensor) so we send blank.
SendServiceEvent("", title, text, sev, duration)
} else {
SendServiceEvent(senso... | go | {
"resource": ""
} |
q18099 | SendServiceEvent | train | func SendServiceEvent(service string, title string, text string, sev severity, duration time.Duration) {
sendEvent(&EventData{
Title: title,
Text: text,
Severity: int(sev),
Plugin: ServicePlugin,
ID: service,
Host: ServiceHost,
Duration: int(duration / time.Millisecond),
})
} | go | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.